JavaWeb HttpServletRequest应用——解决请求参数乱码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/83511425

本篇是用来学习课本教材上的实例,提前说明,是我学习教材的一个记录

在实际开发中,经常需要获取其用户提交的表单,例如用户名,用户密码等,在HttpServletRequest接口中定义了许多获得参数的方法,其中getParameter()方法用于获取某个指定的参数,getParametrValues()方法用于获得多个同名的参数,下面通过案例学习一下具体的案例。

1.在web-chapter04项目中的webContent根目录下编写一个表单文件form.html,如下列所示:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                              "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 	<form action="/web-chapter04/RequestParamsServlet" method="GET">
 	 	用户名:<input type="text" name="username"><br>
 	 	密  &nbsp;&nbsp;&nbsp;码:<input type="password" name="password"><br>
 	 	爱好:
 	 	<input type="checkbox" name="hobby" value="sing">唱歌
 	 	<input type="checkbox" name="hobby" value="dance">跳舞
 	 	<input type="checkbox" name="hobby" value="football">足球<br>
 	 	<input type="submit" value="提交">
 	</form>
</body>
</html>

2.在cn.itcast.chapter04.request包中创建一个名为RequestParamsServlet的servlet类

package cn.itcast.chaotre04.request;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestParamsServlet extends HttpServlet {
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name=request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("用户名="+name);
		System.out.println("密 码="+password);
		String[] hobbys = request.getParameterValues("hobbys");
		System.out.print("爱好");
		for(int i = 0 ;i<hobbys.length;i++) {
			System.out.println(hobbys[i]+",");
		}
	}

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

}

3.在web.xml中配置好RequestParamsServlet映射

<servlet>
    <description></description>
    <display-name>RequestParamsServlet</display-name>
    <servlet-name>RequestParamsServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.RequestParamsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RequestParamsServlet</servlet-name>
    <url-pattern>/RequestParamsServlet</url-pattern>
  </servlet-mapping>

4.启动tomcat服务器在浏览器的地址栏中输入地址“http://localhost:8080/web-chapter04/form.html”

可以看到本应该是汉字的用户用被使用?替代了,

5.解决中文乱码问题

这个时候可以在RequestParamsServlet中的定义name之后加上

name=new String(name.getBytes("iso8859-1"),"utf-8");

再次测试发现

已经正常了

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/83511425