文章目录
项目资源可以从我的github上获取
https://github.com/chiyu999/smbms.git
三、登录功能优化(注销及权限过滤)
3.1、注销
1、编写servlet
package com.zhang.servlet.user;
import com.zhang.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 {
//移除用户session
req.getSession().removeAttribute(Constants.USER_SESSION);
if (req.getSession().getAttribute(Constants.USER_SESSION) == null){
System.out.println("成功移除用户session,返回登录页面");
}
//返回登录页面
resp.sendRedirect("login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2、注册servlet
<!--退出登录Servlet-->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.zhang.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout.do</url-pattern>
</servlet-mapping>
3.2、登录拦截优化
登录成功,然后退出,退出之后发现用链接进去frame.jsp页面也能进去
退出系统后进入的页面
于是要写个登录拦截器去拦截所有请求,如果用户为登录,则不能进入后台页面
1、编写Filter
package com.zhang.filter;
import com.zhang.pojo.User;
import com.zhang.utils.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SystemFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
//过滤器,从session中获取用户
User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
if (user ==<