前臺中某些位置可以不登陸就可以訪問,而還有一些模塊只有登入用戶才能訪問! 哪些模塊只有登錄用戶才能訪問: 1.購物車 jsp:/jsp/cart/* servlet:CartItemServlet 2.訂單 jsp:/jsp/order/* servlet:OrderServlet 1.web.xm ...
前臺中某些位置可以不登陸就可以訪問,而還有一些模塊只有登入用戶才能訪問!
哪些模塊只有登錄用戶才能訪問:
1.購物車 jsp:/jsp/cart/* servlet:CartItemServlet
2.訂單 jsp:/jsp/order/* servlet:OrderServlet
1.web.xml
<filter> <filter-name>LoginFilter</filter-name> <filter-class>cn.itcast.goods.web.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/jsps/cart/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <servlet-name>CartItemServlet</servlet-name> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/jsps/order/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <servlet-name>OrderServlet</servlet-name> </filter-mapping>
2.LoginFilter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* * 1. 獲取session中的user * 2. 判斷是否為null * > 如果為null:保存錯誤信息,轉發到msg.jsp * > 如果不為null:放行 */ HttpServletRequest req = (HttpServletRequest) request; Object user = req.getSession().getAttribute("sessionUser"); if(user == null) { req.setAttribute("code", "error");//為了顯示X圖片 req.setAttribute("msg", "您還沒有登錄,不能訪問本資源"); req.getRequestDispatcher("/jsps/msg.jsp").forward(req, response); } else { chain.doFilter(request, response);//放行 } }