springmvc拦截器

过滤器与拦截器的区别
过滤器:servlet规范中的一部分,任何javaweb工程都可以使用,在url-pattern中配置 /* 之后,可以对所有访问资源进行过滤

拦截器:拦截器是aop思想的具体应用,拦截器是springmvc框架自己的,只有使用了springMVC 框架的工程才能使用
拦截器只会拦截访问的控制器方法,如果访问的是jsp/html/css/image/js 是不会拦截的

步骤:1,编写一个拦截器 实现HandlerInterceptor接口
2 拦截器注册到容器中 实现WebMvcConfigurer 的addInterceptors
3 指定拦截规则,如果是拦截所有 静态资源也会被拦截

拦截器
需要实现HandlerInterceptor接口

package com.example.springboothuotai02.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录检查,
 * 1  配置好拦截器要拦截哪些请求,
 * 2  把这些配置放在容器中
 */
public class Loginterceptor implements HandlerInterceptor {


    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     *       前置拦截
     *
     * request : 是指经过spring封装的请求对象, 包含请求地址, 头, 参数, body(流)等信息.
     * response:是指经过spring封装的响应对象, 包含输入流, 响应body类型等信息.
     * handler,是指controller的@Controller注解下的"完整"方法名, 是包含exception等字段信息的.
     *
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return HandlerInterceptor.super.preHandle(request, response, handler);

        //登录检查逻辑

        HttpSession session = request.getSession();//
        Object loginUser = session.getAttribute("loginUser");//查看session里边  有没有放登录的用户

        if (loginUser!=null){


            return true;

        }else {
                        request.setAttribute("msg","nononono");
                        response.sendRedirect("/");//重定项 让它跳转到首页
//            request.getRequestDispatcher("/index.html").forward(request,response);
//            session.setAttribute("msg","sadasd");

            return  false;
        }

    }


    /**
     *      后置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    /**
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     *
     *      输出之前的 最后的拦截
     *
     */

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

配置拦截器 设置要拦截的请求

package com.example.springboothuotai02.config;


import com.example.springboothuotai02.interceptor.Loginterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 这个类 用来配置拦截器 要拦截什么请求
 */
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

    /**
     *              配置拦截器 要拦截什么请求
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //  添加配置好的拦截器
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new Loginterceptor());

        interceptorRegistration
        .addPathPatterns("/**")//设置要拦截的条件 /**  表示全都拦截
        .excludePathPatterns("/","/login","/css/**", "/js/**","/images/**","/fonts/**");//配置需要放行的对象

    }
}

登录请求

package com.example.springboothuotai02.controller;


import com.example.springboothuotai02.bean.User;
import org.codehaus.groovy.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class IndexConller {


    /**
     *      登录页面
     *
     * @return
     */
    @GetMapping(value = {"/","/login"})
    public String login(){

        return  "login";
    }


    @PostMapping("/login")
    public  String index(User user, HttpSession session, Model model){

            if (StringUtils.hasLength(user.getUsername()) && StringUtils.hasLength(user.getPasswrod())){

                //把登录成功的用户保存起来
                session.setAttribute("loginUser",user);
                //重定项 意思是登录成功  重定项到index.html
                return "redirect:/index.html";
            }else{
                model.addAttribute("msg","账号或密码错误");
                return "login";
            }



    }


    /**
     *      去index页面
     * @return
     */
    @GetMapping("/index.html")
    public String indexPage(HttpSession session,Model model){
        //如果登录框和密码框不为空 则允许登录
            Object obj=session.getAttribute("loginUser");
            if (obj!=null){

                return  "index";
            }else {
                model.addAttribute("msg","账号或密码错误");
                return  "login";
            }

//        if ()

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值