登录功能优化
注销功能:
Servlet代码xml注册 登录拦截优化
编写一个过滤器xml注册过滤器 登录功能优化 注销功能:
思路:移除session,返回登录页面
Servlet代码package com.yang.servlet.user;import com.yang.util.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 { //移除用户的session req.getSession().removeAttribute(Constants.USER_SESSION); resp.sendRedirect("/login.jsp");//返回登录页面 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
xml注册
package com.yang.filter;import com.yang.pojo.User;import com.yang.util.Constants;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; //从session中获取用户 User user = (User) request.getSession().getAttribute(Constants.USER_SESSION); if (user==null){//已经被移除或者注销,或者未登录 response.sendRedirect("smbms/error.jsp"); }else { chain.doFilter(req,resp); } } public void destroy() { }}
xml注册过滤器