Filterservlet.java
package com.xxpx.servlet;
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 javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.xxpx.bean.User;public class FilterTest implements Filter{ @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)servletRequest; String requestURI = request.getRequestURI(); int lastIndexOf = requestURI.lastIndexOf("/"); String substring = requestURI.substring(lastIndexOf+1); if("login.jsp".equals(substring)){ arg2.doFilter(servletRequest, servletResponse); }else{ HttpServletResponse response = (HttpServletResponse)servletResponse; HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if(user==null){ response.sendRedirect("login.jsp"); }else{ arg2.doFilter(servletRequest, servletResponse); } } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub System.out.println("开始过滤"); }}web.xml配置
<filter>
<filter-name>test</filter-name> <filter-class>com.xxpx.servlet.FilterTest</filter-class> </filter> <filter-mapping> <filter-name>test</filter-name> <url-pattern>/houtai/pages/*</url-pattern> <url-pattern>/houtai/main.jsp</url-pattern> </filter-mapping>