思路:移除session对象+返回登陆页面
package com.thhh.servlet.user; import com.thhh.utils.Constants; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().removeAttribute(Constants.USER_SESSION);//移除用户session resp.sendRedirect(req.getContextPath()+"/login.jsp");//重定向回登陆页面 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<!--注册注销servlet--> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.thhh.servlet.user.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/jsp/logout.do</url-pattern> </servlet-mapping>
1.编写过滤器
package com.thhh.filter; import com.thhh.pojo.User; import com.thhh.utils.Constants; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SysFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req;//父类强转子类,用于获取session HttpServletResponse response = (HttpServletResponse) resp;//父类强转子类,用于重定向 User user = (User) request.getSession().getAttribute(Constants.USER_SESSION); if (user==null){//用户处于未登陆状态 response.sendRedirect(request.getContextPath()+"/error.jsp");//重定向到登陆页面 }else{ chain.doFilter(req,resp);//过滤器放行 } } @Override public void destroy() { } }
2.注册过滤器
<!--注册未登录时请求后台页面过滤器--> <filter> <filter-name>SysFilter</filter-name> <filter-class>com.thhh.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <url-pattern>/jsp/*</url-pattern> <!--注意:我们将所有需要登陆之后才能访问的功能性页面给都放在了/jsp文件夹下,所以过滤器应该过滤这个文件夹下的请求--> </filter-mapping>
3.导入error页面
4.测试功能
测试完成!