1. 程式人生 > >Request.getParameter()亂碼問題

Request.getParameter()亂碼問題

   URIEncoding,該配置決定了使用get請求通過瀏覽器位址列訪問tomcat時的編碼方式,預設的編碼方式使ISO8859-1,Tomcat7官方文件:https://tomcat.apache.org/tomcat-7.0-doc/config/http.html

URIEncoding
This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. 
If not specified, ISO-8859-1 will be used.
   Post請求處理方式

Tomcat對requset.getParameter()的預設編碼方式為iso-8859-1,

        方法一: request.setCharacterEncoding(String env)

         Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().

      方法二:String username=new String(request.getParameter("iso-8859-1"),"utf-8");

  GET請求的處理方式

Tomcat的Get與post的編碼方式不同在於:Tomcat對get請求不會考慮用request.setCharacterEncoding()設定的編碼方式,即Tomcat會永遠使用ISO-8859-1進行編碼

       步驟一:resp.setContentType("text/html;charset=utf-8");

       步驟二:username=new String(username.getBytes("ISO-8859-1"),"utf-8");

       或者

       在server.xml中,修改<connector connectionTimeOut="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URLEncoding="utf-8">(對GET方式)

     <connector connectionTimeOut="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"  URLEncoding="utf-8">

   useBodyEncodingForURI引數表示是否用request.setCharacterEncoding引數對URL提交的資料和表單中GET方式提交的資料進行重新編碼,在預設情況      下,該引數為false。

    URIEncoding引數指定對所有GET方式請求進行統一的重新編碼(解碼)的編碼。

     重啟Tomcat

使用過濾器:

     EncodingFilter類

package mypack;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class EnCodingFilter implements Filter{
	private FilterConfig config;
	private String charset;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		resp.setContentType("text/html;charset="+charset);
		EnCodeRequest request = new EnCodeRequest((HttpServletRequest) req,charset);
		System.out.println("diFilter()");
		chain.doFilter(request, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		this.config=config;
		charset = config.getInitParameter("charset");
		if(charset==null || charset.isEmpty())
			charset="utf-8";
		System.out.println("init()   "+charset);
	}
}
EnquestRequest類
package mypack;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EnCodeRequest extends HttpServletRequestWrapper{
	private String charset;

	public EnCodeRequest(HttpServletRequest request,String charset) {
		super(request);
		this.charset=charset;
	}
	
	public String getParameter(String str){
		HttpServletRequest request = (HttpServletRequest) getRequest();
		String method = getMethod();
		if(method.equalsIgnoreCase("post")){
			try {
				request.setCharacterEncoding(charset);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				throw new RuntimeException("Unsupport CharacterEncoding");
			}
		}
		else if(method.equalsIgnoreCase("get")){
			String value = request.getParameter(str);
			try {
				value= new String(value.getBytes("ISO-8859-1"),charset);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				throw new RuntimeException("Unsupport CharacterEncoding");
			}
			return value;
		}
		return request.getParameter(str);
	}
}
Demo類
package mypack;

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

public class Demo extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter writer = resp.getWriter();
		String username = req.getParameter("username");
		System.out.println(username);
		if(username!=null){
			//username=new String(username.getBytes("ISO-8859-1"),"utf-8");
			writer.println("<html>");
			writer.println("<head><title>test</title></head>");
			writer.println("<body>您好:"+username+"</body>");
			writer.println("</html>");
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>EnCodeAndDecode</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
     <filter-name>filter</filter-name>
     <filter-class>mypack.EnCodingFilter</filter-class>
     <init-param>
       <param-name>charset</param-name>
       <param-value>utf-8</param-value>
     </init-param>
  </filter>
  <filter-mapping>
     <filter-name>filter</filter-name>
     <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>demo</servlet-name>
    <servlet-class>mypack.Demo</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>demo</servlet-name>
    <url-pattern>/demo</url-pattern>
  </servlet-mapping>
  
</web-app>
對於Tomcat8以及以上Request.getParameter()預設編碼為utf-8

官網:https://tomcat.apache.org/tomcat-8.0-doc/config/http.html

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