2016-06-01 34 views
0

嗯,我有,當我將數據發送到我的controller一個問題:Spring MVC的轉換器

@RequestMapping("/someUrl") 
public String method(@RequestParam Long id) { 
    //do something 
} 

所以,如果我送字符串「null」我有例外

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [java.lang.Long]; 

我明白爲什麼所以,但我怎麼能改變轉換器?我想要字符串「null」轉換爲空。也許有其他方法可以解決這個問題嗎?

+0

我期待這樣的網址在第一位:/ someUrl/{id}。你爲什麼不把它自己轉換成處理程序? – Neron

+1

@Neron這是一個路徑參數,而不是一個請求參數。至於轉換自己,爲什麼你會這樣做,而不是讓框架處理它呢? – Kayaman

+1

請參閱[documentation](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-typeconversion)瞭解如何將自定義添加到轉換器。 – Kayaman

回答

2

使用空,你不應該在URL中使用的參數和使用@RequestParam

RequestMapping("/someUrl") 
public String method(@RequestParam(required = false) Long id) { 
    //do something 
} 

所需attribut然後請求URL像http://example.com/someUrl

或者,如果你真的需要發送「空」,然後使用一個自定義轉換器http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-typeconversion

+0

我的意思是'空'像一個字符串 –

+0

那麼你需要一個來定製轉換器 – JEY

1

剛剛從Long改變ID的類型String,不讓它像需要建議@JEY

@RequestMapping("/someUrl") 
public String method(@RequestParam(required = false) String id) { 
    if(id!=null) 
     Long l = Long.valueOf(id) 
    //do something 
}