JAVA过滤器
对于get请求和post请求全局过滤:
自己创建一个类,实现HttpServletRequestWrapper接口
package com.dh.deno;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
public class FilterSetRequest extends
HttpServletRequestWrapper {
public FilterSetRequest(HttpServletRequest request){
super(request);
}
@Override
public String getParameter(String name){
String value = super.getParameter(name);
//判断是否是使用get请求
if(getMethod().equalsIgnoreCase("GET")){
try
{
value = new String(value.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return value;
}
}
在Filter类中使用自己定义的reqest
package com.dh.deno;
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 com.sun.net.httpserver.Filter.Chain;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
public class MyFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//掉包的request
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
FilterSetRequest req = new FilterSetRequest((HttpServletRequest)request);
chain.doFilter(req, response);
}
public void init(FilterConfig arg0)
throws ServletException {
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。