參考於:https://www.cnblogs.com/myitnews/p/11565941.html#autoid-1-0-0html
Spring Web MVC是一種基於Java的實現了Web MVC設計模式的請求驅動類型的輕量級Web框架,即便用了MVC架構模式的思想,將web層進行職責解耦,基於請求驅動指的就是使用請求-響應模型,框架的目的就是幫助咱們簡化開發,Spring Web MVC也是要簡化咱們平常Web開發的。與之相反的是基於組件的、事件驅動的Web框架,如Tapestry、JSF等。前端
- 前端控制器是DispatcherServlet;
- 應用控制器其實拆爲處理器映射器(Handler Mapping)進行處理器管理和視圖解析器(View Resolver)進行視圖管理;
- 頁面控制器/動做/處理器爲Controller接口(僅包含ModelAndView handleRequest(request, response) 方法)的實現(也能夠是任何的POJO類);
- 支持本地化(Locale)解析、主題(Theme)解析及文件上傳等;
- 提供了很是靈活的數據驗證、格式化和數據綁定機制;
- 提供了強大的約定大於配置(慣例優先原則)的契約式編程支持。
用戶請求發送給DispatcherServlet,DispatcherServlet調用HandlerMapping處理器映射器;java
HandlerMapping根據xml或註解找到對應的處理器,生成處理器對象【其實返回的是一個執行器鏈:包含handler和多個攔截器Interceptor】返回給DispatcherServlet;web
DispatcherServlet會調用相應的HandlerAdapter;spring
HandlerAdapter通過適配調用具體的處理器去處理請求,生成ModelAndView返回給DispatcherServlet編程
DispatcherServlet將ModelAndView傳給ViewReslover解析生成View返回給DispatcherServlet;json
DispatcherServlet根據View進行渲染視圖,最後響應給用戶。設計模式
相似的表示組件做用的還有:架構
return new ModelAndView("index")
。@RestController public class HelloController { @GetMapping("/hello") public String hello(){ return "this is my spring-boot-quick-start..."; } @GetMapping("go") public ModelAndView go(){ ModelAndView mv = new ModelAndView("index"); return mv; } }
ExceptionHandler
,捕獲Controller中拋出指定類型的異常。@ControllerAdvice public class GlobalExceptionHandler { @ResponseBody @ExceptionHandler(value = ApiException.class) public AjaxResult handle(ApiException e){ if(e.getErrorCode()!=null){ return AjaxResult.error(e.getErrorCode().getCode(), e.getMessage()); } return AjaxResult.error(e.getMessag()); } }
@ControllerAdvice public class MyControllerAdvice { @InitBinder public void globalInitBinder(WebDataBinder binder){ binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); } }
@ControllerAdvice public class MyControllerAdvice { @ModelAttribute(value = "message")//在全部攔截器的preHandler方法執行以後執行 public String globalModelAttribute(){ System.out.println("MyControllerAdvice.globalModelAttribute"); return "test"; } } @RestController public class HelloController { @GetMapping("go") public ModelAndView go(@ModelAttribute("message") String message){ System.out.println(message); //"test" ModelAndView mv = new ModelAndView(message); return mv; //跳轉到 test.html頁面 } }
@GetMapping("/go/{id}") public String PathVa(@PathVariable("id") Long id){ System.out.println(id); return "test"; }
處理請求地址映射的註解,可用於類或方法上。mvc
用於類上,表示類中的全部響應請求的方法都是以該地址做爲父路徑。
參數:
@RequestMapping(value = "/go",method = RequestMethod.GET)
= GetMapping("/go")
application/json, text/html;
能夠對類成員變量、方法一級構造參數進行標註,完成自動裝配。
首先將默認類型匹配的bean自動裝配到屬性中。
若是類型匹配的bean不止一個,接着根據名稱匹配。
若是查詢結果爲空,則拋出異常,若是想避免,可使用required = false
。