码迷,mamicode.com
首页 > 其他好文 > 详细

解决中文乱码过滤器

时间:2016-07-23 21:35:58      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:解决中文乱码过滤器


解决中文乱码过滤器



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.HttpServletRequestWrapper;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet Filter implementation class CharacterEncodingFilter

 */

public class CharacterEncodingFilter implements Filter {


/**

* Default constructor.

*/

public CharacterEncodingFilter() {

// TODO Auto-generated constructor stub

}


/**

* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)

*/

public void doFilter(ServletRequest req, ServletResponse res,

FilterChain chain) throws IOException, ServletException {


HttpServletRequest  request = (HttpServletRequest)req;

HttpServletResponse response = (HttpServletResponse)res;

        request.setCharacterEncoding("UTF-8");

        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");

        

        CharacterEncodingRequest  characterEncodingRequest = new CharacterEncodingRequest(request);

chain.doFilter(characterEncodingRequest, response);

}


public void destroy() {

// TODO Auto-generated method stub


}


public void init(FilterConfig arg0) throws ServletException {

// TODO Auto-generated method stub


}


}


class CharacterEncodingRequest extends HttpServletRequestWrapper {

private HttpServletRequest request;


public CharacterEncodingRequest(HttpServletRequest request) {

super(request);

this.request = request;

}


@Override

public String getParameter(String name) {

String value = this.request.getParameter(name);

if (value == null) {

return null;

}


if (!this.request.getMethod().equalsIgnoreCase("get")) {

return value;

}

try {

value = new String(value.getBytes("ISO-8859-1"), this.getRequest()

.getCharacterEncoding());

} catch (Exception e) {

throw new RuntimeException(e);

}


return value;

}


}


本文出自 “德泽无忧” 博客,谢绝转载!

解决中文乱码过滤器

标签:解决中文乱码过滤器

原文地址:http://dezewuyou.blog.51cto.com/2628602/1829009

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!