【SpringBoot】九、配置拦截器和过滤器实现验证登录

目录

目的

一、让内置服务器支持JSP

二、拦截器

三、过滤器

1. 写过滤器

2. 在入口类配置

四、控制器类

五、前端


目的

想让后端作API接口,给我请求,给你数据。后端返回json数据,包括状态码、数据等。SpringMVC不处理jsp视图,改为json视图(关于json视图上一章已提及)。那么页面跳转交由前端ajax处理,jsp页面放到webapp下,不搞WEB-INF。交由控制器的请求让拦截器拦截,前端的jsp请求过滤器搞定。

一、让内置服务器支持JSP

        <!--内置tomcat对Jsp支持的依赖,用于编译Jsp-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- 开启servlet支持 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>

二、拦截器


/**
 * 关于登录拦截的配置
 *
 * @author ZRH
 * @version 1.0.0
 * @date 2020/9/3
 */
@Configuration
public class LoginConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 建造者模式
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/login").excludePathPatterns("/logout")
                .excludePathPatterns("/js/**").excludePathPatterns("/css/**").excludePathPatterns("/img/**");
    }
}

三、过滤器

1. 写过滤器

注意@WebFilter是Servlet3.0的,不是SpringBoot的。因为写成SpringBoot的配置类还要写两个类,麻烦。

/**
 * 登录过滤器,过滤非法访问需要登录的jsp
 *
 * @author ZRH
 * @version 1.0.0
 * @date 2020/9/3
 */
@Slf4j
@WebFilter(urlPatterns = "*.jsp", filterName = "loginFilter")
public class LoginFilter 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 res = (HttpServletResponse) servletResponse;
        String path = req.getContextPath();
        String indexPath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/pages/login.jsp";

        Object loginUser = req.getSession().getAttribute(CommonConstant.LOGIN_EMPLOYEE);
        if (!req.getRequestURI().endsWith("login.jsp") && loginUser == null) {
            res.sendRedirect(indexPath);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

2. 在入口类配置

@SpringBootApplication
@MapperScan("com.winrh.mapper")
@ServletComponentScan("com.winrh.filter")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

四、控制器类

封装状态码、数据,返回DTO

@RestController
public class LoginController extends BaseController {


    @Autowired
    EmployeeService employeeService;

    /**
     * 登录
     * <p>
     *
     * @param employeeDomain 员工实体类
     * @return org.springframework.web.servlet.ModelAndView
     * @author ZRH
     * @date 2020-08-18
     * @version 1.0.0
     */
    @PostMapping(value = "/login")
    public RestResultDTO<Object> login(@RequestBody EmployeeDomain employeeDomain, HttpSession session) {
        return handleMessage(employeeService.checkAccount(employeeDomain, session), session.getAttribute(CommonConstant.LOGIN_EMPLOYEE));
    }


    /**
     * 退出系统
     * <p>
     *
     * @param session
     * @return
     * @author ZRH
     * @date 2020-08-19
     * @version 1.0.0
     */
    @DeleteMapping(value = "/logout")
    public RestResultDTO<Long> logout(HttpSession session) {
        session.setAttribute(CommonConstant.LOGIN_EMPLOYEE, null);
        return handleMessage(StatusCodeConstant.SUCCESS_STATUS_CODE);
    }
}

五、前端

使用Ajax发送接收并跳转

<script type="text/javascript">
    function login() {
        let account = $("#account").val();
        let password = $("#password").val();
        let url = "${pageContext.request.contextPath}/login";
        let data = {"account": account, "password": password};
        console.log(data);
        $.ajax({
            type: 'POST',
            url: url,
            contentType: "application/json",
            data: JSON.stringify(data),
            dataType: 'json',
            timeout: 3000,
            cache: false,
            async: true,
            success: function (data) {
                console.log(data);
                alert(data.message);
                if(data.data.hasOwnProperty('type')){
                    let type = data.data.type;
                    console.log(type);
                    if(type == 0){
                        window.location.href="${pageContext.request.contextPath}/pages/admin/index.jsp";
                    }else if (type == 1){
                        window.location.href="${pageContext.request.contextPath}/pages/employee/index.jsp";
                    }
                }

            }
        });
    }

</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

winrh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值