在使用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) {
......................