SpringBoot(五)springboot项目中使用拦截器——实现对未登录请求的拦截

一、创建Controller

package cn.krain.springboot.web;

import cn.krain.springboot.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController {
   

    //登录请求
    @RequestMapping(value = "/login")
    @ResponseBody
    public String userLogin(HttpServletRequest request){
   
        User user = new User();
        user.setId(1001);
        user.setName("lisi");
        request.getSession().setAttribute("user",user);		//登录后将user对象放入到session中
        return "login success";
    }

    //无论用户登录与否都可以访问
    @RequestMapping(value = "/out")
    @ResponseBody
    public String out(){
   
        return "anytime";
    }

    //用户登录后可访问
    @RequestMapping(value = "/detail")
    @ResponseBody
    public String getDetail(){
   
        return "user detail";
    }

    //用户未登录时可以访问
    @RequestMapping(value = "/error")
    @ResponseBody
    public String error(){
   
        return "error";
    }
}
  • User实体对象
package cn.krain.springboot.model;

public class User {
   
    private Integer id;
    private String name;

    public Integer getId() {
   
        return id;
    }

    public void setId(Integer id) {
   
        this.id = id;
    }

    public String getName() {
   
        return name;
    }

    public void setName(String name) {
   
        this.name = name;
    }
}

二、创建拦截器

package cn.krain.springboot.interceptor;

import cn.krain.springboot.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class UserInterceptor implements HandlerInterceptor {
   

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   

        System.out.println("====================进入拦截器====================");

        User user = (User) request.getSession().getAttribute("user");

        if (user == null){
   
            response.sendRedirect("/user/error");       //检测到用户未登录时,跳转到error界面
            return  false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
   

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
   

    }
}

三、创建拦截器配置类

  在项目中创建一个config包,创建一个配置类InterceptorConfig,并实现WebMvcConfigurer接口,覆盖接口中的addInterceptors方法,并为该配置类添加@Configuration注解,标注此类为一个配置类,让Spring Boot扫描到,这里的操作就相当于SpringMVC的注册拦截器,@Configuration 就相当于一个 applicationContext-mvc.xml文件。

package cn.krain.springboot.config;

import cn.krain.springboot.interceptor.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration  //用于定义配置类,相当于applicationContext-mvc.xml文件;
                // 定义一个拦截器,相当于之前的 mvc 里的配置
public class InterceptorConfig implements WebMvcConfigurer {
   

    //所要拦截的请求路径
    String[] addPathPatterns = {
   
        "/user/**"
    };

    //不需要拦截的请求路径
    String[] excludePathPatterns = {
   
        "/user/login","/user/error","/user/out"
    };

    //mvc:interceptor class=""
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
   
        registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
    }
}
全部评论

相关推荐

10-21 23:48
蚌埠坦克学院
csgq:可能没hc了 昨天一面完秒挂
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务