靜態資源
首先需要了解的是SpringBoot和之前的SpringMVC不太一樣,SpringBoot對jsp頁面的支持性很差,大家都知道jsp頁面一般用在tomcat服務器上,而tomcat服務器一般需要war直接運行,SpringBoot一般不打war,一般打成jar。
Spring Boot 默認為我們提供了靜態資源處理,使用 WebMvcAutoConfiguration 中的配置各種屬性。
建議大家使用Spring Boot的默認配置方式,
攔截器
攔截器這玩意兒不多說了,一般寫過SpringMVC的應該都寫過,SpringBoot中本質上也差不多要實現攔截器功能需要完成以下2個步驟:
- 1.創建我們自己的攔截器類並實現 HandlerInterceptor 接口
- 2.其實重寫WebMvcConfigurerAdapter中的addInterceptors方法把自定義的攔截器類添加進來即可
package com.gwd.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub System.out.println(">>>MyInterceptor>>>>>>>在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行(主要是用於進行資源清理工作)"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println(">>>MyInterceptor>>>>>>>請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后)"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println(">>>MyInterceptor>>>>>>>在請求處理之前進行調用(Controller方法調用之前)"); return true;// 只有返回true才會繼續向下執行,返回false取消當前請求 } }
package com.gwd.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.gwd.interceptor.MyInterceptor; @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns 用於添加攔截規則 // excludePathPatterns 用戶排除攔截 //addPathPatterns("/**")對所有請求都攔截,但是排除了/others和/login請求的攔截 registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*").excludePathPatterns("/login","/others"); super.addInterceptors(registry); } }
addPathPatterns對所有請求都攔截,但是排除了login和others(用逗號分隔開來)請求的攔截。
Controller:
package com.gwd.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @RequestMapping("/hello") public String index() { return "hello"; } @RequestMapping("/login") public String login() { return "login"; } }