.官網連接 ,可以看出有三種方式
.目前只寫 converter,其他兩種有空再寫
※converter
※Java Bean
public class Book { private Integer id; private String name; private Integer price; // setter/getter... public Book() {} public Book(Integer id, String name, Integer price) { this.id = id; this.name = name; this.price = price; } }
※假設前端傳三個值為 id@name@price 這樣的格式,所以我在此類有三個屬性
※轉換類
@Component public class TestConverter implements Converter<String, Book> { @Override public Book convert(String source) { String[] array = source.split("@"); return new Book(Integer.valueOf(array[0]), array[1], Integer.valueOf(array[2])); } }
※
※spring 設定檔
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" p:converters-ref="testConverter" /> <mvc:annotation-driven conversion-service="conversionService" />
※conversion-service 不加會 500
※測試
@RequestMapping("book") public String pojo(@RequestParam("xxx") Book b) { System.out.println(b.getId()); System.out.println(b.getPrice()); System.out.println(b.getName()); return "hello"; } ------------------------------ <a href="ooo/xxx/book.mvc?xxx=123@toy@500">bookTransfer</a>
※如果不合乎自訂的轉換要求,會出現 400,描述為「The request sent by the client was syntactically incorrect.」
※注意:如果前端傳 Book 的屬性,如 id、name、price 只是給 Book 塞值,並不會去轉換
※傳特殊字元
public void bruceTest() throws UnsupportedEncodingException { final String encode = "UTF-8"; final String and = URLEncoder.encode("&", encode); System.out.println(and); System.out.println(URLDecoder.decode(and, encode)); } ------------------------------ const and = encodeURIComponent("&"); console.log(and); console.log(decodeURIComponent(and));
※上面是 java,下面是javascript,使用此方式,可以知道網址列的特殊字元的編碼為何
※假設想傳 ooo/xxx/book.mvc?xxx=123&toy&500,但「&」是 get 請求的關鍵字,所以要用「%26」取代,變成 ooo/xxx/book.mvc?xxx=123%26toy%26500
沒有留言:
張貼留言