1.注销功能:移除session,返回登录页面即可
(1)编写移除注销功能的servlet
1 package com.xiaoma.servlet.user; 2 3 import com.xiaoma.util.Constants; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 11 public class LogoutServlet extends HttpServlet { 12 @Override 13 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 14 //移除session 15 req.getSession().removeAttribute(Constants.USER_SESSION); 16 //重定向到登录页面 17 resp.sendRedirect(req.getContextPath()+"/login.jsp"); 18 } 19 20 @Override 21 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 22 doGet(req, resp); 23 } 24 }
(2)在web.xml中注册我们的servlet,注意这里的url-patten是走的前端的jsp/common/head.jsp下的退出走的那个url
(3)效果图
----------------------------------------------------------------------------------------------------------------------------------------------------------------
2. 登录权限拦截
(1)在filter文件夹下创建一个SysFilter类文件,用来进行登录拦截,所需的error.jsp页面链接:https://pan.baidu.com/s/1UKtUbRBphFyIlk6RU9aR9g提取码:5210
1 package com.xiaoma.filter; 2 3 import com.xiaoma.pojo.User; 4 import com.xiaoma.util.Constants; 5 6 import javax.servlet.*; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 11 12 public class SysFilter implements Filter { 13 14 @Override 15 public void init(FilterConfig filterConfig) throws ServletException { 16 17 } 18 19 @Override 20 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { 21 //request用来获取session,request用来重定向 22 HttpServletRequest request=(HttpServletRequest) req; 23 HttpServletResponse response=(HttpServletResponse) resp; 24 25 //获取session 26 User user=(User) request.getSession().getAttribute(Constants.USER_SESSION); 27 28 //用户session为空,就说明用户已经注销了,或者未登录 29 if (user == null) { 30 response.sendRedirect(((HttpServletRequest) req).getContextPath()+"/error.jsp"); 31 }else{ 32 filterChain.doFilter(req,resp); 33 } 34 } 35 36 @Override 37 public void destroy() { 38 39 } 40 }
(2)在web.xml中注册过滤器
1 <!--注册权限拦截过滤器--> 2 <filter> 3 <filter-name>SysFilter</filter-name> 4 <filter-class>com.xiaoma.filter.SysFilter</filter-class> 5 </filter> 6 <filter-mapping> 7 <filter-name>SysFilter</filter-name> 8 <url-pattern>/jsp/*</url-pattern> 9 </filter-mapping>
(3)运行测试效果