java spring boot 拦截器 实现未登录用户不能登录

java spring boot  拦截器 实现未登录用户不能登录

拦截器可以理解为PHP的前置控制器  运行控制器前的触发

 

1 先创建个拦截器

package com.example.demo212;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.hutool.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("user") == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                JSONObject res = new JSONObject();
                res.put("success", false);
                res.put("message", "用户未登录!");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500);
                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 {

    }
}

2 写拦截器配置

package com.example.demo212;

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 InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器
        InterceptorRegistration ir = registry.addInterceptor(new MyInterceptor());
        // 添加拦截请求
        ir.addPathPatterns("/*");
        // 添加不拦截的请求
        ir.excludePathPatterns("/login");

        // 以上三句代码可以使用下面的代替
        // registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*").excludePathPatterns("/login");
    }
}
package com.example.demo212;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.*;


@SpringBootApplication
@RestController
@Validated
public class Demo212Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo212Application.class, args);
    }
    @RequestMapping("/getUser")
    public String getUserStr(String name, Integer age) {
        return "name: " + name + " ,age:" + age;
    }
    @GetMapping("/login")
    public String Login(){
        return "login";
    }

    @GetMapping("/add")
    public String add(){
        return "add";
    }
}

运行http://localhost:8080/add

显示

{"message":"用户未登录!","success":false}
posted @ 2020-04-24 19:54  newmiracle宇宙  阅读(2129)  评论(0编辑  收藏  举报