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

时间:2023-01-25 18:25:42
 过滤器解决全站中文乱码问题大致分为两种:
 post 方式提交:在过滤器内使用 request.setCharacterEncoding("utf-8");即可解决 ②GET方式提交: 需要掉包request对象     掉包request对象分为两步:
        ①写一个request装饰类    需要继承HttpServletRequestWrapper类,该类的重写代码                设计人员已经帮你写好 所以只需要重写getParameter方法即可         ②在放行时,使用自己的request
具体代码如下:
package com.mxf.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
* 装饰request
* @author ma
*
*/
public class EncodingRequest extends HttpServletRequestWrapper{

private HttpServletRequest req;
public EncodingRequest(HttpServletRequest request) {
super(request);

this.req = request;
}
public String getParameter(String name) {

String value = req.getParameter(name);

try {
value = new String(value.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {

e.printStackTrace();
}

return value;
}

}

过滤器的代码为:

package com.mxf.filter;

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{

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

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

/*String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"),"utf-8");*/

HttpServletRequest req = (HttpServletRequest) request;
if(req.getMethod().equalsIgnoreCase("get"))
{
/**
* 处理GET请求乱码问题
*/

/**
* 掉包request
* 1.写一个request装饰类
* 2.在放行时,使用自己的request
*/
EncodingRequest er = new EncodingRequest(req);
chain.doFilter(er, response);
}else if(req.getMethod().equalsIgnoreCase("post"))
{
/**
* 处理post请求乱码问题
*/
request.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}

}

public void init(FilterConfig arg0) throws ServletException {

}

}