zoukankan      html  css  js  c++  java
  • Servlet处理表单数据

    Servlet 表单数据

    很多情况下,需要传递一些信息,从浏览器到 Web 服务器,最终到后台程序。浏览器使用两种方法可将这些信息传递到 Web 服务器,分别为 GET 方法和 POST 方法。

     

    使用 Servlet 读取表单数据

    不区分GET和POST

    Servlet 处理表单数据,这些数据会根据不同的情况使用不同的方法自动解析

    • getParameter():您可以调用 request.getParameter() 方法来获取表单参数的值。
    • getParameterValues():如果参数出现一次以上,则调用该方法,并返回多个值,例如复选框。
    • getParameterNames():如果您想要得到当前请求中的所有参数的完整列表,则调用该方法。
    • 注意:如果表单提交的数据中有中文数据则需要转码:

      String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
    • tomcat默认用ISO8859-1解码浏览器发来的数据,用此编码重新编码,再用实际编码解码为字符串即可获得原始数据
    • 注意!POST方式获得的数据会被受上述过程影响,GET方式附加在URL上的数据似乎没有被tomcat默认解码,不需要调整编码即可使用

    读取所有的表单参数

    以下是通用的实例,使用 HttpServletRequest  request的 request.getParameterNames() 方法读取所有可用的表单参数name的枚举(自动去重名)。该方法返回一个枚举,其中包含未指定顺序的参数名。

    一旦我们有一个枚举,我们可以以标准方式循环枚举,使用 hasMoreElements() 方法来确定何时停止,使用 nextElement() 方法来获取每个参数的name。

    再用String[] request.getParameterValues(name)获得每个name可能具有的values 根据返回String[] values的values.length分单value和多value进行处理。


    附简单例子:

    ParseForm.java

    package hentai.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    
    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 implementation class Main
     */
    @WebServlet("/ParseForm")
    public class ParseForm extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	//
    	private String msg = "";
    
    	/**
    	 * Default constructor.
    	 */
    	public ParseForm() {
    		// TODO Auto-generated constructor stub
    	}
    
    	@Override
    	public void init() throws ServletException {
    		// TODO 自动生成的方法存根
    		super.init();
    		//
    		msg = "1314233";
    	}
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		//判断提交方式以决定如何转换编码
    		boolean isPOST = false;
    		if(request.getMethod().toUpperCase().equals("POST"))
    			isPOST = true;
    		//设置响应格式与编码
    		response.setContentType("text/html;charset=utf-8");
    		//获得响应输出
    		PrintWriter out = response.getWriter();
    		//输出
    		out.println("<h1>" + request.getMethod() + "</h1>");
    		//遍历请求参数并打印回浏览器
    		Enumeration<String> allNames = request.getParameterNames();
    		while (allNames.hasMoreElements()) {
    			String name = allNames.nextElement();
    			String[] values = request.getParameterValues(name);
    			if (values.length == 1) {
    				String value = values[0];
    				if(isPOST)
    					value = new String(value.getBytes("ISO8859-1"), "utf-8");
    				out.println("<p>" + name + ":" + value + "</p>");
    			} else {
    				for (String value : values) {
    					if(isPOST)
    						value = new String(value.getBytes("ISO8859-1"), "utf-8");
    					out.println("<p>" + name + "s:" + value + "</p>");
    				}
    			}
    
    		}
    		// out.println(request.getContextPath());
    		//response.sendRedirect("form.html");
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    	@Override
    	public void destroy() {
    		// TODO 自动生成的方法存根
    		super.destroy();
    	}
    
    }
    

     form.html

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    	<meta charset="UTF-8">
    	<title>form</title>
    </head>
    
    <body>
    
    	<form method="post" action="ParseForm" id="dataForm">
    		<input type="text" name="uName" />
    		<input type="password" name="uPwd" />
    
    		<input type="radio" name="sex" value="1" />男
    		<input type="radio" name="sex" value="0" />女
    		<input type="radio" name="sex" value="-1" />保密
    
    		<input type="checkbox" name="hobby" value="game" />游戏
    		<input type="checkbox" name="hobby" value="music" />音乐
    		<input type="checkbox" name="hobby" value="write" />写作
    
    		<input type="submit" value="submit" />
    		<!--<input type="button" value="提交" />
    		<script>
    			var dataFormChilds = document.getElementById("dataForm").getElementsByTagName("input");
    			for (var i = 0; i < dataFormChilds.length; i++) {
    				if (dataFormChilds[i].getAttribute("type") == "button") {
    					dataFormChilds[i].onclick = function () {
    						alert(this);
    						this.parentElement.submit();
    					}
    				}
    			}
    		</script>-->
    	</form>
    
    </body>
    
    </html>
    

     单选按钮名字需要一样,Servlet获得参数时获得是被选中的radio的value

    多选框,......获得的是被选中的框的value的值的数组

    其他待补充......

  • 相关阅读:
    mysql用户
    mysql字符集
    tidb之一致性算法raft学习
    更新港资股票数据
    php中的时区设置
    PHP 中的注释
    python下如何处理windows的路径名
    安装第三方模块
    偏函数
    装饰器没学明白,记录一下,以后再学
  • 原文地址:https://www.cnblogs.com/Leroscox/p/8284419.html
Copyright © 2011-2022 走看看