日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java SSM篇5——SpringMVC

發(fā)布時(shí)間:2025/3/12 java 10 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java SSM篇5——SpringMVC 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Java SSM篇5——SpringMVC

1、MVC模式

MVC是軟件工程中的一種軟件架構(gòu)模式,它是一種分離業(yè)務(wù)邏輯與顯示界面的開發(fā)思想

  • M(model)模型:處理業(yè)務(wù)邏輯,封裝實(shí)體
  • V(view) 視圖:展示內(nèi)容
  • C(controller)控制器:負(fù)責(zé)調(diào)度分發(fā)(1.接收請求、2.調(diào)用模型、3.轉(zhuǎn)發(fā)到視圖)

2、SpringMVC優(yōu)點(diǎn)

  • 輕量級(jí),簡單易學(xué)
  • 高效 , 基于請求響應(yīng)的MVC框架
  • 與Spring兼容性好,無縫結(jié)合
  • 約定優(yōu)于配置
  • 功能強(qiáng)大:RESTful、數(shù)據(jù)驗(yàn)證、格式化、本地化、主題等
  • 簡潔靈活

3、SpringMVC快速入門

導(dǎo)入依賴

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.6</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version></dependency> </dependencies>

在web.xml注冊DispatcherServlet

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><!--注冊DispatcherServlet--><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc-config.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><!--/ 匹配所有的請求;(不包括.jsp)--><!--/* 匹配所有的請求;(包括.jsp)--><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping> </web-app>

springmvc核心配置文件

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttps://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 自動(dòng)掃描包,讓指定包下的注解生效,由IOC容器統(tǒng)一管理 --><context:component-scan base-package="cn.winkto.controller"/><!-- 讓Spring MVC不處理靜態(tài)資源 --><mvc:default-servlet-handler /><!--處理器映射器和處理器適配器,以及功能增強(qiáng)--><mvc:annotation-driven /><!-- 視圖解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"id="internalResourceViewResolver"><!-- 前綴 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 后綴 --><property name="suffix" value=".jsp" /></bean></beans>

第一個(gè)controller

@Controller public class HelloController {@RequestMapping("/hello")public String hello(){System.out.println("hello");return "hello";} }

hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body> <h1>Hello, i am winkto!</h1> </body> </html>

錯(cuò)誤分析:web項(xiàng)目下沒有l(wèi)ib包或者包不全

4、Spring執(zhí)行流程

5、SpringMVC組件詳解

  • 前端控制器:DispatcherServlet 用戶請求到達(dá)前端控制器,它就相當(dāng)于 MVC 模式中的 C,DispatcherServlet 是整個(gè)流程控制的 中心,由它調(diào)用其它組件處理用戶的請求,DispatcherServlet 的存在降低了組件之間的耦合性
  • 處理器映射器:HandlerMapping HandlerMapping 負(fù)責(zé)根據(jù)用戶請求找到 Handler 即處理器,SpringMVC 提供了不同的映射器 實(shí)現(xiàn)不同的映射方式,例如:配置文件方式,實(shí)現(xiàn)接口方式,注解方式等
  • 處理器適配器:HandlerAdapter 通過 HandlerAdapter 對處理器進(jìn)行執(zhí)行,這是適配器模式的應(yīng)用,通過擴(kuò)展適配器可以對更多類型 的處理器進(jìn)行執(zhí)行
  • 處理器:Handler【開發(fā)者編寫】 它就是我們開發(fā)中要編寫的具體業(yè)務(wù)控制器。由 DispatcherServlet 把用戶請求轉(zhuǎn)發(fā)到 Handler。由Handler 對具體的用戶請求進(jìn)行處理
  • 視圖解析器:ViewResolver View Resolver 負(fù)責(zé)將處理結(jié)果生成 View 視圖,View Resolver 首先根據(jù)邏輯視圖名解析成物 理視圖名,即具體的頁面地址,再生成 View 視圖對象,最后對 View 進(jìn)行渲染將處理結(jié)果通過頁面展示給 用戶
  • 視圖:View 【開發(fā)者編寫】 SpringMVC 框架提供了很多的 View 視圖類型的支持,包括:jstlView、freemarkerView、 pdfView等。最常用的視圖就是 jsp。一般情況下需要通過頁面標(biāo)簽或頁面模版技術(shù)將模型數(shù)據(jù)通過頁面展 示給用戶,需要由程序員根據(jù)業(yè)務(wù)需求開發(fā)具體的頁面

6、SpringMVC請求

  • 基本類型參數(shù)
  • 對象類型參數(shù)
  • 數(shù)組類型參數(shù)
  • 集合類型參數(shù)

6.1、基本類型參數(shù)

參數(shù)名稱與請求參數(shù)的name一致,參數(shù)值會(huì)自動(dòng)映射匹配

@RequestMapping("/parameter1") @ResponseBody public String parameter1(int id, String name){return id+"==="+name; } http://localhost:8080/springmvc_war_exploded/parameter1?id=1&name=zhangsan

6.2、對象類型參數(shù)

實(shí)體類屬性名與請求參數(shù)的name一致,參數(shù)值會(huì)自動(dòng)映射匹配

public class Person {private int id;private String name;private String password; } @RequestMapping("/parameter2") @ResponseBody public String parameter2(Person person){return person.toString(); } http://localhost:8080/springmvc_war_exploded/parameter2?id=2&name=lisi&password=blingbling

6.3、數(shù)組類型參數(shù)

數(shù)組名稱與請求參數(shù)的name一致,參數(shù)值會(huì)自動(dòng)映射匹配

@RequestMapping("/parameter3") @ResponseBody public String parameter3(String[] hobits){return Arrays.toString(hobits); } http://localhost:8080/springmvc_war_exploded/parameter3?hobits=Basketball&hobits=Football

6.4、集合類型參數(shù)

public class Paramater {private List<Person> people;private Person person; } @RequestMapping("/parameter4") @ResponseBody public String parameter4(Paramater paramater){return paramater.toString(); } <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html><head><title>$Title$</title></head><body><form action="${pageContext.request.contextPath}/parameter4" method="post">list集合<br>第一個(gè)元素:<input type="text" name="people[0].id" placeholder="編號(hào)"><input type="text" name="people[0].name" placeholder="姓名"><input type="text" name="people[0].password" placeholder="密碼"><br>第二個(gè)元素:<input type="text" name="people[1].id" placeholder="編號(hào)"><input type="text" name="people[1].name" placeholder="姓名"><input type="text" name="people[1].password" placeholder="密碼"><br>person:<input type="text" name="person.id" placeholder="編號(hào)"><input type="text" name="person.name" placeholder="姓名"><input type="text" name="person.password" placeholder="密碼"><br><input type="submit" value="提交"></form></body> </html>

6.5、中文亂碼

6.5.1、GET 方式請求出現(xiàn)的中文亂碼

使用 String 的getBytes(“ISO-8859-1”)方法,先轉(zhuǎn)換為 byte[] ,再創(chuàng)建一個(gè)String,既 String name=new String(bytes,”UTF-8”);

6.5.2、POST 方式請求出現(xiàn)的中文亂碼

<!-- 配置編碼過濾 --> <filter><filter-name>EncoidingFilter</filter-name><filter-class>cn.winkto.controller.EncoidingFilter</filter-class><init-param><param-name>Encoding</param-name><param-value>utf-8</param-value></init-param> </filter><filter-mapping><filter-name>EncoidingFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>

6.6、自定義類型轉(zhuǎn)換

6.6.1、日期類型轉(zhuǎn)換

@RequestMapping("/parameter5") @ResponseBody public String parameter5(Date date){return date.toString(); } <form action="${pageContext.request.contextPath}/parameter5" method="post"><input type="text" name="date"><input type="submit" value="提交"> </form> 2020/02/02 Sun Feb 02 00:00:00 CST 2020

以/分割確實(shí)沒有什么問題,但是一旦使用-分割就出現(xiàn)錯(cuò)誤

6.6.2、自定義類型轉(zhuǎn)換

自定義轉(zhuǎn)換器

public class DateConverter implements Converter<String, Date> {public Date convert(String s) {SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {return simpleDateFormat.parse(s);} catch (ParseException e) {e.printStackTrace();}return null;} }

配置轉(zhuǎn)換器

<bean id="converter" class="org.springframework.context.support.ConversionServiceFactoryBean"><property name="converters"><set><bean class="cn.winkto.converter.DateConverter" /></set></property> </bean>

啟動(dòng)轉(zhuǎn)換器

<mvc:annotation-driven conversion-service="converter" />

測試

2020-02-02 10:19:00 Sun Feb 02 10:19:00 CST 2020

6.7、@RequestParam

當(dāng)請求的參數(shù)name名稱與Controller的業(yè)務(wù)方法參數(shù)名稱不一致時(shí),就需要通過@RequestParam注 解顯示的綁定

@RequestMapping("/parameter6") @ResponseBody public String parameter6(@RequestParam(value = "a",defaultValue = "0",required = false) int id){return id+""; } http://localhost:8080/springmvc_war_exploded/parameter6 0 http://localhost:8080/springmvc_war_exploded/parameter6?a=1 1

6.8、@RequestHeader、@CookieValue

@RequestMapping("/parameter7") @ResponseBody public String parameter7(@RequestHeader("cookie") String cookie){return cookie; } @RequestMapping("/parameter8") @ResponseBody public String parameter8(@CookieValue("JSESSIONID") String JSESSIONID){return JSESSIONID; }

6.9、原生servlet的獲取

@RequestMapping("/parameter9") @ResponseBody public String parameter9(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession httpSession){System.out.println(httpServletRequest);System.out.println(httpServletResponse);System.out.println(httpSession);return "servlet"; }

7、SpringMVC響應(yīng)

7.1、頁面跳轉(zhuǎn)

7.1.1、返回字符串邏輯視圖

@RequestMapping("/hello") public String hello(){return "hello"; }

7.1.2、原始ServletAPI

@RequestMapping("/hello1") public void hello1(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws ServletException, IOException {httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(httpServletRequest,httpServletResponse); } @RequestMapping("/hello2") public void hello2(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws ServletException, IOException {httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/hello"); }

7.1.3、ModelAndView

@RequestMapping("/hello3") public ModelAndView hello(ModelAndView modelAndView) {modelAndView.setViewName("hello");return modelAndView; }

7.2、返回?cái)?shù)據(jù)

@RequestMapping("/hello4") @ResponseBody public String hello4() {return "hello"; }

7.3、 轉(zhuǎn)發(fā)和重定向

7.3.1、原始ServletAPI

@RequestMapping("/hello1") public void hello1(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws ServletException, IOException {httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(httpServletRequest,httpServletResponse); } @RequestMapping("/hello2") public void hello2(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws ServletException, IOException {httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/hello"); }

7.3.2、springmvc

@RequestMapping("/hello5") public String hello5() {return "forward:/WEB-INF/jsp/hello.jsp"; } @RequestMapping("/hello6") public String hello6() {return "redirect:/hello"; }

7.4、@SessionAttributes

  • 如果在多個(gè)請求之間共用數(shù)據(jù),則可以在控制器類上標(biāo)注一個(gè) @SessionAttributes,配置需要在 session中存放的數(shù)據(jù)范圍,Spring MVC將存放在model中對應(yīng)的數(shù)據(jù)暫存到 HttpSession 中
  • 只能放置在控制器類上

7.5、靜態(tài)資源訪問的開啟

7.5.1、處理1

<mvc:resources mapping="/js/**" location="/js/"/>

7.5.2、處理2

<mvc:default-servlet-handler/>

8、@ResponseBody

用于將Controller的方法返回的對象,通過HttpMessageConverter接口轉(zhuǎn)換為指定格式的數(shù) 據(jù)如:json,xml等,通過Response響應(yīng)給客戶端

9、RestFul

Restful是一種軟件架構(gòu)風(fēng)格、設(shè)計(jì)風(fēng)格,而不是標(biāo)準(zhǔn),只是提供了一組設(shè)計(jì)原則和約束條件。主要用 于客戶端和服務(wù)器交互類的軟件,基于這個(gè)風(fēng)格設(shè)計(jì)的軟件可以更簡潔,更有層次,更易于實(shí)現(xiàn)緩存機(jī) 制等。 Restful風(fēng)格的請求是使用“url+請求方式”表示一次請求目的的

9.1、方式對比

傳統(tǒng)方式

http://127.0.0.1/item/queryItem.action?id=1 查詢,GET http://127.0.0.1/item/saveItem.action 新增,POST http://127.0.0.1/item/updateItem.action 更新,POST http://127.0.0.1/item/deleteItem.action?id=1 刪除,GET或POST

RestFul風(fēng)格

http://127.0.0.1/item/1 查詢,GET http://127.0.0.1/item 新增,POST http://127.0.0.1/item 更新,PUT http://127.0.0.1/item/1 刪除,DELETE

9.2、Restful的好處

  • 使路徑變得更加簡潔
  • 獲得參數(shù)更加方便,框架會(huì)自動(dòng)進(jìn)行類型轉(zhuǎn)換
  • 通過路徑變量的類型可以約束訪問參數(shù),如果類型不一樣,則訪問不到對應(yīng)的請求方法,如這里訪問是的路徑是/commit/1/a,則路徑與方法不匹配,而不會(huì)是參數(shù)轉(zhuǎn)換失敗

9.3、Restful的使用

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping
//基本類型 @GetMapping("/restful1/{a}") @ResponseBody public String restful1(@PathVariable int a) {return a+""; } //對象類型 @GetMapping("/restful2/{id}/{name}/{password}") @ResponseBody public String restful2(Person person) {return person.toString(); } http://localhost:8080/springmvc_war_exploded/restful1/1 http://localhost:8080/springmvc_war_exploded/restful2/1/zhangsan/lisi

10、文件

10.1、文件上傳三要素

  • 表單項(xiàng) type=“file”
  • 表單的提交方式 method=“POST”
  • 表單的enctype屬性是多部分表單形式 enctype=“multipart/form-data"

10.2、文件上傳原理

  • 當(dāng)form表單修改為多部分表單時(shí),request.getParameter()將失效
  • 當(dāng)form表單的enctype取值為 application/x-www-form-urlencoded 時(shí), form表單的正文內(nèi)容格式是: name=value&name=value
  • 當(dāng)form表單的enctype取值為 mutilpart/form-data 時(shí),請求正文內(nèi)容就變成多部分形式

10.3、文件上傳的實(shí)現(xiàn)

導(dǎo)入依賴

<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version> </dependency>

配置文件上傳解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><!-- 設(shè)定文件上傳的最大值為5MB,5*1024*1024 --><property name="maxUploadSize" value="5242880"></property><!-- 設(shè)定文件上傳時(shí)寫入內(nèi)存的最大值,如果小于這個(gè)參數(shù)不會(huì)生成臨時(shí)文件,默認(rèn)為10240 --><property name="maxInMemorySize" value="40960"></property> </bean>

配置接口

@Controller public class FileLoad {//傳統(tǒng)方式@RequestMapping("/upload")public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {String filename = file.getOriginalFilename();if ("".equals(filename)){return "redirect:/index.jsp";}System.out.println(filename);String path=request.getServletContext().getRealPath("upload");File file1=new File(path);if (!file1.exists()){file1.mkdir();}System.out.println(path);InputStream inputStream=file.getInputStream();OutputStream outputStream=new FileOutputStream(new File(path,filename));int len=0;byte[] bytes= new byte[1024];while ((len=inputStream.read(bytes))!=-1){outputStream.write(bytes,0,len);outputStream.flush();}inputStream.close();outputStream.close();System.out.println("ok===================");return "redirect:/index.jsp";}//springmvc方式@RequestMapping("upload1")public String upload1(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {String path=request.getServletContext().getRealPath("upload");File file1=new File(path);if (!file1.exists()){file1.mkdir();}System.out.println(path);file.transferTo(new File(path+"/"+file.getOriginalFilename()));return "redirect:/index.jsp";} }

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html><head><title>$Title$</title></head><body><form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data"><input type="file" name="file"><input type="submit" value="Submit"></form></body> </html>

10.4、文件下載

接口

@Controller public class FileLoad {@RequestMapping("/download")public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{//要下載的圖片地址String path = request.getServletContext().getRealPath("/upload");String fileName = "1.png";//1、設(shè)置response 響應(yīng)頭response.reset(); //設(shè)置頁面不緩存,清空bufferresponse.setCharacterEncoding("UTF-8"); //字符編碼response.setContentType("multipart/form-data"); //二進(jìn)制傳輸數(shù)據(jù)//設(shè)置響應(yīng)頭response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));File file = new File(path,fileName);//2、 讀取文件--輸入流InputStream input=new FileInputStream(file);//3、 寫出文件--輸出流OutputStream out = response.getOutputStream();byte[] buff =new byte[1024];int index=0;//4、執(zhí)行 寫出操作while((index= input.read(buff))!= -1){out.write(buff, 0, index);out.flush();}out.close();input.close();return null;} }

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html><head><title>$Title$</title></head><body><a href="${pageContext.request.contextPath}/download">1.png</a></body> </html>

11、攔截器

Spring MVC 的攔截器類似于 Servlet 開發(fā)中的過濾器 Filter,用于對處理器進(jìn)行預(yù)處理和后處理

11.1、攔截器與過濾器的比對

區(qū)別過濾器攔截器
使用范圍任何java web項(xiàng)目只有springmvc項(xiàng)目才可以使用
攔截范圍url-paten配置了/*后可以對所有資源進(jìn)行攔截只會(huì)攔截控制器方法

11.2、攔截器快速入門

書寫攔截器,實(shí)現(xiàn)HandlerInterceptor接口

public class MyInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("方法前");return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("方法后");}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("清理操作");} }

springmvc核心配置文件配置攔截器

<mvc:interceptors><mvc:interceptor><!--/** 包括路徑及其子路徑--><!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會(huì)被攔截--><!--/admin/** 攔截的是/admin/下的所有--><mvc:mapping path="/**"/><!--bean配置的就是攔截器--><bean class="cn.winkto.controller.MyInterceptor"/></mvc:interceptor> </mvc:interceptors>

11.3、攔截器鏈

開發(fā)中攔截器可以單獨(dú)使用,也可以同時(shí)使用多個(gè)攔截器形成一條攔截器鏈。開發(fā)步驟和單個(gè)攔截器 是一樣的,只不過注冊的時(shí)候注冊多個(gè),注意這里注冊的順序就代表攔截器執(zhí)行的順序

書寫攔截器,實(shí)現(xiàn)HandlerInterceptor接口

public class MyInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("方法前");return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("方法后");}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("清理操作");} } public class MyInterceptor1 implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("方法前");return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("方法后");}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("清理操作");} }

springmvc核心配置文件配置攔截器

<mvc:interceptors><mvc:interceptor><!--/** 包括路徑及其子路徑--><!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會(huì)被攔截--><!--/admin/** 攔截的是/admin/下的所有--><mvc:mapping path="/**"/><!--bean配置的就是攔截器--><bean class="cn.winkto.controller.MyInterceptor"/></mvc:interceptor><mvc:interceptor><mvc:mapping path="/**"/><!--bean配置的就是攔截器--><bean class="cn.winkto.controller.MyInterceptor1"/></mvc:interceptor> </mvc:interceptors>

12、異常處理

12.1、異常處理思路

  • 當(dāng)前方法捕獲處理(try-catch),這種處理方式會(huì)造成業(yè)務(wù)代碼和異常處理代碼的耦合
  • 自己不處理,而是拋給調(diào)用者處理(throws),調(diào)用者再拋給它的調(diào)用者,也就是一直向上拋

在這種方法的基礎(chǔ)上,衍生出了SpringMVC的異常處理機(jī)制,系統(tǒng)的mapper、service、controller出現(xiàn)都通過throws Exception向上拋出,最后由springmvc前端控 制器交由異常處理器進(jìn)行異常處理

12.2、自定義異常處理

編寫自定義異常處理器,繼承HandlerExceptionResolver接口,書寫頁面跳轉(zhuǎn),并注入容器

@Component public class MyHandlerExceptionResolver implements HandlerExceptionResolver {public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {System.out.println("發(fā)生異常了"+e);ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("error");return modelAndView;} }

異常頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body> <h1>Error</h1> </body> </html>

測試

@RequestMapping("/hello") public String hello(){throw new RuntimeException("啦啦啦"); }

12.3、web的處理異常機(jī)制

web.xml

<!--處理500異常--> <error-page><error-code>500</error-code><!--路徑以web目錄為基準(zhǔn)--><location>/500.jsp</location> </error-page> <!--處理404異常--> <error-page><error-code>404</error-code><!--路徑以web目錄為基準(zhǔn)--><location>/404.jsp</location> </error-page> 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的Java SSM篇5——SpringMVC的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。