网上图书商城项目学习笔记-023前端登录过滤器实现

一、流程分析

网上图书商城项目学习笔记-023前端登录过滤器实现_第1张图片

二、代码

1.web.xml

 1 <!-- 登录过滤(订单及购物车只有登录才能访问) -->
 2   <filter>
 3       <display-name>LoginFilter</display-name>
 4       <filter-name>LoginFilter</filter-name>
 5       <filter-class>com.tony.goods.web.servlet.LoginFilter</filter-class>
 6   </filter>
 7   <filter-mapping>
 8       <filter-name>LoginFilter</filter-name>
 9       <url-pattern>/jsps/cart/*</url-pattern>
10   </filter-mapping>
11   <filter-mapping>
12       <filter-name>LoginFilter</filter-name>
13       <servlet-name>CartItemServlet</servlet-name>
14   </filter-mapping>
15   <filter-mapping>
16       <filter-name>LoginFilter</filter-name>
17       <url-pattern>/jsps/order/*</url-pattern>
18   </filter-mapping>
19   <filter-mapping>
20       <filter-name>LoginFilter</filter-name>
21       <servlet-name>OrderServlet</servlet-name>
22   </filter-mapping>

 

2.Filter

(1)LoginFilter.java

 1 package com.tony.goods.web.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 
13 public class LoginFilter implements Filter {
14 
15     @Override
16     public void destroy() {
17         
18     }
19 
20     @Override
21     public void doFilter(ServletRequest request, ServletResponse response,
22             FilterChain chain) throws IOException, ServletException {
23         HttpServletRequest req = (HttpServletRequest) request;
24         Object user = req.getSession().getAttribute("sessionUser");
25         if(user == null) {
26             req.setAttribute("code", "error");
27             req.setAttribute("msg", "您还没有登录,不能访问本资源");
28             req.getRequestDispatcher("/jsps/msg.jsp").forward(req, response);
29         } else {
30             chain.doFilter(request, response);
31         }
32     }
33 
34     @Override
35     public void init(FilterConfig filterConfig) throws ServletException {
36         
37     }
38 
39 }

 

 

你可能感兴趣的:(网上图书商城项目学习笔记-023前端登录过滤器实现)