过滤器--解决全站中文乱码问题

阅读更多

全站乱码案例:

     * 利用Servlet的doGet()和doPost()方法中,可以解决中文乱码:

[java] view plain copy print ?
  1.      * doGet()  
  2.        String value = request.getParameter("");  
  3. value = new String(value.getBytes("ISO8859-1"),"utf-8");  
  4.   
  5. response.setContentType("text/html;charset=utf-8");  
  6.      * doPost()  
  7.        request.setCharacterEncoding("utf-8");  
  8. response.setContentType("text/html;charset=utf-8");  
       * doGet()
         String value = request.getParameter("");
	 value = new String(value.getBytes("ISO8859-1"),"utf-8");

	 response.setContentType("text/html;charset=utf-8");
       * doPost()
         request.setCharacterEncoding("utf-8");
	 response.setContentType("text/html;charset=utf-8");


     * 以上问题:
       * 实际开发时,Web应用程序的逻辑比较复杂(多个Servlet).
       * 上述的解决方案,仅能解决当前Servlet的中文乱码问题.

       * 如果使用上述方案,解决中文乱码问题:代码重复性太多.

过滤器--解决全站中文乱码问题_第1张图片

EncodingFilter:

 

[java] view plain copy print ?
  1. package app.java.filter.demo1;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. /** 
  15.  * 当前Filter用于解决全站中文乱码问题. 
  16.  * @author JYL 
  17.  */  
  18. public class EncodingFilter implements Filter {  
  19.   
  20.     public void destroy() {  
  21.           
  22.     }  
  23.   
  24.     public void doFilter(ServletRequest req, ServletResponse resp,  
  25.             FilterChain chain) throws IOException, ServletException {  
  26.           
  27.         //1 进行Request与Response对象的类型强转  
  28.         HttpServletRequest request = (HttpServletRequest)req;  
  29.         HttpServletResponse response = (HttpServletResponse)resp;  
  30.           
  31.         //2 解决中文乱码问题:1)请求的中文乱码(GET\POST);2)响应的中文乱码.  
  32.         request.setCharacterEncoding("utf-8");  
  33.         response.setContentType("text/html;charset=utf-8");  
  34.           
  35.         //3 创建自定义的Request对象  
  36.         MyRequest myRequest = new MyRequest(request);  
  37.           
  38.         //3 放行  
  39.         chain.doFilter(myRequest, response);  
  40.     }  
  41.   
  42.     public void init(FilterConfig arg0) throws ServletException {  
  43.     }  
  44.   
  45. }  
package app.java.filter.demo1;

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;
import javax.servlet.http.HttpServletResponse;

/**
 * 当前Filter用于解决全站中文乱码问题.
 * @author JYL
 */
public class EncodingFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		//1 进行Request与Response对象的类型强转
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		//2 解决中文乱码问题:1)请求的中文乱码(GET\POST);2)响应的中文乱码.
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//3 创建自定义的Request对象
		MyRequest myRequest = new MyRequest(request);
		
		//3 放行
		chain.doFilter(myRequest, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}

 

MyRequest:

 

[java] view plain copy print ?
  1. package app.java.filter.demo1;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletRequestWrapper;  
  7. /** 
  8.  * 自定义的Request对象 
  9.  * @author JYL 
  10.  */  
  11. public class MyRequest extends HttpServletRequestWrapper {  
  12.   
  13.     public MyRequest(HttpServletRequest request) {  
  14.         super(request);  
  15.     }  
  16.       
  17.     @Override  
  18.     public String getParameter(String name) {  
  19.         String value = super.getParameter(name);  
  20.         if(super.getMethod().equalsIgnoreCase("GET")){  
  21.             try {  
  22.                 value = new String(value.getBytes("ISO-8859-1"),"utf-8");  
  23.             } catch (UnsupportedEncodingException e) {  
  24.                 e.printStackTrace();  
  25.             }  
  26.         }  
  27.         return value;  
  28.     }  
  29.   
  30. }  
package app.java.filter.demo1;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * 自定义的Request对象
 * @author JYL
 */
public class MyRequest extends HttpServletRequestWrapper {

