1. 程式人生 > 實用技巧 >springMVC學習(四)JSON傳遞

springMVC學習(四)JSON傳遞

接收、返回JSON

  • 匯入fastjson開發包

  • 配置JSON介面卡(註解驅動模式)

<!--註解驅動-->
<mvc:annotation-driven>
<!-- register-defaults="true"表示使用預設的訊息轉換器 -->
<mvc:message-converters register-defaults="true">
<!-- fastjson介面卡 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 這裡順序不能反,一定先寫text/html,不然IE執行AJAX時,返回JSON會出現下載檔案 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
<property name="fastJsonConfig">
<bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
<property name="features">
<list>
<value>AllowArbitraryCommas</value>
<value>AllowUnQuotedFieldNames</value>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

使用兩個註解

  • @RequestBody,作用在形參列表上,用於將前臺傳送過來固定格式的資料【xml 格式或者 json等】封裝為對應的 JavaBean 物件,封裝時使用到的一個物件是系統預設配置的 HttpMessageConverter進行解析,然後封裝到形參上

  • @ResponseBody,作用在方法上的,@ResponseBody 表示該方法的返回結果直接寫入 HTTP response body 中,一般在非同步獲取資料時使用【也就是AJAX】,在使用 @RequestMapping後,返回值通常解析為跳轉路徑,但是加上 @ResponseBody 後返回結果不會被解析為跳轉路徑,而是直接寫入 HTTP response body 中。@ResponseBody就可以理解成將java的物件轉換成json字串的格式給前端解析(json資料格式解析比較簡單)。如果不加,就走檢視解析器,返回頁面

  @RequestMapping(value = "/json.action")
public @ResponseBody User jsonTest(@RequestBody User user){
user.setId("2");
return user;
}

使用postman請求時,設定 Content-Type:application/json;charset=utf-8

HttpMessageConverter

在使用 <mvc:annotation-driven />標籤配置時,預設配置了RequestMappingHandlerAdapter,並配置了一下預設的HttpMessageConverter

  • ByteArrayHttpMessageConverter: 負責讀取二進位制格式的資料和寫出二進位制格式的資料;

  • StringHttpMessageConverter: 負責讀取字串格式的資料和寫出二進位制格式的資料;

  • ResourceHttpMessageConverter:負責讀取資原始檔和寫出資原始檔資料;

  • FormHttpMessageConverter: 負責讀取form提交的資料(能讀取的資料格式為 application/x-www-form-urlencoded,不能讀取multipart/form-data格式資料);負責寫入application/x-www-from-urlencoded和multipart/form-data格式的資料;

  • MappingJacksonHttpMessageConverter: 負責讀取和寫入json格式的資料;

  • SouceHttpMessageConverter: 負責讀取和寫入 xml 中javax.xml.transform.Source定義的資料;

  • Jaxb2RootElementHttpMessageConverter: 負責讀取和寫入xml 標籤格式的資料;

  • AtomFeedHttpMessageConverter: 負責讀取和寫入Atom格式的資料;

  • RssChannelHttpMessageConverter: 負責讀取和寫入RSS格式的資料;

當使用@RequestBody和@ResponseBody註解時,RequestMappingHandlerAdapter就使用它們來進行讀取或者寫入相應格式的資料

引數繫結

springmvc的引數繫結有以下幾種方法:

1)預設的引數繫結 Request Response Session Model(實現ModelMap)

2)簡單型別引數繫結 方法的形參上(Integer,String,Double,Boolean)

3)pojo型別

4)包裝型別 QueryVo

5)引數繫結之自定義引數轉換

高階引數繫結 1)繫結陣列 直接在方法的引數上繫結 xxx[] xxx 將陣列注入物件,用該物件來接受陣列

2)繫結list 使用包裝類,包裝類中有list集合

自定義引數轉換步驟(不再使用@InitBinder註解)

  • 定義轉換類,實現Conveter介面

public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
public class StringTrimConverter implements Converter<String,String> {
@Override
public String convert(String s) {
return s.trim();
}
}
  • 配置轉換器(基於註解驅動)

  <!--自定義引數轉換器-->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converters.DateConverter"/>
<bean class="converters.StringTrimConverter"/>
</list>
</property>
</bean>
<!--註解驅動-->
<mvc:annotation-driven conversion-service="conversionService">

@RequestParam註解

如果前端傳遞的引數名稱和業務方法中的引數名稱不一樣,就需要使用@RequestParam註解(在方法形參前使用),該註解有三個變數

  • value,指定前端傳遞的屬性名稱

  • required,是否必須要有該引數

  • defaultvalue,設定預設值

資料回顯

提交後,如果出現錯誤,將剛才提交的資料回顯到剛才的提交頁面,就需要用到資料回顯,有以下幾種回顯方法:

  • springmvc預設對pojo資料進行回顯:springmvc預設支援pojo資料回顯,springmvc自動將形參中的pojo重新放回request域中,request的key為pojo的類名(首字母小寫),jsp頁面呼叫

<input name="pojo的屬性名" value="${pojo.屬性名}">
  • 如果key不是pojo的類名(首字母小寫),可以使用@ModelAttribute完成資料回顯

//相當於 model.addAttribute("item", itemsCustom)
public String editItemSubmit(Model model,@ModelAttribute("item") ItemsCustomitemsCustom)

jsp頁面呼叫

<input name="item的屬性名" value="${item.屬性名}">
  • 簡單型別資料回顯,最簡單方法是使用model。model.addAttribute("id", id)

  • 如果要回顯的資料是公共的,在方法上使用@ModelAttribute,就不用在每一個controller方法通過Model將資料傳到頁面

  //單獨將商品型別的方法提出來
@ModelAttribute("itemsType")
public Map<String,String> getItemsType(){
Map<String,String> itemsType=new HashMap<>();
itemsType.put("1","數碼");
itemsType.put("2","服裝");
return itemsType;
}

檔案上傳

新增依賴

  • commons-fileupload-1.2.2.jar

  • commons-io-2.4.jar

配置檔案上傳解析器

  <!--檔案上傳配置-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設定上傳檔案的最大尺寸為5MB和編碼 -->
<property name="maxUploadSize" value="5242880"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>

controller

  @RequestMapping("/upload.action")
public void upload(MultipartFile picture){
//MultipartFile該物件就是封裝了圖片檔案
System.out.println(picture.getOriginalFilename());
}

jsp

<form action="/upload.action" method="post" enctype="multipart/form-data" >
<input type="file" name="picture">
<input type="submit" value="submit">
</form>