先是filter对象
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request2=(HttpServletRequest) request;//进行类型转换,转换为http类型的,
//设置编码为utf-8
response.setContentType("text/html;charset=UTF-8");//处理响应编码
request.setCharacterEncoding("UTF-8");
if(request2.getMethod().equals("GET")){//调用getMethod的方法与方法进行比较
//当方法为GET方法时
//将当前的requet修改为我们自己的request
codRequest request3=new codRequest(request2);
chain.doFilter(request3, response);//将当前自动请求对象转发到doFilter的
}else if(request2.getMethod().equals("POST")){
//当方法为post请求时调用此方法
chain.doFilter(request, response);
}
}自定义的class类继承自 HttpServletRequestWrapper:
package cn.edu.nsu.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class codRequest extends HttpServletRequestWrapper {
private HttpServletRequest request=null;
public codRequest(HttpServletRequest request) {
super(request);
this.request=request;
}
public String getParameter(String name) {
String ss=null;
try {
ss=new String(request.getParameter(name).getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);//将异常抛出
}
return ss;//返回被修改了的字符串
}
}jsp的测试代码:
<body>
<a href="<c:url value='/testServlet'/>?op=中文乱码?">超链接</a>
<form action="<c:url value='/testServlet' />" method="post">
<input type="text" name="name"/>
<input type="submit" />
</form>
</body>