JavaWeb之不同Tomcat版本对get、post请求,中文乱码问题

Myeclipse安装时的前期工作空间的编码准备,就不说了

Tomcat8

public class dd extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		 Tomcat8
		resp.setContentType("text/html;UTF-8");
		req.setCharacterEncoding("UTF-8");
		System.out.println(req.getParameter("name"));
		
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		 System.out.println(req.getParameter("name")); //不用进行ISO转码

	}
}


Tomcat8.x 以前版本

public class ee extends HttpServlet {



	private static final long serialVersionUID = 1L;


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println(request.getParameter("name")); //??????
		
		//需要进行 ISO 解码 ,utf 编码
		String name = request.getParameter("name");
		System.out.println(new String(name.getBytes("ISO-8859-1"),"UTF-8"));//你好
		
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
		
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		System.out.println(request.getParameter("name"));	// post请求   
	}
}



测试:jsp

<body>


    <a href="${pageContext.request.contextPath}/dd?name=你好">GET</a>
   
    <form action="${pageContext.request.contextPath}/dd" method="post">
    <span style="white-space:pre">	</span><input type="text" name="name" />
    <span style="white-space:pre">	</span><input type="submit" value="提交post" /> 
    </form>
   
    <form action="${pageContext.request.contextPath}/dd" method="get">
    <span style="white-space:pre">	</span><input type="text" name="name" />
    <span style="white-space:pre">	</span><input type="submit" value="提交get"/> 
    </form>
  </body>



也可以使用直接修改配置文件的办法:

再Tomcat根目录下的config.xml文件,找到<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

再其中添加:URIEncoding="UTF-8" 和 useBodyEncodingForURI=“true”

useBodyEncodingForURI(默认false):参数表示是否用 与 request.setCharacterEncoding一致的编码 
如果是true,参数对URL提交的数据和表单中GET方式提交的数据进行重新编码。

URIEncoding (默认ISO8859-1)参数指定对所有GET方式请求进行统一的重新编码(解码)的编码。


再Tomcat8中,关于URIEncoding的描述做出了更改:http://localhost:8080/docs/config/http.html

URIEncoding

This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, UTF-8will be used unless theorg.apache.catalina.STRICT_SERVLET_COMPLIANCEsystem property is set totrue in which case ISO-8859-1 will be used.



PS:极其不建议在Tomcat的配置文件上做编码的修改,因为你不知道用户用的什么版本或根本就不是Tomcat,总不能和用户说:别用weblogic,你用tomcat 吧,再顺便那个配置文件改改


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值