SpringMVC綁定基本類型參數的問題

在使用SpringMVC綁定基本類型(如String,Integer等)參數時,應通過@RequestParam註解指定具體的參數名稱,否則,當源代碼在非debug模式下編譯後,運行時會引發HandlerMethodInvocationException異常,這是因爲只有在debug模式下編譯,其參數名稱才存儲在編譯好的代碼中。

譬如下面的代碼會引發異常:

@RequestMapping(value = "/security/login", method = RequestMethod.POST)
public ModelAndView login(@RequestParam String userName, @RequestParam String password,
HttpServletRequest request) {
......................



如果使用Eclipse編譯不會在運行時出現異常,這是因爲Eclipse默認是採用debug模式編譯的,但是如果使用Ant通過javac任務編譯的話就會出現異常,除非指定debug=”true”。出現的異常如同:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public org.springframework.web.servlet.ModelAndView com.mypackage.security.controller.LoginController.login(java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest)]; nested exception is java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
..........

org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public org.springframework.web.servlet.ModelAndView com.mypackage.security.controller.LoginController.login(java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest)]; nested exception is java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
..........


java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.getRequiredParameterName(HandlerMethodInvoker.java:618)
..........

最好的做法是通過@RequestParam註解指定具體的參數名稱,如,上面的代碼應該如此編寫(注意@RequestParam部分):

@RequestMapping(value = "/security/login", method = RequestMethod.POST)
public ModelAndView login(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpServletRequest request) {
......................


參考:http://stackoverflow.com/questions/2622018/compile-classfile-issue-in-spring-3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章