1建立个过滤器
package cn.itcast.web.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() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 处理post请求编码问题
request.setCharacterEncoding("utf-8");
HttpServletRequest req = (HttpServletRequest) request;
/*
* 处理GET请求的编码问题
*/
// String username = request.getParameter("username");
// username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
/*
* 调包request
* 1. 写一个request的装饰类
* 2. 在放行时,使用我们自己的request
*/
if(req.getMethod().equals("GET")) {
EncodingRequest er = new EncodingRequest(req);
chain.doFilter(er, response);
} else if(req.getMethod().equals("POST")) {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
2.在web.xml配置过滤器
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>cn.itcast.filter.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. EncodingRequest从写requset
package cn.itcast.web.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 装饰reqeust
* @author cxf
*
*/
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) {
throw new RuntimeException(e);
}
return value;
}
}