Java超詳細講解SpringMVC如何獲取請求數(shù)據(jù)
1.獲得請求參數(shù)
客戶端請求參數(shù)的格式是:name=value&name=value… … 服務器端要獲得請求的參數(shù),有時還需要進行數(shù)據(jù)的封裝,SpringMVC可以接收如下類型的參數(shù):
1)基本類型參數(shù):
Controller中的業(yè)務方法的參數(shù)名稱要與請求參數(shù)的name一致,參數(shù)值會自動映射匹配。
//http://localhost:8080/project/quick9?username=zhangsan&age=12 @RequestMapping("/quick9") @ResponseBody public void quickMethod9(String username,int age) throws IOException { System.out.println(username); System.out.println(age); }
2)POJO類型參數(shù):
Controller中的業(yè)務方法的POJO參數(shù)的屬性名與請求參數(shù)的name一致,參數(shù)值會自動映射匹配。
//http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12 public class User { private String username; private int age; getter/setter… } @RequestMapping("/quick10") @ResponseBody public void quickMethod10(User user) throws IOException { System.out.println(user); }
3)數(shù)組類型參數(shù)
Controller中的業(yè)務方法數(shù)組名稱與請求參數(shù)的name一致,參數(shù)值會自動映射匹配。
//http://localhost:8080/project/quick11?strs=111&strs=222&strs=333 @RequestMapping("/quick11") @ResponseBody public void quickMethod11(String[] strs) throws IOException { System.out.println(Arrays.asList(strs)); }
4)集合類型參數(shù)
獲得集合參數(shù)時,要將集合參數(shù)包裝到一個POJO中才可以。
<form action="${pageContext.request.contextPath}/quick12" method="post"> <input type="text" name="userList[0].username"><br> <input type="text" name="userList[0].age"><br> <input type="text" name="userList[1].username"><br> <input type="text" name="userList[1].age"><br> <input type="submit" value="提交"><br> </form>
@RequestMapping("/quick12") @ResponseBody public void quickMethod12(Vo vo) throws IOException { System.out.println(vo.getUserList()); }
當使用 ajax提交時,可以指定 contentType為json形式,那么在方法參數(shù)位置使用@RequestBody可以 直接接收集合數(shù)據(jù)而無需使用POJO進行包裝。
<script> //模擬數(shù)據(jù) var userList = new Array(); userList.push({username: "zhangsan",age: "20"}); userList.push({username: "lisi",age: "20"}); $.ajax({ type: "POST", url: "/itheima_springmvc1/quick13", data: JSON.stringify(userList), contentType : 'application/json;charset=utf-8' }); </script>
@RequestMapping("/quick13") @ResponseBody public void quickMethod13(@RequestBody List<User> userList) throws IOException { System.out.println(userList); }
注意: 通過谷歌開發(fā)者工具抓包發(fā)現(xiàn),沒有加載到jquery文件,原因是SpringMVC的前端控制器 DispatcherServlet的url-pattern配置的是/,代表對所有的資源都進行過濾操作,我們可以通過以下兩種方式指定放行靜態(tài)資源: • 在spring-mvc.xml配置文件中指定放行的資源
<mvc:resources mapping="/js/**" location="/js/"/>
• 或者使用<mvc:default-servlet-handler/>標簽
2.請求亂碼問題
當post請求時,數(shù)據(jù)會出現(xiàn)亂碼,我們可以在web.xml設置一個過濾器來進行編碼的過濾。
<!--資源過濾器--> <filter> <filter-name>CharacterEncodingFilter</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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
當請求的參數(shù)名稱與Controller的業(yè)務方法參數(shù)名稱不一致時,就需要通過@RequestParam注解顯示的綁定。
<form action="${pageContext.request.contextPath}/quick14" method="post"> <input type="text" name="name"><br> <input type="submit" value="提交"><br> </form>
3.參數(shù)綁注解@RequestParam???????
注解@RequestParam還有如下參數(shù)可以使用:
value: | 請求參數(shù)名稱 |
required: | 此在指定的請求參數(shù)是否必須包括,默認是true,提交時如果沒有此參數(shù)則報錯 |
defaultValue: | 當沒有指定請求參數(shù)時,則使用指定的默認值賦值 |
@RequestMapping("/quick14") @ResponseBody public void quickMethod14(@RequestParam(value="name",required = false,defaultValue = "defaultname") String username) throws IOException { System.out.println(username); }
4.獲得Restful風格的參數(shù)
Restful是一種軟件 架構風格、 設計風格,而不是標準,只是提供了一組設計原則和約束條件。主要用于客戶端和服務 器交互類的軟件,基于這個風格設計的軟件可以更簡潔,更有層次,更易于實現(xiàn)緩存機制等。
Restful風格的請求是使用 “url+請求方式”表示一次請求目的的,HTTP 協(xié)議里面四個表示操作方式的動詞如下:
GET : | 獲取資源 |
DELETE: | 刪除資源 |
PUT: | 更新資源 |
POST: | 新建資源 |
例如:
/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就是要獲得的請求參數(shù),在SpringMVC中可以使用占位符進行參數(shù)綁定。地址/user/1可以寫成 /user/{id},占位符{id}對應的就是1的值。在業(yè)務方法中我們可以使用@PathVariable注解進行占位符的匹配獲取工作。
//http://localhost:8080/itheima_springmvc1/quick19/zhangsan @RequestMapping("/quick19/{name}") @ResponseBody public void quickMethod19(@PathVariable(value = "name",required = true) String name){ System.out.println(name); }
5.自定義類型轉(zhuǎn)換器
- 雖然SpringMVC 默認已經(jīng)提供了一些常用的類型轉(zhuǎn)換器,例如客戶端提交的字符串轉(zhuǎn)換成int型進行參數(shù)設置。
- 但是不是所有的數(shù)據(jù)類型都提供了轉(zhuǎn)換器,沒有提供的就需要自定義轉(zhuǎn)換器,例如:日期類型的數(shù)據(jù)就需要自 定義轉(zhuǎn)換器。
自定義類型轉(zhuǎn)換器的開發(fā)步驟:
① 定義轉(zhuǎn)換器類實現(xiàn)Converter接口
public class DateConverter implements Converter<String, Date> { @Override public Date convert(String source) { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = format.parse(source); } catch (ParseException e) { e.printStackTrace(); } return date; } }
② 在spring-mvc.xml配置文件中聲明轉(zhuǎn)換器
<!--配置自定義轉(zhuǎn)換器--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="converter.DateConverter"/> </list> </property> </bean>
③ 在<annotation-driven>中引用轉(zhuǎn)換器
<!--注解驅(qū)動--> <mvc:annotation-driven conversion-service="conversionService"/>
6.獲得請求頭
@RequestHeader
使用@RequestHeader可以獲得請求頭信息,相當于web階段學習的request.getHeader(name) @RequestHeader注解的屬性如下:
value | 請求頭的名稱 |
required | 是否必須攜帶此請求頭 |
@RequestMapping("/quick17") @ResponseBody public void quickMethod17(@RequestHeader(value = "User-Agent",required = false) String headerValue){ System.out.println(headerValue); }
@CookieValue
使用@CookieValue可以獲得指定Cookie的值
@CookieValue注解的屬性如下:
value | 指定cookie的名稱 |
required | 是否必須攜帶此cookie |
@RequestMapping("/quick18") @ResponseBody public void quickMethod18(@CookieValue(value = "JSESSIONID",required = false) String jsessionid){ System.out.println(jsessionid); }
7.文件上傳
文件上傳客戶端三要素:
- 表單項type=“file”
- 表單的提交方式是post
- 表單的enctype屬性是多部分表單形式,及enctype=“multipart/form-data”??????????????
<form action="${pageContext.request.contextPath}/quick20" method="post" enctype="multipart/form-data"> 名稱:<input type="text" name="name"><br> 文件:<input type="file" name="file"><br> <input type="submit" value="提交"><br> </form>
文件上傳步驟
① 在pom.xml導入fileupload和io坐標
<!--文件下載--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
② 配置文件上傳解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="500000"/> </bean>
③ 編寫文件上傳代碼
@RequestMapping("/quick8") @ResponseBody public void save8(String name, MultipartFile uploadfile) { System.out.println("save8 running..."); System.out.println(name); String filename = uploadfile.getOriginalFilename(); try { uploadfile.transferTo(new File("D:\\upload\\"+filename)); } catch (IOException e) { e.printStackTrace(); } }
8.小結
MVC實現(xiàn)數(shù)據(jù)請求參數(shù)配置
- 基本類型參數(shù)
- POJO類型參數(shù)
- 數(shù)組類型參數(shù)
- 集合類型參數(shù)???????
MVC獲取請求數(shù)據(jù)處理
- 中文亂碼問題
- @RequestParam 和 @PathVariable
- 獲得Servlet相關API
- @RequestHeader 和 @CookieValue
- 文件上傳
到此這篇關于Java超詳細講解SpringMVC如何獲取請求數(shù)據(jù)的文章就介紹到這了,更多相關Java SpringMVC 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- SpringMVC詳解如何映射請求數(shù)據(jù)
- 關于SpringMVC請求域?qū)ο蟮臄?shù)據(jù)共享問題
- SpringMVC 重新定向redirect請求中攜帶數(shù)據(jù)方式
- 使用springmvc的controller層獲取到請求的數(shù)據(jù)方式
- Springmvc獲取前臺請求數(shù)據(jù)過程解析
- Springmvc處理ajax請求并返回json數(shù)據(jù)
- SpringMVC 跨重定向請求傳遞數(shù)據(jù)的方法實現(xiàn)
- SpringMVC解析JSON請求數(shù)據(jù)問題解析
- SpringMVC請求數(shù)據(jù)詳解講解
相關文章
SpringCloud Gateway的路由,過濾器和限流解讀
這篇文章主要介紹了SpringCloud Gateway的路由,過濾器和限流解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02MyBatis-Plus攔截器實現(xiàn)數(shù)據(jù)權限控制的方法
MyBatis-Plus是一款基于MyBatis的增強工具,它提供了一些便捷的功能和增強的查詢能力,數(shù)據(jù)權限控制是在系統(tǒng)中對用戶訪問數(shù)據(jù)進行限制的一種機制,這篇文章主要給大家介紹了關于MyBatis-Plus攔截器實現(xiàn)數(shù)據(jù)權限控制的相關資料,需要的朋友可以參考下2024-01-01