Spring MVC 關於controller的字符編碼問題


在使用springMVC框架構建web應用,客戶端常會請求字符串、整型、json等格式的數據,通常使用@ResponseBody注解使 controller回應相應的數據而不是去渲染某個頁面。如果請求的是非英文格式的字符串,往往在客戶端顯示的是亂碼。原因是spring的 StringHttpMessageConverter默認的字符類型是iso8895-1 ‘西歐語言',中文等字符需要單獨指定。

這里總結幾種解決方案:

1.不使用@ResponseBody注解,使用HttpServeletResponse設置contentType屬性

?
1
2
3
4
5
@RequestMapping (value = "/rest/create/document" )
public void create(Document document, HttpServletRespone respone) {
repoonse.setContentType( "text/plain;charset='utf-8'" );
response.write( "中文string" );
}

2.返回Response Entity object,設置contentType,例:

?
1
2
3
4
5
6
@RequestMapping (value = "/rest/create/document" ) public ResponseEntity<String> create(Document document, HttpServletRespone respone) {
HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add( "Content-Type" , "text/html; charset=utf-8" );
Document newDocument = DocumentService.create(Document);
String json = jsonSerializer.serialize(newDocument);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.OK);
}

3.使用produces屬性:

?
1
2
3
4
5
6
@RequestMapping (value = "/rest/create/document" ,produces= "text/plain;charset=UTF-8" ) //返回的內容類型
@ResponseBody
public String create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {
Document newDocument = DocumentService.create(Document);
return jsonSerializer.serialize(newDocument);
}

@RequestMapping

參數綁定(@RequestParam、 @RequestBody、 @RequestHeader 、 @PathVariable)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package org.springframework.web.bind.annotation;
 
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Target ({ElementType.METHOD, ElementType.TYPE})
@Retention (RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
   String name() default "" ;
 
   String[] value() default {};
 
   RequestMethod[] method() default {};
 
   String[] params() default {};
 
   String[] headers() default {};
 
   String[] consumes() default {};
 
   String[] produces() default {};
}

RequestMapping是一個用來處理請求地址映射的注解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。

RequestMapping注解有六個屬性。

1、value, method;

value: 指定請求的實際地址,指定的地址可以是URI Template 模式(后面將會說明);

method: 指定請求的method類型, GET、POST、PUT、DELETE等;

2、consumes,produces;

consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;

produces: 指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;

3、params,headers;

params: 指定request中必須包含某些參數值是,才讓該方法處理。

headers: 指定request中必須包含某些指定的header值,才能讓該方法處理請求。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM