Servlet的5种方式实现表单提交(注册小功能),后台获取表单数据实例

用servlet实现一个注册的小功能 ,后台获取数据。

注册页面:

  

注册页面代码 :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <form action="/RequestDemo/RequestDemo3" method="post">
    用户名:<input type="text" name="userName"><br/>
    密码:<input type="text" name="pwd"><br/>
    性别:<input type="radio" name="sex" value="男" checked="checked">男
      <input type="radio" name="sex" value="女">女<br/>
    爱好:<input type="checkbox" name="hobby" value="足球">足球
      <input type="checkbox" name="hobby" value="篮球">篮球
      <input type="checkbox" name="hobby" value="排球">排球
      <input type="checkbox" name="hobby" value="羽毛球">羽毛球<br/>
    所在城市:<select name="city">
         <option>---请选择---</option>
         <option value="bj">北京</option>
         <option value="sh">上海</option>
         <option value="sy">沈阳</option>
        </select>
        <br/>
    <input type="submit" value="点击注册">
  </form>
</body>
</html>

人员实体类: 注意:人员实体类要与表单中的name一致,约定要优于编码

package com.chensi.bean;

//实体类中的字段要与表单中的字段一致,约定优于编码
public class User {

  private String userName;
  private String pwd;
  private String sex;
  private String[] hobby;
  private String city;
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public String getPwd() {
    return pwd;
  }
  public void setPwd(String pwd) {
    this.pwd = pwd;
  }
  public String getSex() {
    return sex;
  }
  public void setSex(String sex) {
    this.sex = sex;
  }
  public String[] getHobby() {
    return hobby;
  }
  public void setHobby(String[] hobby) {
    this.hobby = hobby;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }

}

接收方法一:         Servlet页面(后台接收数据方法一)

package com.chensi;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet 获得填写的表单数据
 */
@WebServlet("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    //获取传过来的表单数据,根据表单中的name获取所填写的值
    String userName = request.getParameter("userName");
    String pwd = request.getParameter("pwd");
    String sex = request.getParameter("sex");
    String[] hobbys = request.getParameterValues("hobby");

    System.out.println(userName);
    System.out.println(pwd);
    System.out.println(sex);
    for (int i = 0; hobbys!=null&&i < hobbys.length; i++) {
      System.out.println(hobbys[i]+"\t");
    }
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

}

得到的数据:

    

接收方法二:

package com.chensi;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet 获得填写的表单数据
 */
@WebServlet("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    //获取传过来的表单数据,根据表单中的name获取所填写的值
    Enumeration<String> names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String strings = (String) names.nextElement();
      String[] parameterValues = request.getParameterValues(strings);
      for (int i = 0;parameterValues!=null&&i < parameterValues.length; i++) {
        System.out.println(strings+":"+parameterValues[i]+"\t");
      }
    }
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

}

得到的数据:

    

接收方法三: 利用反射赋值给User

package com.chensi;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chensi.bean.User;

/**
 * Servlet 获得填写的表单数据
 */
@WebServlet("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    //获取传过来的表单数据,根据表单中的name获取所填写的值

      try {
        User u = new User();
        System.out.println("数据封装之前: "+u);
        //获取到表单数据
        Map<String, String[]> map = request.getParameterMap();
        for(Map.Entry<String,String[]> m:map.entrySet()){
          String name = m.getKey();
          String[] value = m.getValue();
          //创建一个属性描述器
          PropertyDescriptor pd = new PropertyDescriptor(name, User.class);
          //得到setter属性
          Method setter = pd.getWriteMethod();
          if(value.length==1){
            setter.invoke(u, value[0]);
          }else{
            setter.invoke(u, (Object)value);
          }
        }
        System.out.println("封装数据之后: "+u);
      } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        e.printStackTrace();
      }

    }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

}

得到的结果:

  

接收方法四:使用apache 的 BeanUtils 工具来进行封装数据(ps:这个Benautils工具,Struts框架就是使用这个来获取表单数据的哦!)

package com.chensi;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.chensi.bean.User;

/**
 * Servlet 获得填写的表单数据
 */
@WebServlet("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    //获取传过来的表单数据,根据表单中的name获取所填写的值

    //方法四:使用beanUtil来封装User类
    User u = new User();
    System.out.println("没有使用BeanUtil封装之前: "+u);
    try {
      BeanUtils.populate(u, request.getParameterMap());
      System.out.println("使用BeanUtils封装之后: "+u);
    } catch (IllegalAccessException | InvocationTargetException e) {
      e.printStackTrace();
    }

    }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

}

得到的结果:

   

接收方法 方式五: 使用inputStream流来进行接收(一般字符串啥的不用这个方法,一般是文件上传下载时候才会使用这种方法)因为接收到的字符串各种乱码,编码问题解决不好

package com.chensi;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.chensi.bean.User;

/**
 * Servlet 获得填写的表单数据
 */
@WebServlet("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    //获取传过来的表单数据,根据表单中的name获取所填写的值
    response.setContentType("text/html;charset=UTF-8");
    //获取表单数据
    ServletInputStream sis = request.getInputStream();
    int len = 0;
    byte[] b = new byte[1024];
    while((len=sis.read(b))!=-1){
      System.out.println(new String(b, 0, len, "UTF-8"));
    }

    sis.close();

  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
}

得到的结果:(各种乱码 。。。。)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • jquery ajax提交表单从action传值到jsp实现小结

    jsp页面: 复制代码 代码如下: var clientTel = $("#clientTel").val(); var activityId = $("#activityId").val(); $.ajax({ type : "post",//发送方式 url : "/arweb/reserve/saveCode.action",// 路径 data : "clientTel="+clientTel+&q

  • jquery ajax 如何向jsp提交表单数据

    AJAX越来越火了,作为一个WEB程序开发者要是不会这个感觉就要落伍,甚至有可能在求职的时候屡被淘汰.我也是一个WEB程序开发者,当然我也要 "随波逐流"一把,不然饭碗不保啊! 之前实现AJAX使用Javascript脚本一个一个敲出来的,很繁琐.学习Jquery之后就感觉实现AJAX并不是那么的困难了,当然除了 Jquery框架外还有其它的优秀框架这里我就着重说下比较流行的Jquery.Jquery AJAX提交表单有两种方式,一是url参数提交数据,二是form提交(和平常一样在后

  • JSP刷新页面表单重复提交问题解决办法分享

    使用sessionID和时间戳作为标识,关键代码如下: 复制代码 代码如下: public class SswpdjAction extends BaseAction{     public String execute(){     /**业务代码**/     ................     //设置标识     this.setSessionToken();     //转到添加页面     return "toAdd";     }     public String

  • bootstrap Validator 模态框、jsp、表单验证 Ajax提交功能

    效果图: 如图,这是使用Validator插件,所完成的功能,效果很强大,也很方便,这边推荐使用这种方式,最后介绍一下原始js验证写法. 首先,导入插件: <link href="<%=basePath %>bootstrap/css/bootstrap-datetimepicker.min.css" rel="external nofollow" rel="stylesheet" media="screen"

  • JSP使用自定义标签防止表单重复提交的方法

    本文实例讲述了JSP使用自定义标签防止表单重复提交的方法.分享给大家供大家参考.具体如下: 1. 编写servelt: package cn.itcast.apsliyuan.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletReques

  • JSP针对表单重复提交的处理方法

    本文实例讲述了JSP针对表单重复提交的处理方法.分享给大家供大家参考,具体如下: 1. 在生成表单时执行如下: 复制代码 代码如下: session.setAttribute("forum_add", "forum_add"); 2. 提交处理时作如下判断 if (isRedo(request, "forum_add")) { //提示重复提交,作相关处理 } 相关函数: /** * 判断是否为重复提交 * 1,检查Session中是否含有指定名

  • jsp中如何实现按下回车键自动提交表单

    为了省事很多时候希望可以按回车键来提交表单,要控制这些行为,可以借助JS来达到要求. 代码如下: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../../common/include_tag.jsp"%> <%@ include fi

  • JSP中的FORM表单中只有一个input文本时,按回车键将会自动提交表单

    一个列表界面只有一个输入框查询条件,当首次进入在输入框中输入汉字后,按回车键发现输入框中汉字变成乱码!本以为一个很简单不过的问题,结果却花了好久才找到原因(据说是浏览器问题),按回车后执行了两次查询. 1.未修改前代码: <form id="ff" name="ff" method="post"> <input type="text" id="userName" name="us

  • JSP之表单提交get和post的区别详解及实例

    JSP之表单提交get和post的详解及实例 一 get和post的区别 二 实战(post方式提交) 1.login.jsp <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %> <% String path = request.getContextPath(); String basePath = req

  • 表单提交前触发函数返回true表单才会提交

    直接看代码 复制代码 代码如下: <form id="payForm" action="yeepaypay.html" target="_blank" method="post" onsubmit="return checkform();"> 例子中的onsubmit函数即为表单提交前触发的函数 复制代码 代码如下: function checkform() { var value = $(&q

  • jquery form表单提交插件asp.net后台中文解码

    在asp.net 后台页面提取时需要解码.解码的方式为:HttpUtility.UrlDecode(context.Request["infostr"].ToString());

  • jquery插件EasyUI中form表单提交实例分享

    之前用AJax给Controller传递参数,然后再调用服务端的方法对数据库进行更改,今天碰到一个新的方法,就是表单的提交,这样可以省去AJax传参. 当表单提交后,我们可以获取表单上控件中的值,然后再调用服务端的方法对数据库进行更改.下面的一张截图是具体的业务需求. 一.要实现的功能:从上面这个表单中,获取控件中的值,然后传递给后台.下面是表单代码. 二.表单代码 <div id="Editwin" class="easyui-window" title=&

  • Javascript异步表单提交,图片上传,兼容异步模拟ajax技术

    前言: 咋一看标题还挺长的呢,还有这么多功能,其实简化一点就是一个功能,异步表单提交,只是在异步表单提交这个大功能下,可以实现图片上传,模拟ajax技术(其实很早以前就是通过这个方式来实现多浏览器的兼容ajax,这里只是怀怀旧,作为一个技术来玩玩),下面的内容需要有一定的js基础,要不然理解起来会比较困难. 注意事项: 这是我bBank里面的一个方法,现在我把他提取出来成一个通用方法来讲解. bBank 框架介绍:http://www.cnblogs.com/bruceli/archive/20

  • JQuery form表单提交前验证单选框是否选中、删除记录时验证经验总结(整理)

    先上三张效果图:     这些功能在Java Web开发中可能是经常需要的,虽然很简单却使很实用的功能,这里记录下以免忘记. 1. 先说表单提交前验证:后台经常用到(这里是提交后统一验证,及时验证请参考我另一篇文章 http://blog.csdn.net/jianzhonghao/article/details/52503431) 1.1 通过submit 按钮提交后 会根据form的属性action="路径"来跳转到相应的路径,这时,给form添加一个 onsubmit =&quo

  • mvc中form表单提交的三种方式(推荐)

    第一种方式:submit 按钮 提交 <form action="MyDemand" method="post"> <span>关键字:</span> <input name="keywords" type="text" value="@keywords" /> <input type="submit" value="搜索&

  • 在表单提交前进行验证的几种方式整理

    在表单提交前进行验证的几种方式 . 在Django中,为了减轻后台压力,可以利用JavaScript在表单提交前对表单数据进行验证.下面提供了有效的几种方式(每个.html文件为一种方式). formpage1.html 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional

  • mvc form表单提交的几种形式整理总结

    mvc中form表单提交的几种形式 第一种方式:submit 按钮 提交 <form action="MyDemand" method="post"> <span>关键字:</span> <input name="keywords" type="text" value="@keywords" /> <input type="submit&quo

  • jQuery中验证表单提交方式及序列化表单内容的实现

    之前项目中使用的表单提交方式 使用form()方法可以将提交事件脱离submit按钮,绑定到任何事件中 复制代码 代码如下: function addSubmit(){ $('#addForm').form('submit', { url : _basePath + '/@Controller/@RequestMapping', onSubmit : function() { if(boolean){//放置能否提交的判断条件 $.messager.show({ title:'提示',msg:'

随机推荐