Servlet读取表单提交数据

getParameter(请查Servlet的帮助文档)

public java.lang.String getParameter(java.lang.String name)

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data. 

步骤1、编写含登录表单的jsp页面

(1) 注意要改变页面的编码方式为支持中文的编码方式

默认的编码方式为iso8859-1,需要修改为gb2312utf-8,推荐为utf-8

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

(2) 编写登陆的form表单

注意表单元素的name属性,将来用于Servlet获取表单值的方法中

<body>
	<center>
		<form method="post" action="Servlet/LoginServlet" name="Login">
			<table border="1" width="217" height="89">
				<tr>
					<td>name:</td>
					<td><input type="text" name="User_Name">
					</td>
				</tr>
				<tr>
					<td>pass:</td>
					<td><input type="password" name="User_Pass">
					</td>
				</tr>
				<tr>
					<center>
						<input type="submit" value="提交">
					</center>
				</tr>
			</table>
		</form>
	</center>
</body>

步骤2、编写Servlet去读取表单的数据、并在web.xml中配置

(1)servlet的编写

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doGet");
		// 从表单接收提交过来的数据并打印到页面和控制台。
		// 通过表单元素的name属性获取到提交的数据
		String username=req.getParameter("User_Name");
		String userpass=req.getParameter("User_Pass");
		
		System.out.println(username);
		System.out.println(userpass);
		
		String name=new String(username.getBytes("ISO8859-1"), "UTF-8");
		String pass=new String(userpass.getBytes("ISO8859-1"), "UTF-8");

		System.out.println(name);
		System.out.println(pass);
		//给该Servlet所显示的页面指定MIME类型,支持中文的字符集
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		// 向客户端写一个html页面
		out.write("<html> <body> <h1>");
		out.write(name);
		out.write(pass);
		out.write("</h1> </body> </html>");
		out.flush(); // 清空缓存
		
	}

中文乱码问题的解决

为什么会出现乱码问题:

程序中的数据在不同的地方传输(网络上传输),不同的地方存储,不同的地方显示,各个地方都可能会有不同的中文字符的编码方式,我们要做到的是:能让各个地方的编码能一致。

1)客户端提交表单的页面的编码为utf-8

2Servlet中获取到请求包中的数据,请求包中的数据是iso8859-1来编码,以正确的方式解码,以utf-8的方式来对字符串重新编码

把网络上传输过来的IOS8859-1的编码的数据,转换为正确的中文

String name=new String(username.getBytes("ISO8859-1"), "UTF-8");

Servlet往客户端写的页面正确的编码——utf-8

resp.setContentType("text/html;charset=utf-8");

web.xml配置

 <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.java.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/Servlet/LoginServlet</url-pattern>
  </servlet-mapping>

web.xml中Servlet的URL地址,

 <url-pattern>/Servlet/LoginServlet</url-pattern>

填写到表单的action的参数位置。

注意不要前面的斜杠

		<form method="post" action="Servlet/LoginServlet" name="Login">

最后就是测试了