	public MyRequest(HttpServletRequest request) {
		super(request);
	}
	
	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if(super.getMethod().equalsIgnoreCase("GET")){
			try {
				value = new String(value.getBytes("ISO-8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return value;
	}

}

 

TestServlet:

 

[java] view plain copy print ?
  1. package app.java.filter.demo1;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class TestServlet extends HttpServlet {  
  12.   
  13.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  14.             throws ServletException, IOException {  
  15.   
  16.         String username = request.getParameter("username");  
  17.         String password = request.getParameter("password");  
  18.           
  19.         System.out.println(username+" : "+password);  
  20.           
  21.         response.getWriter().println("中文解决了,真好!!!!");  
  22.     }  
  23.   
  24.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  25.             throws ServletException, IOException {  
  26.   
  27.         String username = request.getParameter("username");  
  28.         String password = request.getParameter("password");  
  29.           
  30.         System.out.println(username+" : "+password);  
  31.           
  32.         response.getWriter().println("中文解决了,真好!!!!");  
  33.     }  
  34.   
  35. }  
package app.java.filter.demo1;

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 TestServlet extends HttpServlet {

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

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		System.out.println(username+" : "+password);
		
		response.getWriter().println("中文解决了,真好!!!!");
	}

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

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		System.out.println(username+" : "+password);
		
		response.getWriter().println("中文解决了,真好!!!!");
	}

}

 

xml:

 

[html] view plain copy print ?
  1. <filter>  
  2.     <filter-name>EncodingFilterfilter-name>  
  3.     <filter-class>demo1.EncodingFilterfilter-class>  
  4.   filter>  
  5.   <filter-mapping>  
  6.     <filter-name>EncodingFilterfilter-name>  
  7.     <url-pattern>/*url-pattern>  
  8.   filter-mapping>  

  	EncodingFilter
  	demo1.EncodingFilter
  
  
  	EncodingFilter
  	/*
  

jsp:

 

 

[html] view plain copy print ?
  1. <form action="test" method="post">  
  2.         用户名:<input type="text" name="username"><br>  
  3.         密码:<input type="password" name="password"><br>  
  4.         <input type="submit" value="提交">  
  5.     form>  
  6.     <a href="test?username=张无忌&password=123">GET方式发送的请求a>  
用户名:
密码:
GET方式发送的请求

 

 

另一种:

 

[java] view plain copy print ?
  1. package com.itheima.filter;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.util.Map;  
  6.   
  7. import javax.servlet.Filter;  
  8. import javax.servlet.FilterChain;  
  9. import javax.servlet.FilterConfig;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.ServletRequest;  
  12. import javax.servlet.ServletResponse;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletRequestWrapper;  
  15.   
  16. public class MyFilter implements Filter {  
  17.   
  18.     public void init(FilterConfig filterConfig) throws ServletException {  
  19.   
  20.     }  
  21.   
  22.     public void doFilter(ServletRequest request, ServletResponse response,  
  23.             FilterChain chain) throws IOException, ServletException {  
  24.         HttpServletRequest req = (HttpServletRequest) request;  
  25.         // 解决post方式  
  26.         // req.setCharacterEncoding("UTF-8");  
  27.         req = new MyRequest(req);  
  28.   
  29.         chain.doFilter(req, response);  
  30.     }  
  31.   
  32.     public void destroy() {  
  33.     }  
  34. }  
  35.   
  36. // 实现与被包装对象相同的接口  
  37. // 定义一个与被包装类相对象的引用  
  38. // 定义一个构造方法,把被包装对象传过来  
  39. // 对于不需要改写方法,直接调用  
  40. // 对于无需要改写方法,写自己的方法体  
  41. class MyRequest extends HttpServletRequestWrapper {  
  42.     HttpServletRequest request;  
  43.   
  44.     public MyRequest(HttpServletRequest request) {  
  45.         super(request);  
  46.         this.request = request;  
  47.     }  
  48.   
  49.     /* 
  50.      * @Override public String getParameter(String name) { name = 
  51.      * request.getParameter(name);//乱码 try { return new 
  52.      * String(name.getBytes("iso-8859-1"),"UTF-8"); } catch 
  53.      * (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } 
  54.      */  
  55.   
  56.     @Override  
  57.     public String getParameter(String name) {  
  58.         Map map = getParameterMap();  
  59.         return map.get(name)[0];  
  60.     }  
  61.   
  62.     @Override  
  63.     public String[] getParameterValues(String name) {  
  64.         Map map = getParameterMap();  
  65.         return map.get(name);  
  66.     }  
  67.   
  68.     private boolean flag = true;  
  69.   
  70.     @Override  
  71.     public Map getParameterMap() {  
  72.         Map map = request.getParameterMap();// 乱码  
  73.         if (flag) {  
  74.             for (Map.Entry m : map.entrySet()) {  
  75.                 String[] values = m.getValue();  
  76.                 for (int i = 0; i < values.length; i++) {  
  77.                     try {  
  78.                         values[i] = new String(  
  79.                                 values[i].getBytes("iso-8859-1"), "UTF-8");  
  80.                     } catch (UnsupportedEncodingException e) {  
  81.                         e.printStackTrace();  
  82.                     }  
  83.                 }  
  84.   
  85.             }  
  86.             flag = false;  
  87.         }  
  88.         return map;  
  89.   
  90.     }  
  91.   
  92. }  
package com.itheima.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

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;
import javax.servlet.http.HttpServletRequestWrapper;

public class MyFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		// 解决post方式
		// req.setCharacterEncoding("UTF-8");
		req = new MyRequest(req);

		chain.doFilter(req, response);
	}

	public void destroy() {
	}
}

// 实现与被包装对象相同的接口
// 定义一个与被包装类相对象的引用
// 定义一个构造方法,把被包装对象传过来
// 对于不需要改写方法,直接调用
// 对于无需要改写方法,写自己的方法体
class MyRequest extends HttpServletRequestWrapper {
	HttpServletRequest request;

	public MyRequest(HttpServletRequest request) {
		super(request);
		this.request = request;
	}

	/*
	 * @Override public String getParameter(String name) { name =
	 * request.getParameter(name);//乱码 try { return new
	 * String(name.getBytes("iso-8859-1"),"UTF-8"); } catch
	 * (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
	 */

	@Override
	public String getParameter(String name) {
		Map map = getParameterMap();
		return map.get(name)[0];
	}

	@Override
	public String[] getParameterValues(String name) {
		Map map = getParameterMap();
		return map.get(name);
	}

	private boolean flag = true;

	@Override
	public Map getParameterMap() {
		Map map = request.getParameterMap();// 乱码
		if (flag) {
			for (Map.Entry m : map.entrySet()) {
				String[] values = m.getValue();
				for (int i = 0; i < values.length; i++) {
					try {
						values[i] = new String(
								values[i].getBytes("iso-8859-1"), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}

			}
			flag = false;
		}
		return map;

	}

}

 

转载:https://blog.csdn.net/CSDN_GIA/article/details/54094426

你可能感兴趣的:(过滤器--解决全站中文乱码问题)