idea生成SpringBoot項目和攔截器設置

maven創建springBoot工程很簡單:

File-->new-->project-->Spring Initializr-->next-->next-->web-->web

裏面自動生成了一個啓動類SpringbootExampleApplication:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootExampleApplication.class, args);
    }
}

自定義一個Controller:

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello/{userId}")
    public String say(@PathVariable("userId") Integer userId){
        System.out.println("進入controller中的say方法");
        return "Hello:" + userId;
    }

    @ResponseBody
    @RequestMapping("/search")
    public List<String> getAllInfo(){
        List<String> res = new ArrayList<>();
        res.add("wqh");
        res.add("hello");
        res.add("end");
        return res;
    }
}

右擊SpringbootExampleApplication,選擇Debug,發現tomcat已經啓動。

測試均沒問題:

http://localhost:8080/hello/4    

http://localhost:8080/search

有時候需要自定義一個SpringBoot攔截器完成相關需求。

定義一個攔截器:

@Component
public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>在請求處理之前進行調用(Controller方法調用之前)");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>請求處理之後進行調用,但是在視圖被渲染之前(Controller方法調用之後)");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>在整個請求結束之後被調用,也就是在DispatcherServlet 渲染了對應的視圖之後執行(主要是用於進行資源清理工作)");
    }
}

配置類:

@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    @Autowired
    MyInterceptor1 myInterceptor1;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor1).addPathPatterns("/**").excludePathPatterns("/search");//選擇過濾的url請求
    }
}

實現WebMvcConfigurer接口,不要繼承WebMvcConfigurerAdapter這個類,因爲該類已經過時,也不要繼承WebMvcConfigurationSupport這個類,因爲該類會使WebMvc自動失效。可參考:

https://blog.csdn.net/qq_35299712/article/details/80061532

參考:

https://www.jianshu.com/p/dc5cc2e25ab2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章