从零开始系列——Filter过滤器常见两大用法
EncodingFilter
在Web开发中经常需要对请求和响应进行字符编码,通常采用的是UTF-8。如果每一次都需要在Servlet中进行设置,就会显得代码臃肿。
解决方法:Filter(过滤器)
使用方法:创建一个Java类并且实现Filter这个接口
Filter接口提供了init(初始化方法),doFilter(过滤方法),destroy(销毁方法)三种方法
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class EncodingFilter implements Filter { private String encoding = null; public void init(FilterConfig filterConfig) throws ServletException { // 从Web.xml中进行初始化值的配置 encoding = filterConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); filterChain.doFilter(request,response); } public void destroy() {} }
Web.xml中注册过滤器
<filter> <filter-name>encoding</filter-name> <filter-class>com.code.global.EncodingFilter</filter-class> <!-- 初始化值 --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <!-- /*表示对所有的请求地址进行过滤 --> <url-pattern>/*</url-pattern> </filter-mapping>
LoginFilter
针对一些跳过登陆的使用人进行过滤
思路:用户一旦登陆成功后,将对应信息存入到session中,过滤器只要对那些需要登陆后操作的地址进行过滤即可
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AccountFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException {} public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; // 获得登陆成功后的session值 Object object = request.getSession().getAttribute("User"); if (object==null) // 没有登陆 response.sendRedirect("/Login/login.do"); else filterChain.doFilter(request,response); } public void destroy() {} }
Web.xml配置
<filter> <filter-name>User</filter-name> <filter-class>com.code.global.AccountFilter</filter-class> </filter> <filter-mapping> <filter-name>User</filter-name> <!-- 需要过滤的请求地址 只要是/Admin/xxx的请求都会进行登陆过滤 --> <url-pattern>/Admin/*</url-pattern> </filter-mapping>