package day31_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;
/**
* 处理全站乱码--Filter(过滤器)
*2022年3月30日下午5:10:24
* @author tao
*/
@WebFilter("/*")
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 {
//处理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().equalsIgnoreCase("GET")) {
EncodingRequest er = new EncodingRequest(req);
chain.doFilter(er, response);
}else if(req.getMethod().equalsIgnoreCase("POST")) {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
?下面是需要用到的装饰类
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
装饰类是为扩展类的功能
package day31_Filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;
/**
* 装饰request
*2022年3月30日下午5:12:38
* @author tao
* HttpServletRequestWrapper类 -->实现了HttpServletRequest接口
*/
public class EncodingRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public EncodingRequest(HttpServletRequest request) {
super(request);
// TODO Auto-generated constructor stub
this.request = request;
}
public String getParameter(String name) {
// TODO Auto-generated method stub
String value = request.getParameter(name);
//处理编码问题
try {
value = new String(value.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
return value;
}
}
|