HttpServletRequestWrapper Filter中装饰Request 解决全站编码问题!

时间:2021-01-01 18:26:08

利用Filter解决全站编码问题!!!

解决问题的核心是对request的装饰!!

package com.xuxiang.decorate;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
*
* HttpServletRequest 的装饰类
*
* 装饰者:EncodingRequest
* 被装饰者 :Request
* 他们共有的超类是HttpServletRequest
* @author Administrator
*
*/
public class EncodingRequest extends HttpServletRequestWrapper {

//首先创建一个超类的变量
private HttpServletRequest httpServletRequest;

//创建构造器,获取超类
public EncodingRequest(HttpServletRequest httpServletRequest){
super(httpServletRequest);
this.httpServletRequest=httpServletRequest;
}

//重写request中的某个方法,扩展其功能!!
@Override
public String getParameter(String name) {
String value=httpServletRequest.getParameter(name);
try {
value = new String (value.getBytes("ISO-8859-1"),"utf-8");

} catch (UnsupportedEncodingException e) {

throw new RuntimeException(e);
}
return value;
}


}

package com.xuxiang.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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.xuxiang.decorate.EncodingRequest;

/**
* 拦截器设置
* @author Administrator
*
*/
public class EncodingFilter implements Filter {

public void destroy() {

}

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

HttpServletRequest req = (HttpServletRequest) request;

if (req.getMethod().equals("GET")) {
// 实例装饰者类EncodingRequest;
EncodingRequest eRequest = new EncodingRequest(req);
//将装饰者实例对象eRequest 过滤给资源文件!!
chain.doFilter(eRequest, response);

} else if (req.getMethod().equals("POST")) {

request.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}

}

public void init(FilterConfig fConfig) throws ServletException {

}

}

这样就能解决全站编码的问题!!