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}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM