(request)get和post方法获取请求参数及乱码解决方法

方式一:get获取请求参数
	1.使用方法:Request.getParameter(“name属性值”); 
	2.基本实现代码: 
	public class ParameterServlet extends HttpServlet {
		public void doGet(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			//根据表单的name属性值获取请求参数
			String userName = request.getParameter("userName");
			System.out.println("用户名:"+ userName);
		}
		public void doPost(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
表单:
	<html>
	  <head>
	    <base href="<%=basePath%>">
	    <title>My JSP 'index.jsp' starting page</title>
	  </head>
	  <body>
		    <form action="/parameter/parameter" method="get">
		   	用户名:<input type="text" name="username" >
		   	<input type="submit" value="提交">  
		    </form>
	  </body>
	</html>
3.get请求方式的乱码原因:表单是用utf-8进行编码,而request对象默认使用iso8859-1进行解码,所以会出现乱码。		
4.解决乱码
1.方式一
1.把乱码还原成原来的数据。 
2.Get提交请求参数解决乱码的步骤: 
	乱码.getBytes(“iso8859-1”)找回原来的数字
	使用对应的码表进行解码。  new  String(码值, “码表”);
3.代码
public class ParameterServlet extends HttpServlet { 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	//根据表单的name属性值获取请求参数
	String userName = request.getParameter("userName");
	//System.out.println("用户名:"+ userName);  //?? 在iso码表中任何一个数字都有对应不同的字符。
	//第一步:需要把乱码找iso8859-1码表,找回原来的数字
	byte[] buf = userName.getBytes("iso8859-1");
		//第二步: 使用utf-8码表进行解码
		userName = new String(buf,"utf-8");
		System.out.println(userName);
						
}
				 
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {		
						
	}
				 
}
2.方式二:修改tomcat-->conf-->sever.xml 文件中的编码,搜索8080        
方式二:post请求	
表单:
	<html>
	  <head>
	    <base href="<%=basePath%>">
	    <title>My JSP 'index.jsp' starting page</title>
	  </head>
	  <body>
		    <form action="/parameter/parameter" method="get">
		   	用户名:<input type="text" name="username" >
		   	<input type="submit" value="提交">  
		    </form>
	  </body>
	</html>
2.乱码问题
1.因为post提交的数据出现在实体内容上,所以解决乱码问题的时候我们可以直接设置获取实体内容时候使用的码表。 
代码:request.setCharacterEncoding("UTF-8"); 	 
public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {			
	//获取请求参数 注意: post提交的数据是在实体内容上,request有一个方法是可以设置获取实体内容时候使用的码表。
	request.setCharacterEncoding("UTF-8"); //设置获取实体内容时候使用的码表。
	String userName =request.getParameter("userName");
	System.out.println("用户名:"+ userName);			
}
			








猜你喜欢

转载自blog.csdn.net/chenzuen113113/article/details/80822688