我使用彈簧4.1.3.RELEASE彈簧顯示錯誤消息
我有以下形式:
<form method="GET">
<label for="employeeId">Id:</label>
<form:input path="empId" />
<input type="submit" />
</form>
提交按鈕發送這是會通過以下的方法進行處理的請求:
@RequestMapping(value="/{empId}", method=RequestMethod.GET)
public String getEmployeeById(@PathVariable @ModelAttribute String empId, BindException binding, Model model){
try{
model.addAttribute("employee", employeeDAO.getEmployeeById(Integer.valueOf(empId)));
} catch (EmptyResultDataAccessException ex) {
binding.reject("405", "Employee not found");
}
return "employeesList";
}
的employeeDAO.getEmployeeById
方法拋出EmptyResultDataAccessException
如果有這樣的一個ID沒有僱員。如果拋出異常,我需要顯示錯誤消息。我提供的代碼不起作用。它拋出一個expcetion:
java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply: public java.lang.String com.badmitrii.EmployeeListController.getEmployeeById(java.lang.String,org.springframework.validation.BindException,org.springframework.ui.Model)
org.springframework.web.method.annotation.ErrorsMethodArgumentResolver.resolveArgument(ErrorsMethodArgumentResolver.java:64)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
我試圖刪除@ModelAttribute
,但同樣expcetion發生了。如何解決這個問題?也許有更好的方法去做,而不是嘗試處理BindingException
類的異常?
你的控制器是有缺陷的,你是不是使用的模型,因此'@ ModelAttribute'是沒有幫助這裏,'@ PathVariable'僅適用於包含ID,您所提交它作爲一個請求參數的URL。 –