springboot拦截器实例

首先我们要知道springboot拦截器可以做什么?

他可以对你加入限制访问条件的URL路径进行非法拦截,可以用于权限验证、解决乱码、操作日志记录、性能监控、异常处理等

首先我们首先我们需要在pom.xml引入一些主要使用依赖

  <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

接下来创建一个component包

 在里面创建一个WebMvcConfigurer:继承WebMvcConfigurationSupport类,重写下面介绍到的addInterceptors方法


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.WebMvcConfigurationSupport;

//这个注解不能忘记添加让他被spring容器创建管理
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
// 重写addInterceptors方法添加需要拦截的和不需要拦截的
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        InterceptorRegistration registration = registry.addInterceptor(new AuthorityInterceptor());


          //拦截器是按照顺序执行的
         //addPathPatterns 用于添加拦截规则
         //excludePathPatterns 用于排除拦截
		 
         //我这里拦截了所有请求
        registration.addPathPatterns("/**");
    }
}

添加Interceptors方法继承Hanlder方法

import com.example.sell.dataobject.SellerInfo;
import com.example.sell.dto.UserDTO;
import com.example.sell.enums.ResultEnum;
import com.example.sell.except.SellException;
import lombok.extern.slf4j.Slf4j;
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;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class Interceptor implements HandlerInterceptor {
//设置不拦截静态的URI
    private static final Set<String> URI = new HashSet<>();
    //不拦截的URI
    static {
//根据自己需要修改

        URI.add("/user/index.html");
        URI.add("/user/index");
        URI.add("/user/doLogin");
        URI.add("/user/doLoginTest");
        URI.add("/user/verifyCode");
    }
   
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object object) throws Exception {
        String uri = request.getRequestURI();
        if (URI.contains(uri)) {
            log.info("不拦截" + uri);
            return true;
        }
        log.info("拦截" + uri);
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        if (userDTO == null) {
//这是我自己写的错误提示,大家可用系统的也可以自己写
            throw new SellException(ResultEnum.USER_NOT_LOGIN);
        }
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception {
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}

现在来写控制层

UserController
//登录
    @PostMapping("/doLogin")
    public ModelAndView doLogin(@RequestParam(value = "userName",required = false) String userName,
                                @RequestParam(value = "passWord",required = false) String passWord
                                ,Map<String,Object> map,HttpServletRequest request,
                                HttpServletResponse response){
用户实体类
        User user = new User();
        try {
//
            user = userService.findOne(userName,passWord);
//用于存储用户session信息
            UserDTO userDTO = new UserDTO();
//复制user查询到的信息复制给userDTO
            BeanUtils.copyProperties(user,userDTO);
//获得user信息存储在map里面
            map.put("user ",user );
//存储userDTO信息进session
            request.getSession().setAttribute("userDTO",userDTO);
//这段忽略
/*
            if (userDTO != null){
                String userId1 =userDTO.getUserId();
                String passWord1= userDTO.getPassWord();
                //生成token并存入数据返回
                String token = JwtUtil.sign(userId1,passWord1);
                System.out.println("token值为:");
                System.out.println(token);
                map.put("token",token);
            }*/
        }catch (SellException e){
            map.put("msg",e.getMessage());
            map.put("url","/user/index");
            return new ModelAndView("common/error",map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("url", "/seller/order/list");
        return  new ModelAndView("common/loginsuccess",map);

    }

前端登录页面就不举例了

好了拦截器到这里就制作完成了

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Lsnow1228

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

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

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

打赏作者

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

抵扣说明:

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

余额充值