Java教程

拦截器Filter

本文主要是介绍拦截器Filter,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.xxx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截非法访问index.jsp
 */
@WebFilter("/*")
public class fil2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //未登录跳入登录界面
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        //获取请求路径
        String url= req.getRequestURI();
        System.out.println(url);
        //放行登录界面(包括各种静态资源以及各种操作)
        if(url.contains("/login.jsp")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(url.contains("/js")||url.contains("/image")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(url.contains("/loginServlet")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //已经登录状态
        String uname=(String) req.getSession().getAttribute("uname");
        if(uname!=null){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        resp.sendRedirect("login.jsp");


    }

    @Override
    public void destroy() {

    }
}
package com.xxx.servlet;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class Login extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if(true){
            req.getSession().setAttribute("uname","uname");
            resp.sendRedirect("index.jsp");
        }else{
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="loginServlet" method="post">
        uname:<input name="uname"><br>
        <button>submit</button>
    </form>

</body>
</html>
这篇关于拦截器Filter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!