學(xué)習(xí)視頻:【編程不良人】繼spring之后快速入門springmvc,面對SpringMVC不用慌
第七章、SpringMVC與Ajax集成
-
引入相關(guān)依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency>
-
開發(fā)控制器
@Controller @RequestMapping("json") public class JsonController { /** * 引入jackson庫可以使用@ResponseBody自動轉(zhuǎn)換為json格式數(shù)據(jù)【推薦】 */ @RequestMapping("showAll") public @ResponseBody List<User> findAll() { //1.收集數(shù)據(jù) //2.調(diào)用業(yè)務(wù) List<User> users = new ArrayList<>(); users.add(new User(UUID.randomUUID().toString(), "小紅", 23, new Date())); users.add(new User(UUID.randomUUID().toString(), "小名", 29, new Date())); users.add(new User(UUID.randomUUID().toString(), "小撒", 25, new Date())); return users; } /** * 傳統(tǒng)寫法:引入阿里fastjson手動轉(zhuǎn)換為json格式數(shù)據(jù) */ @RequestMapping("findAll") public void findAll(HttpServletResponse response) throws IOException { //1.收集數(shù)據(jù) //2.調(diào)用業(yè)務(wù) List<User> users = new ArrayList<>(); users.add(new User(UUID.randomUUID().toString(), "小陳", 23, new Date())); users.add(new User(UUID.randomUUID().toString(), "小名", 29, new Date())); users.add(new User(UUID.randomUUID().toString(), "小撒", 25, new Date())); // fastjson String s = JSONObject.toJSONStringWithDateFormat(users, "yyyy-MM-dd"); response.setContentType("application/json;charset=UTF-8"); response.getWriter().println(s); } }
-
日期格式修正
@JsonFormat(pattern = "yyyy-MM-dd") private Date bir;
可以正常響應(yīng)
第八章、SpringMVC的攔截器
-
攔截器 :Interceptor 攔截 中斷
類似于javaweb中的Filter,不過沒有Filter那么強大
-
作用
Spring MVC的攔截器是一種用于在請求處理過程中進行預(yù)處理和后處理的機制。攔截器可以在請求到達控制器之前和之后執(zhí)行一些操作,例如日志記錄、權(quán)限驗證、數(shù)據(jù)處理等。
-
攔截器特點
- 請求到達會經(jīng)過攔截器,響應(yīng)回來同樣會經(jīng)過攔截器
- 攔截器只能Controller的請求,不能攔截jsp、靜態(tài)資源相關(guān)請求
- 攔截器可以中斷請求軌跡
-
開發(fā)攔截器
-
類 實現(xiàn)
implements HandlerInterceptor
接口中的方法 -
配置攔截器
注冊攔截器對象 bean id class=””
配置攔截器攔截請求路徑
-
-
編碼和測試結(jié)果
攔截器接口的實現(xiàn)
public class MyInterceptor implements HandlerInterceptor { @Override //**參數(shù)1:當(dāng)前請求對象 參數(shù)2:當(dāng)前請求響應(yīng)對象 參數(shù)3:當(dāng)前請求的控制器對應(yīng)的方法對象** public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("handler = " + ((HandlerMethod)handler).getMethod().getName() ); System.out.println("MyInterceptor.preHandle"); //強制用戶登錄 Object user = request.getSession().getAttribute("user"); // if (user == null) { // // 重定向到登錄頁面 // response.sendRedirect(request.getContextPath() + "/login.jsp"); // return false; // } return HandlerInterceptor.super.preHandle(request, response, handler); } @Override // 參數(shù)1、2、3同上 **參數(shù)4:當(dāng)前控制器方法的返回值** public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("modelAndView = " + modelAndView); System.out.println("MyInterceptor.postHandle"); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override // 參數(shù)1、2、3同上 **參數(shù)4:請求過程中出現(xiàn)異常時的異常對象** public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor.afterCompletion"); if (ex != null) { System.out.println("ex.getMessage() = " + ex.getMessage()); } HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
dispatcher.xml 配置攔截器
<!--注冊攔截器--> <bean id="myInterceptor" class="com.baizhi.interceptors.MyInterceptor"/> <!--配置攔截器--> <mvc:interceptors> <!--配置一個攔截器--> <mvc:interceptor> <!-- mvc:mapping 代表攔截哪個請求路徑--> <mvc:mapping path="/json/test"/> <!--排除具體地攔截請求--> <mvc:exclude-mapping path="/json/showAll"/> <!--使用攔截器--> <ref bean="myInterceptor"/> </mvc:interceptor> </mvc:interceptors>
進行測試
@RequestMapping("test") public String test() { System.out.println("JsonController.test"); // throw new RuntimeException(); return "index"; }
按預(yù)期執(zhí)行順序執(zhí)行
看到攔截器的執(zhí)行順序,我們會聯(lián)想到Spring中的AOP,兩者的底層邏輯都是通過動態(tài)代理實現(xiàn)的,雖然攔截器和AOP都可以用于在請求處理過程中添加額外的邏輯,但攔截器更專注于請求處理階段的任務(wù),而AOP更適用于在不同模塊中實現(xiàn)橫切關(guān)注點的功能。
關(guān)于動態(tài)代理和AOP底層可以看之前學(xué)習(xí)的:Spring5學(xué)習(xí)隨筆-AOP底層實現(xiàn)(JDK、CGlib)、實現(xiàn)切面(@Aspect)
Spring5學(xué)習(xí)隨筆-AOP系列Spring動態(tài)代理
第九章、SpringMVC中的全局異常處理
-
SpringMVC作為一個控制主要作用
- 處理請求 接收請求數(shù)據(jù) 調(diào)用業(yè)務(wù)對象
- 請求響應(yīng) 跳轉(zhuǎn)對應(yīng)視圖展示數(shù)據(jù)
-
現(xiàn)有控制器開發(fā)存在問題?
-
在處理用戶請求出現(xiàn)運行時異常直接響應(yīng)給用戶的是一個錯誤節(jié)目,對于用戶的使用體驗不友好。
沒有使用全局異常處理時
-
-
全局異常處理機制
作用:用來解決整合系統(tǒng)中任意一個控制器拋出異常時的統(tǒng)一處理入口
-
編碼
開發(fā)控制類
public class GlobalExceptionResolver implements HandlerExceptionResolver { /** * 用來處理發(fā)生異常時的方法 * * @param request 當(dāng)前請求對象 * @param response 當(dāng)前請求對應(yīng)的響應(yīng)對象 * @param handler 當(dāng)前請求的方法對象 * @param ex 當(dāng)前出現(xiàn)異常時的異常對象 * @return 出現(xiàn)異常時展示視圖和數(shù)據(jù) */ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("進入全局異常處理器,獲取的異常信息為:" + ex.getMessage()); ModelAndView modelAndView = new ModelAndView(); // 基于不同業(yè)務(wù)異常跳轉(zhuǎn)到不同頁面 modelAndView.setViewName("redirect:/error.jsp"); // return "error" -> error.jsp // modelAndView中的model默認放到request作用域,如果使用redirect跳轉(zhuǎn),model中數(shù)據(jù)會自動拼接到跳轉(zhuǎn)url modelAndView.addObject("msg", ex.getMessage()); return modelAndView; } }
dispatcher.xml 配置全局異常處理類
<bean class="com.baizhi.handlerexception.GlobalExceptionResolver"/>
-
基于不同業(yè)務(wù)異常跳轉(zhuǎn)不同頁面
// 基于不同業(yè)務(wù)異常跳轉(zhuǎn)到不同頁面 if (ex instanceof NotFoundException) { modelAndView.setViewName("notFound"); } else if (ex instanceof GeneralException) { modelAndView.setViewName("generalException"); }
文章來源:http://www.zghlxwxcb.cn/news/detail-748629.html
異常處理器的工作流程文章來源地址http://www.zghlxwxcb.cn/news/detail-748629.html
到了這里,關(guān)于Spring MVC學(xué)習(xí)隨筆-Ajax集成(JSON格式返回數(shù)據(jù))、攔截器(MyInterceptor)、全局異常處理(GlobalExceptionResolver)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!