Java-Filter实现权限拦截

白衣少年
2022-11-29 / 0 评论 / 31 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月29日,已超过457天没有更新,若内容或图片失效,请留言反馈。
要求:用户登录之后才能进入主页,用户注销后就不能进入主页了!

首先我们写一个登录的页面

<h1>登录</h1>
<form action="/servlet/login" method="post">
    <input type="text" name="username">
    <input type="submit">
</form>

然后登录的 servlet ,登录成功或者登录失败

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端请求的参数
        String username = req.getParameter("username");
        if (username.equals("admin")){ //登录成功
            req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp"); //假如用户名正确,就重定向到sys/success.jsp
        }else { //登录成功
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

然后写一个登录失败的jsp,注销后跳转到登录界面

<h1>错误</h1>
<h3>没有权限,用户名错误</h3>

<p><a href="/Login.jsp">返回登录页面</p>

我们发现无论成功与否都能进入成功主页:所以我们添加一个过滤器
注销后移除session

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object user_session = req.getSession().getAttribute("USER_SESSION");
        if (user_session!=null){
            req.getSession().removeAttribute("USER_SESSION");
            resp.sendRedirect("/Login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

添加过滤器

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //通过强转拿到session
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (request.getSession().getAttribute("USER_SESSION")==null){
            response.sendRedirect("/error.jsp");
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

这样过滤以后就拦截了进入主页
为了节约性能:我们建一个文件来放我们的 USER_SESSION------>Constant

public class Constant {
    public final static String USER_SESSION = "USER_SESSION";
}

效果:
filter实现拦截.png

2

打赏

评论 (0)

OwO
取消