欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringBoot拦截器实现登录拦截的示例代码

时间:2023-03-15 09:24:29|栏目:JAVA代码|点击:

可以对URL路径进行拦截,可以用于权限验证、解决乱码、操作日志记录、性能监控、异常处理等

 实现代码

新建 interceptor包

添加拦截器代码

package com.qcby.interceptor;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
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;
 
public class LoginInterceptor  implements HandlerInterceptor {
 
    @Autowired
    private HttpSession httpSession;
    //Controller逻辑执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle....");
        String uri = request.getRequestURI();
        System.out.println("当前路径"+uri);
 
        /**
         * HandlerMethod=>Controller中标注@RequestMapping的方法
         *  需要配置静态资源不拦截时,添加这块逻辑  => 前后端分离项目
         */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (httpSession.getAttribute("username") == null) {
            // 未登录跳转到登录界面
            throw  new RuntimeException("no login!");
        } else {
            return true;
        }
    }
 
    //Controller逻辑执行完毕但是视图解析器还未进行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }
 
    //Controller逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion....");
    }
}

注册,配置拦截路径和排除登录需访问路径

package com.qcby.config;
 
import com.qcby.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                // 那些路径不拦截
                .excludePathPatterns("/user/login","/error");
    }
 
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }
}

实现类

@RestController
@RequestMapping("user")
public class UserController {
@Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;
    @ApiOperation("用户登录接口")
    @RequestMapping(value="login",method = {RequestMethod.GET,RequestMethod.POST})
    public Map<String,Object>login(User user){
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
            map.put("msg","用户或密码为空!");
            return map;
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername())
                .eq("password",user.getPassword());
        User user1=userService.getOne(queryWrapper);
        if(user1!=null){
            map.put("cod",1);
            map.put("data",user1);
            session.setAttribute("username",user1.getUsername());
        }else {
            map.put("msg","用户名或密码错误!");
        }
        return map;
    }
}

当我们未登录时我们不能进入拦截的页面 

 登录

登录之后我们就能进入hello方法了 

上一篇:SpringBoot2零基础到精通之配置文件与web开发

栏    目:JAVA代码

下一篇:学生视角看Java 面向对象的继承本质

本文标题:SpringBoot拦截器实现登录拦截的示例代码

本文地址:http://www.codeinn.net/misctech/227468.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有