到目前爲止咱們編寫的全部Controller的方法的返回值都是String類型,可是你們應該都知道,咱們有時候數據傳遞特別是在ajax中,咱們返回的數據常常須要使用json,那麼如何來保證返回的數據的是json格式呢?使用@ResponseBody註解javascript
pom.xmlhtml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mashibing</groupId> <artifactId>springmv_ajax</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.3.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.10.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.10.3</version> </dependency> </dependencies> </project>
springmvc.xmljava
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> </beans>
JsonController.javajquery
package com.mashibing.controller; import com.mashibing.bean.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class JsonController { @ResponseBody @RequestMapping("/json") public List<User> json(){ List<User> list = new ArrayList<User>(); list.add(new User(1,"zhangsan",12,"男",new Date(),"1234@qq.com")); list.add(new User(2,"zhangsan2",12,"男",new Date(),"1234@qq.com")); list.add(new User(3,"zhangsan3",12,"男",new Date(),"1234@qq.com")); return list; } }
User.java程序員
package com.mashibing.bean; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; public class User { private Integer id; private String name; private Integer age; private String gender; @JsonFormat( pattern = "yyyy-MM-dd") private Date birth; @JsonIgnore private String email; public User() { } public User(Integer id, String name, Integer age, String gender, Date birth, String email) { this.id = id; this.name = name; this.age = age; this.gender = gender; this.birth = birth; this.email = email; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + ", birth=" + birth + ", email='" + email + '\'' + '}'; } }
同時@ResponseBody能夠直接將返回的字符串數據做爲響應內容web
package com.mashibing.controller; import com.mashibing.bean.User; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class OtherController { @ResponseBody @RequestMapping("/testResponseBody") public String testResponseBody(){ return "<h1>success</h1>"; } }
ajax.jspajax
<%@ page import="java.util.Date" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="script/jquery-1.9.1.min.js"></script> </head> <% pageContext.setAttribute("ctp",request.getContextPath()); %> <body> <%=new Date()%> <a href="${ctp}/json">獲取用戶信息</a> <div> </div> <script type="text/javascript"> $("a:first").click(function () { $.ajax({ url:"${ctp}/json", type:"GET", success:function (data) { console.log(data) $.each(data,function() { var user = this.id+"--"+this.name+"--"+this.age+"--"+this.gender+"--"+this.birth+"--"+this.email; $("div").append(user+'<br/>'); }) } }); return false; }); </script> </body> </html>
testOther.jspspring
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 15:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <% pageContext.setAttribute("ctp",request.getContextPath()); %> <head> <title>Title</title> </head> <body> <form action="${ctp}/testRequestBody" method="post" enctype="multipart/form-data"> <input name="username" value="zhangsan"><br> <input name="password" value="123456"><br> <input type="file" name="file" ><br> <input type="submit"><br> </form> </body> </html>
OtherController.javaapache
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class OtherController { @RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody String body){ System.out.println("請求體:"+body); return "success"; } }
同時@RequestBody可以接受json格式的請求數據:json
testOther.jsp
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 15:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <script type="text/javascript" src="script/jquery-1.9.1.min.js"></script> <html> <% pageContext.setAttribute("ctp",request.getContextPath()); %> <head> <title>Title</title> </head> <body> <form action="${ctp}/testRequestBody" method="post" enctype="multipart/form-data"> <input name="username" value="zhangsan"><br> <input name="password" value="123456"><br> <input type="file" name="file" ><br> <input type="submit"><br> </form> <hr/> <a href="${ctp}/testRequestJson">發送json數據</a> <script type="text/javascript"> $("a:first").click(function () { var user = {id:"1",name:"zhangsan",age:"12",gender:"男",birth:"2020-3-13",email:"123@qq.com"}; var userJson = JSON.stringify(user); $.ajax({ url:"${ctp}/testRequestJson", type:"POST", data:userJson, contentType:"application/json", success:function (data) { alert(data); } }); return false; }); </script> </body> </html>
OtherController.java
package com.mashibing.controller; import com.mashibing.bean.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class OtherController { @RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody String body){ System.out.println("請求體:"+body); return "success"; } @RequestMapping("/testRequestJson") public String testRequestBody(@RequestBody User user){ System.out.println("對象:"+user); return "success"; } }
在接受請求的時候還可使用HttpEntity對象,用來接受參數,能夠獲取請求頭信息。
package com.mashibing.controller; import com.mashibing.bean.User; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class OtherController { @RequestMapping("/testHttpEntity") public String testRequestBody(HttpEntity<String> httpEntity){ System.out.println(httpEntity); return "success"; } }
package com.mashibing.controller; import com.mashibing.bean.User; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class OtherController { @RequestMapping("/testResponseEntity") public ResponseEntity<String> testResponseEntity(){ String body = "<h1>hello</h1>"; MultiValueMap<String,String> header = new HttpHeaders(); header.add("Set-Cookie","name=zhangsan"); return new ResponseEntity<String>(body,header, HttpStatus.OK); } }
package com.mashibing.controller; import com.mashibing.bean.User; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.io.FileInputStream; import java.io.FileNotFoundException; @Controller public class OtherController { @RequestMapping("/download") public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception { //獲取要下載文件的路徑及輸入流對象 ServletContext servletContext = request.getServletContext(); String realPath = servletContext.getRealPath("/script/jquery-1.9.1.min.js"); FileInputStream fileInputStream = new FileInputStream(realPath); byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); fileInputStream.close(); //將要下載文件內容返回 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Content-Disposition","attachment;filename=jquery-1.9.1.min.js"); return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK); } }
Spring MVC 爲文件上傳提供了直接的支持,這種支持是經過即插即用的 MultipartResolver 實現的。Spring 用 Jakarta Commons FileUpload 技術實現了一個 MultipartResolver 實現類:CommonsMultipartResovler
Spring MVC 上下文中默認沒有裝配 MultipartResovler,所以默認狀況下不能處理文件的上傳工做,若是想使用 Spring 的文件上傳功能,需如今上下文中配置 MultipartResolver。
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mashibing</groupId> <artifactId>springmvc_upload</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.3.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.10.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.10.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> </dependencies> </project>
web.xml
<?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"> <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.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
springmvc.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean> </beans>
index.jsp
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 17:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="testUpload" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="file"/><br><br> 描述: <input type="text" name="desc"/><br><br> <input type="submit" value="提交"/> </form> </body> </html>
UploadHandler.java
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.io.InputStream; @Controller public class UploadHandler { @RequestMapping(value = "/testUpload", method = RequestMethod.POST) public String testUpload(@RequestParam(value = "desc", required = false) String desc, @RequestParam("file") MultipartFile multipartFile) throws IOException { System.out.println("desc : " + desc); System.out.println("OriginalFilename : " + multipartFile.getOriginalFilename()); multipartFile.transferTo(new File("D:\\file\\"+multipartFile.getOriginalFilename())); return "success"; //增長成功頁面: /views/success.jsp } }
success.jsp
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 17:03 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> success </body> </html>
若是是多文件上傳,那麼又改如何處理呢?
index.jsp
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 17:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="testUpload" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="file"/><br><br> 文件: <input type="file" name="file"/><br><br> 文件: <input type="file" name="file"/><br><br> 描述: <input type="text" name="desc"/><br><br> <input type="submit" value="提交"/> </form> </body> </html>
UploadHandler.java
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.io.InputStream; @Controller public class UploadHandler { @RequestMapping(value = "/testUpload", method = RequestMethod.POST) public String testUpload(@RequestParam(value = "desc", required = false) String desc, @RequestParam("file") MultipartFile[] multipartFile) throws IOException { System.out.println("desc : " + desc); for (MultipartFile file : multipartFile) { if (!file.isEmpty()) { System.out.println("OriginalFilename : " + file.getOriginalFilename()); file.transferTo(new File("D:\\file\\" + file.getOriginalFilename())); } } return "success"; //增長成功頁面: /views/success.jsp } }
SpringMVC提供了攔截器機制,容許運行目標方法以前進行一些攔截工做或者目標方法運行以後進行一下其餘相關的處理。自定義的攔截器必須實現HandlerInterceptor接口。
preHandle():這個方法在業務處理器處理請求以前被調用,在該方法中對用戶請求 request 進行處理。若是程序員決定該攔截器對請求進行攔截處理後還要調用其餘的攔截器,或者是業務處理器去進行處理,則返回true;若是程序員決定不須要再調用其餘的組件去處理請求,則返回false
postHandle():這個方法在業務處理器處理完請求後,可是DispatcherServlet 向客戶端返回響應前被調用,在該方法中對用戶請求request進行處理。
afterCompletion():這個方法在DispatcherServlet徹底處理完請求後被調用,能夠在該方法中進行一些資源清理的操做。
MyFirstInterceptor.java
package com.mashibing.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyFirstInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(this.getClass().getName()+"------->preHandle"); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(this.getClass().getName()+"------->postHandle"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(this.getClass().getName()+"------->afterCompletion"); } }
TestInterceptorController.java
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestInterceptorController { @RequestMapping("test01") public String test01(){ System.out.println("test01"); return "success"; } }
springmvc.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:interceptors> <bean class="com.mashibing.interceptor.MyFirstInterceptor"></bean> </mvc:interceptors> </beans>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% System.out.println("success.jsp");%> success </body> </html>
經過運行結果可以發現攔截器的執行順序以下:
能夠看到先執行攔截器的preHandle方法----》執行目標方法----》執行攔截器的postHandle方法----》執行頁面跳轉----》執行攔截器的afterCompletion方法
在配置攔截器的時候有兩個須要注意的點:
一、若是prehandle方法返回值 爲false,那麼意味着不放行,那麼就會形成後續的全部操做都中斷
二、若是執行到方法中出現異常,那麼後續流程不會處理可是afterCompletion方法會執行
再添加另一個攔截器
MySecondInterceptor.java
package com.mashibing.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MySecondInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(this.getClass().getName()+"------->preHandle"); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(this.getClass().getName()+"------->postHandle"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(this.getClass().getName()+"------->afterCompletion"); } }
看到以下執行順序:
調整兩個攔截器的配置順序:
你們能夠看到對應的效果,誰先執行取決於配置的順序。
攔截器的preHandle是按照順序執行的
攔截器的postHandle是按照逆序執行的
攔截器的afterCompletion是按照逆序執行的
若是執行的時候核心的業務代碼出問題了,那麼已經經過的攔截器的afterCompletion會接着執行。
一、過濾器是基於函數回調的,而攔截器是基於java反射的
二、過濾器依賴於servlet容器,而攔截器不依賴與Servlet容器
三、過濾器幾乎對全部的請求都起做用,而攔截器只能對action請求起做用
四、攔截器能夠訪問action的上下文,而過濾器不能夠
五、在controller的生命週期中,攔截器能夠屢次調用,而過濾器只能在web容器初始化的時候初始化一次,後續匹配的全部請求都會通過過濾器來進行過濾
在平常工做中,若是你的網站須要給不一樣語言地區的人進行查看,此時就須要使用國際化的基本操做,springmvc的國際化操做比較容易。
index.jsp
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 17:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="i18n">國際化頁面登陸</a> </body> </html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <html> <head> <title>Title</title> </head> <body> <h1><fmt:message key="welcomeinfo"/></h1> <form action="login" method="post" > <fmt:message key="username"/>: <input type="text" name="username"/><br><br> <fmt:message key="password"/>: <input type="password" name="password"/><br><br> <input type="submit" value="<fmt:message key="loginBtn"/>"/> </form> </body> </html>
I18nController.java
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class I18nController { @RequestMapping("i18n") public String i18n(){ return "login"; } }
login_en_US.properties
welcomeinfo=welcome to mashibing.com username=USERNAME password=PASSWORD loginBtn=LOGIN
login_zh_CN.properties
welcomeinfo=歡迎進入馬士兵教育 username=用戶名 password=密碼 loginBtn=登陸
springmvc.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="login"></property> </bean> </beans>
其實SpringMVC中國際化的處理很是簡單,就是按照瀏覽器所帶來的語言信息決定的。
Locale locale = request.getLocale();//獲取瀏覽器的區域信息
在DispatcherServlet中會包含一個組件,用來專門獲取區域信息
經過圖片可以發現,默認調用的是org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver類
在程序中能夠獲取Locale的相關信息:
package com.mashibing.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Locale; @Controller public class I18nController { @Autowired private MessageSource messageSource; @RequestMapping("i18n") public String i18n(Locale locale){ System.out.println(locale); String username = messageSource.getMessage("username", null, locale); System.out.println(username); return "login"; } }
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <html> <head> <title>Title</title> </head> <body> <h1><fmt:message key="welcomeinfo"/></h1> <form action="login" method="post" > <fmt:message key="username"/>: <input type="text" name="username"/><br><br> <fmt:message key="password"/>: <input type="password" name="password"/><br><br> <input type="submit" value="<fmt:message key="loginBtn"/>"/> <a href="i18n?locale=zh_CN">中文</a><a href="i18n?locale=en_US">英文</a> </form> </body> </html>
MyLocaleResolver.java
package com.mashibing; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; public class MyLocaleResolver implements LocaleResolver { /** * 解析並返回locale * @param request * @return */ @Override public Locale resolveLocale(HttpServletRequest request) { Locale locale = null; String localeStr = request.getParameter("locale"); if(localeStr!=null && ! "".equals(localeStr)){ locale = new Locale(localeStr.split("_")[0],localeStr.split("_")[1]); }else{ locale = request.getLocale(); } return locale; } /** * 不支持設置locale的信息 * @param request * @param response * @param locale */ @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { throw new UnsupportedOperationException( "Cannot change HTTP accept header - use a different locale resolution strategy"); } }
springmvc.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="login"></property> </bean> <!--配置區域信息解析器--> <bean id="localeResolver" class="com.mashibing.MyLocaleResolver"></bean> </beans>
除了能夠自定義區域信息解析器以外,咱們還可使用SpringMVC中自帶的SessionLocaleResolver:
I18nController.java
package com.mashibing.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import javax.servlet.http.HttpSession; import java.util.Locale; @Controller public class I18nController { @Autowired private MessageSource messageSource; @RequestMapping("i18n") public String i18n(@RequestParam(value = "locale",defaultValue = "zh_CN") String localeStr,Locale locale, HttpSession session){ Locale l = null; if(localeStr!=null && ! "".equals(localeStr)){ l = new Locale(localeStr.split("_")[0],localeStr.split("_")[1]); }else{ l = locale; } session.setAttribute(SessionLocaleResolver.class.getName() + ".LOCALE",l); return "login"; } }
springmvc.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="login"></property> </bean> <!--配置區域信息解析器--> <!-- <bean id="localeResolver" class="com.mashibing.MyLocaleResolver"></bean>--> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> </beans>
使用LocaleChangeInterceptor來實現國際化:
springmvc.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:default-servlet-handler></mvc:default-servlet-handler> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.mashibing"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">--> <!-- <property name="defaultEncoding" value="UTF-8"></property>--> <!-- <property name="maxUploadSize" value="1024000"></property>--> <!-- </bean>--> <!-- <mvc:interceptors>--> <!-- <bean class="com.mashibing.interceptor.MySecondInterceptor"></bean>--> <!-- <bean class="com.mashibing.interceptor.MyFirstInterceptor"></bean>--> <!-- </mvc:interceptors>--> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="login"></property> </bean> <!--配置區域信息解析器--> <!-- <bean id="localeResolver" class="com.mashibing.MyLocaleResolver"></bean>--> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean> </mvc:interceptors> </beans>
I18nController.java
package com.mashibing.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import javax.servlet.http.HttpSession; import java.util.Locale; @Controller public class I18nController { @Autowired private MessageSource messageSource; @RequestMapping("i18n") public String i18n(@RequestParam(value = "locale",defaultValue = "zh_CN") String localeStr,Locale locale, HttpSession session){ // Locale l = null; // if(localeStr!=null && ! "".equals(localeStr)){ // l = new Locale(localeStr.split("_")[0],localeStr.split("_")[1]); // }else{ // l = locale; // } // session.setAttribute(SessionLocaleResolver.class.getName() + ".LOCALE",l); return "login"; } }
在SpringMVC中擁有一套很是強大的異常處理機制,SpringMVC經過HandlerExceptionResolver處理程序的異常,包括請求映射,數據綁定以及目標方法的執行時發生的異常。
在容器啓動好,進入DispatcherServlet以後,會對HandlerExceptionResolver進行初始化操做:
會默認的從DispatcherServlet.properties中找到對應的異常處理類:
#默認的處理類 org.springframework.web.servlet.HandlerExceptionResolver= #處理@ExceptionHandler org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver,\ #處理@ResponseStatus,給自定義異常使用 org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\ #判斷是不是SpringMVC自帶異常 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
本身定義異常處理方式:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="exception1">本身處理異常</a> </body> </html>
ExceptionController.java
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; @Controller public class ExceptionController { @RequestMapping("exception1") public String exception(){ System.out.println("exception......."); System.out.println(10/0); return "success"; } @ExceptionHandler(value = {ArithmeticException.class}) public ModelAndView handlerException(Exception exception){ ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("ex",exception); return mv; } }
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 個人出錯頁面: 錯誤信息:${ex} </body> </html>
在一個類中可能會包含多個異常的處理方法,在不一樣的方法上可使用不一樣範圍的異常,在查找的時候會優先調用範圍小的異常處理;
package com.mashibing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; @Controller public class ExceptionController { @RequestMapping("exception1") public String exception(){ System.out.println("exception......."); System.out.println(10/0); return "success"; } @ExceptionHandler(value = {ArithmeticException.class}) public ModelAndView handlerException1(Exception exception){ System.out.println("handlerException1........"); ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("ex",exception); return mv; } @ExceptionHandler(value = {Exception.class}) public ModelAndView handlerException2(Exception exception){ System.out.println("handlerException2........"); ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("ex",exception); return mv; } }
在不一樣的類中可能會包含不一樣的異常處理,所以咱們須要定義一個全局的異常控制器,使用@ControllerAdvice註解標註,若是本類跟全局都有相關異常的處理,那麼會優先使用本類的。
package com.mashibing.controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class MyGlobalExceptionHandler { @ExceptionHandler(value = {ArithmeticException.class}) public ModelAndView handlerException1(Exception exception){ System.out.println("handlerException1........"); ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("ex",exception); return mv; } }
@ResponseStatus的使用:
@ResponseStatus能夠標註到方法上,可是標註在方法以後可能致使該方法沒法被訪問,所以更多的是在自定義類上
package com.mashibing.controller; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; @Controller public class ExceptionController { @ResponseStatus(reason = "不知道什麼緣由,反正錯誤",value = HttpStatus.NOT_ACCEPTABLE) @RequestMapping("exception1") public String exception(){ System.out.println("exception......."); return "success"; } }
@ResponseStatus做用在類上
UserNameException.java
package com.mashibing.controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(reason = "名字不是admin",value = HttpStatus.NOT_ACCEPTABLE) public class UserNameException extends RuntimeException { }
ExceptionController.java
package com.mashibing.controller; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; @Controller public class ExceptionController { @RequestMapping("exception1") public String exception(){ System.out.println("exception......."); return "success"; } @RequestMapping("exception2") public String exception2(String username){ System.out.println("exception2222......."); if ("admin".equals(username)){ return "success"; }else{ throw new UserNameException(); } } }
springmvc自定義的異常:
index.jsp
<%-- Created by IntelliJ IDEA. User: root Date: 2020/3/13 Time: 17:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="exception1">本身處理異常</a> <a href="exception2?username=zhangsan">自定義異常處理</a> <a href="exception3">Springmvc本身異常處理</a> </body> </html>
ExceptionController.java
package com.mashibing.controller; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; @Controller public class ExceptionController { @RequestMapping("exception1") public String exception(){ System.out.println("exception......."); return "success"; } @RequestMapping("exception2") public String exception2(String username){ System.out.println("exception2222......."); if ("admin".equals(username)){ return "success"; }else{ throw new UserNameException(); } } @RequestMapping(value = "exception3",method = RequestMethod.POST) public String exception3(String username){ System.out.println("exception3......."); return "success"; } }