http://pengenjing.iteye.com/blog/1607248
这里写的过滤器用的是适配器模式,思路为:
先写一个类实现Filter,然后在让你写的过滤器来继承自这个类;
步骤:1.建一个AbstractFilter实现Filter;2.建一个类来继承AbstractFilter,还要在web.xml中配置;
web.xml中的配置:
- <filter>
- <filter-name>validateFilter</filter-name>
- <filter-class>com.peng.ValidateFilter(这里写的是类的完全限定名)</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>validateFilter</filter-name>
- <url-pattern>/*(这里是让所有的通过)</url-pattern>
- </filter-mapping>
Abstractr.java
- public abstract class AbstractFilter implements Filter{
- public void destroy() {}
- public abstract void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException ;
- public void init(FilterConfig filterConfig) throws ServletException {}
- }
下面是我自己写的过滤器:我给他取名为 ValidateFilter;
ValidateFilter.java
- package com.kaishengit.web.filter;
- import java.io.IOException;
- import javax.servlet.FilterChain;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import com.kaishengit.entity.User;
- import com.kaishengit.util.Const;
- public class ValidateFilter extends AbstractFilter{
- @Override
- public void doFilter(ServletRequest req, ServletResponse resp,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) resp;
- //判断如果是index.jspx 放行
- String uri = request.getRequestURI();
- uri = uri.substring(uri.lastIndexOf("/")+1);
- //System.out.println("当前请求的路径: " + uri);
- if("".equals(uri) || "index.jsp".equals(uri) || "index.jspx".equals(uri) || "login.jspx".equals(uri) || uri.endsWith("png") || uri.endsWith("jpg")) {
- //所有人都能请求到的URI,放行
- chain.doFilter(request, response);
- } else { //下面是判断是否有session,也就是用户是否已登录状态;
- HttpSession session = request.getSession();
- User user = (User) session.getAttribute(Const.USER_IN_SESSION);
- if(user == null) {
- System.out.println("URI:" + uri + ">>>>访问被拒绝!");
- response.sendRedirect("index.jspx?code=10002");
- } else {
- chain.doFilter(request, response);
- }
- }
- }
- }