在web.xml配置filter
<!-- 登录认证过滤器 -->
<filter>
<filter-name>UserFilter</filter-name>
<filter-class>com.filter.UserFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>UserFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
后台class
public class UserFilter implements Filter{ @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse resp = (HttpServletResponse)response; HttpServletRequest req = (HttpServletRequest)request; HttpSession session = req.getSession(); User user = (User)session.getAttribute("user"); String uri = req.getRequestURI(); //简单判断缓存中是否有用户 if(user==null){//没有用户 //判断用户是否是选择跳到登录界面 if(uri.endsWith("login.jsp")||uri.endsWith("login.do")){ chain.doFilter(request, response); }else{ resp.sendRedirect(req.getContextPath()+"/login.jsp"); } }else{//有用户 chain.doFilter(request, response); } chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
首先要在登录时把user存到session中