SpringMVC的數據響應-數據響應方式
- 頁面跳轉
直接返回字符串
@RequestMapping(value = {"/qq"},method = {RequestMethod.GET},params = {"name"})public String method(){System.out.println("controller");return "success";}
<bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="suffix" value=".jsp"/><property name="prefix" value="/WEB-INF/"/></bean>
通過ModelAndView對象返回
@RequestMapping(value = {"/qq2"})public ModelAndView method2(ModelAndView modelAndView){modelAndView.addObject("name","ccc");modelAndView.setViewName("success");return modelAndView;}@RequestMapping(value = {"/qq3"})public String method3(Model model){model.addAttribute("name","kkk");return "success";}
2) 回寫數據
直接返回字符串
返回對象或集合
SpringMVC的數據響應-回寫數據-返回對象或集合
在方法上添加@ResponseBody就可以返回json格式的字符串,但是這樣配置比較麻煩,配置的代碼比較多,因此,我們可以使用mvc的注解驅動代替上述配置
<mvc:annotation-driven/>
在 SpringMVC 的各個組件中,處理器映射器、處理器適配器、視圖解析器稱為 SpringMVC 的三大組件。
使用<mvc:annotation-driven />
自動加載 RequestMappingHandlerMapping(處理映射器)和
RequestMappingHandlerAdapter( 處 理 適 配 器 ),可用在Spring-xml.xml配置文件中使用
<mvc:annotation-driven />
替代注解處理器和適配器的配置。
同時使用<mvc:annotation-driven />
默認底層就會集成jackson進行對象或集合的json格式字符串的轉換
<?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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"><context:component-scan base-package="com.controller" />
<!-- <mvc:annotation-driven />--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="messageConverters"><list><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/></list></property></bean><bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="suffix" value=".jsp"/><property name="prefix" value="/WEB-INF/"/></bean>
</beans>
@RequestMapping(value = {"/qq5"})@ResponseBodypublic Student method5(Model model){Student student=new Student();student.setName("gg");student.setSno("1122");return student;}
SpringMVC的請求
SpringMVC的請求-獲得請求參數-請求參數類型
客戶端請求參數的格式是:name=value&name=value……
服務器端要獲得請求的參數,有時還需要進行數據的封裝,SpringMVC可以接收如下類型的參數
基本類型參數
POJO類型參數
數組類型參數
集合類型參數
SpringMVC的請求-獲得請求參數-獲得基本類型參數(應用)
Controller中的業務方法的參數名稱要與請求參數的name一致,參數值會自動映射匹配。并且能自動做類型轉換;
http://localhost:8080/qq6?name=zzx&sno=17582
自動的類型轉換是指從String向其他類型的轉換
@RequestMapping(value = {"/qq6"})@ResponseBodypublic void method6(String name,String sno){System.out.println(name);System.out.println(sno);}
SpringMVC的請求-獲得請求參數-獲得POJO類型參數(應用)
Controller中的業務方法的POJO參數的屬性名與請求參數的name一致,參數值會自動映射匹配。
@RequestMapping(value = {"/qq7"})@ResponseBodypublic void method7(Student student){System.out.println(student);}
SpringMVC的請求-獲得請求參數-獲得數組類型參數
Controller中的業務方法數組名稱與請求參數的name一致,參數值會自動映射匹配。
@RequestMapping(value = {"/qq8"})@ResponseBodypublic void method8(String[] student){System.out.println(Arrays.asList(student));}
SpringMVC的請求-獲得請求參數-獲得集合類型參數
獲得集合參數時,要將集合參數包裝到一個POJO中才可以。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/qq9" method="post"><%--表明是第一個User對象的username age--%><input type="text" name="students[0].name"><br/><input type="text" name="students[0].sno"><br/><input type="text" name="students[1].name"><br/><input type="text" name="students[1].sno"><br/><input type="submit" value="提交">
</form>
</body>
</html>
@RequestMapping(value = {"/qq9"})@ResponseBodypublic void method9(VO student){System.out.println(student);}public class VO {List<Student> students;public List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}@Overridepublic String toString() {return "VO{" +"students=" + students +'}';}
}
SpringMVC的請求-獲得請求參數-獲得集合類型參數2
當使用ajax提交時,可以指定contentType為json形式,那么在方法參數位置使用@RequestBody可以直接接收集合數據而無需使用POJO進行包裝
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>var userList = new Array();userList.push({name:"zhangsan",sno:"c11"});userList.push({name:"lisi",sno:"c12"});$.ajax({type:"POST",url:"${pageContext.request.contextPath}/qq10",data:JSON.stringify(userList),contentType:"application/json;charset=utf-8"});</script>
</body>
</html>@RequestMapping(value = {"/qq10"})@ResponseBodypublic void method10(@RequestBody List<Student> userList){System.out.println(userList);}
SpringMVC的請求-獲得請求參數-靜態資源訪問的開啟
<url-pattern>/</url-pattern>
攔截所有請求包括靜態資源,springMVC會將靜態資源當做一個普通的請求處理,從而也找不到相應的處理器導致404錯誤.這時候dispatchServlet完全取代了default servlet,將不會再訪問容器中原始默認的servlet,而對靜態資源的訪問就是通過容器默認servlet來處理的,故而這時候靜態資源將不可訪問。
當有靜態資源需要加載時,比如jquery文件,通過谷歌開發者工具抓包發現,沒有加載到jquery文件,原因是SpringMVC的前端控制器DispatcherServlet的url-pattern配置的是/,代表對所有的資源都進行過濾操作,我們可以通過以下兩種方式指定放行靜態資源:
?在spring-mvc.xml配置文件中指定放行的資源
? <mvc:resources mapping="/js/**"location="/js/"/>
?使用<mvc:default-servlet-handler/>
標簽
<!--開發資源的訪問--><!--<mvc:resources mapping="/js/**" location="/js/"/><mvc:resources mapping="/img/**" location="/img/"/>--><mvc:default-servlet-handler/>
這里有有一點要注意,default servlet對于使用beanName方式配置的處理器,是可以訪問的.但是對于@RequestMapping注解方式配置的處理器是不起作用的,
因為沒有相應的HandlerMapping和HandlerAdapter支持注解的使用。這時候可以使用<mvc:annotation-driven/>
配置在容器中注冊支持@RequestMapping注解的組件即可.
SpringMVC的請求-獲得請求參數-配置全局亂碼過濾器
當post請求時,數據會出現亂碼,我們可以設置一個過濾器來進行編碼的過濾。
<filter><filter-name>filter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>ending</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>filter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
@RequestMapping(value = {"/qq6"})@ResponseBodypublic void method6(String name,String sno){System.out.println(name);System.out.println(sno);}
19-SpringMVC的請求-獲得請求參數-參數綁定注解@RequestParam(應用)
當請求的參數名稱與Controller的業務方法參數名稱不一致時,就需要通過@RequestParam注解顯示的綁定
@RequestMapping(value = {"/qq11"})@ResponseBodypublic void method11(@RequestParam(value="name",required = false, defaultValue = "xxx") String userName){System.out.println(userName);}<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hhhh</title>
</head>
<body>
<h1>hello</h1>
<form action="${pageContext.request.contextPath}/qq11" method="post"><input type="text" name="name"><br><input type="submit" value="提交"><br>
</form>
</body>
</html>
SpringMVC的請求-獲得請求參數-Restful風格的參數的獲取
Restful是一種軟件架構風格、設計風格,而不是標準,只是提供了一組設計原則和約束條件。主要用于客戶端和服務器交互類的軟件,基于這個風格設計的軟件可以更簡潔,更有層次,更易于實現緩存機制等。
Restful風格的請求是使用“url+請求方式”表示一次請求目的的,HTTP 協議里面四個表示操作方式的動詞如下:
GET:用于獲取資源
POST:用于新建資源
PUT:用于更新資源
DELETE:用于刪除資源
例如:
/user/1 GET : 得到 id = 1 的 user
/user/1 DELETE: 刪除 id = 1 的 user
/user/1 PUT: 更新 id = 1 的 user
/user POST: 新增 user
上述url地址/user/1中的1就是要獲得的請求參數,在SpringMVC中可以使用占位符進行參數綁定。地址/user/1可以寫成/user/{id},占位符{id}對應的就是1的值。在業務方法中我們可以使用@PathVariable注解進行占位符的匹配獲取工作。
http://localhost:8080/qq12/xxx
@RequestMapping(value = {"/qq12/{name}"})@ResponseBodypublic void method12(@PathVariable(value="name",required = false) String userName){System.out.println(userName);}
SpringMVC的請求-獲得請求參數-自定義類型轉換器
SpringMVC 默認已經提供了一些常用的類型轉換器,例如客戶端提交的字符串轉換成int型進行參數設置。
但是不是所有的數據類型都提供了轉換器,沒有提供的就需要自定義轉換器,例如:日期類型的數據就需要自定義轉換器。
public class DateConverter implements Converter<String, Date> {public Date convert(String s) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date=null;try {date =simpleDateFormat.parse(s);} catch (ParseException e) {e.printStackTrace();}return date;}
}@RequestMapping(value = {"/qq13"})@ResponseBodypublic void method13(Date date){System.out.println(date);}
<mvc:annotation-driven conversion-service="conversionService2"/><mvc:default-servlet-handler/><bean id="conversionService2" class="org.springframework.context.support.ConversionServiceFactoryBean"><property name="converters"><list><bean class="com.controller.DateConverter"/></list></property></bean>
SpringMVC的請求-獲得請求參數-獲得Servlet相關API
SpringMVC支持使用原始ServletAPI對象作為控制器方法的參數進行注入,常用的對象如下:
HttpServletRequest
HttpServletResponse
HttpSession
@RequestMapping(value = {"/qq14"})@ResponseBodypublic void method14(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession httpSession){System.out.println(httpServletRequest);System.out.println( httpServletResponse);System.out.println(httpSession);}
SpringMVC的請求-獲得請求參數-獲得請求頭信息
使用@RequestHeader可以獲得請求頭信息,相當于web階段學習的request.getHeader(name)
@RequestHeader注解的屬性如下:
value:請求頭的名稱
required:是否必須攜帶此請求頭
使用@CookieValue可以獲得指定Cookie的值
@RequestMapping(value = {"/qq16"})@ResponseBodypublic void method16(@RequestHeader(value = "User-Agent",required = false) String User ){System.out.println(User);}
@CookieValue注解的屬性如下:
value:指定cookie的名稱
required:是否必須攜帶此cookie
@RequestMapping(value = {"/qq17"})@ResponseBodypublic void method17(@CookieValue(value = "JSESSIONID",required = false) String User ){System.out.println(User);}
SpringMVC的請求-文件上傳-客戶端表單實現
文件上傳客戶端表單需要滿足:
表單項type=“file”
表單的提交方式是post
表單的enctype屬性是多部分表單形式,及enctype=“multipart/form-data”
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hhhh</title>
</head>
<body><form action="${pageContext.request.contextPath}/qq18" method="post" enctype="multipart/form-data">名稱 <input type="text" name="name"><br/>文件1<input type="file" name="multipartFile"><br/><input type="submit" value="提交">
</form></body>
</html>
3-SpringMVC的請求-文件上傳-單文件上傳的代碼實現
添加依賴
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.3</version></dependency>
配置多媒體解析器
<!--配置文件上傳解析器,id必須為multipartResolver,否則會出錯--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"/><property name="maxUploadSize" value="500000"/></bean>
完成文件上傳
@RequestMapping(value = {"/qq18"})@ResponseBodypublic void method17(String name, MultipartFile multipartFile){System.out.println(name);try {multipartFile.transferTo(new File("e://"+multipartFile.getOriginalFilename()));} catch (IOException ioException) {ioException.printStackTrace();}}
SpringMVC的請求-文件上傳-多文件上傳的代碼實現
多文件上傳,只需要將頁面修改為多個文件上傳項,將方法參數MultipartFile類型修改為MultipartFile[]即可
@RequestMapping(value = {"/qq19"})@ResponseBodypublic void method19(String name, MultipartFile[] multipartFiles){System.out.println(name);try {for (MultipartFile multipartFile : multipartFiles) {multipartFile.transferTo(new File("e://"+multipartFile.getOriginalFilename()));}} catch (IOException ioException) {ioException.printStackTrace();}<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hhhh</title>
</head>
<body><form action="${pageContext.request.contextPath}/qq19" method="post" enctype="multipart/form-data">名稱 <input type="text" name="name"><br/>文件1<input type="file" name="multipartFile"><br/>文件2<input type="file" name="multipartFile"><br/><input type="submit" value="提交">
</form></body>
</html>