[英]Spring MVC - Handling Errors, Form Submits with Multiple forms
I have a .JSP file that has three forms on it whose fields are dynamically shown/hidden based on user interaction with Javascript/Jquery elements.The forms are spring forms sending their action to a URL that matches a controller. 我有一个.JSP文件,上面有三种形式,它们的字段根据用户与Javascript / Jquery元素的交互而动态显示/隐藏。这些形式是将其操作发送到与控制器匹配的URL的spring形式。
The issue is that when I submit a form, and it does not validate, the URL the form submitted to stays in the URL. 问题是,当我提交表单且未通过验证时,表单提交的URL将保留在URL中。 Then any action I take that is URL dependent is basically corrupted because the URL has the form action appended to it.
然后,我执行的所有依赖于URL的操作都会被破坏,因为URL附加了form操作。
For example, if my .JSP's normal URL is /admin/
, and my spring form is: 例如,如果我的.JSP的常规URL为
/admin/
,而我的春季形式为:
<form:form id="form" method="POST" action="${pageContext.request.contextPath}/admin/createUser" modelAttribute="User">
If validation fails my URL will now be /admin/createUser
. 如果验证失败,我的URL现在将为
/admin/createUser
。 If I am then taking some action using Javascript/Jquery the URL is no longer a valid way to navigate. 如果我随后使用Javascript / Jquery采取措施,则URL不再是有效的导航方式。 I could just work around the URL but it just seems...un-ideal.
我可以绕过URL,但似乎……不理想。
I have tried using redirects like: "redirect:/admin/"
, but spring validation will not work with this because you are basically just reloading the page. 我已经尝试过使用诸如
"redirect:/admin/"
类的"redirect:/admin/"
,但是Spring验证将无法使用此方法,因为您基本上只是在重新加载页面。
Are there any best-practice or "elegant" solutions to this, or something really simple that I'm overlooking? 是否有任何最佳实践或“优雅”的解决方案,或者我忽略的真正简单的事情?
The redirection should probably be done on the client side anyways with a param of returnToURL, and as for error handling in Spring, you can register method as error handler to return proper error responses: 无论如何,重定向都应该在客户端使用returnToURL参数完成,对于Spring中的错误处理,您可以将方法注册为错误处理程序以返回正确的错误响应:
class YourController {
/**
* see @link{org.springframework.web.bind.annotation.ExceptionHandler}
*/
@ExceptionHandler(Exception.class)
public @ResponseBody String handleException(Exception e, HttpServletResponse rsp) {
// set the response status
return "{\"error\" : ...}"'
}
}
If you get error you can return error message to a custom error page to display the error message. 如果收到错误,则可以将错误消息返回到自定义错误页面以显示错误消息。 or in your case you can return the admin page again.. here is some example code .
或者根据您的情况,您可以再次返回管理页面。这是一些示例代码。
@RequestMapping(value = "/createUser" ,method = RequestMethod.POST) public ModelAndView create(@ModelAttribute User user) { if(user == null){ Map<String, String> model = new HashMap<String, String>(); model.put("errorCode", "00"); model.put("errorText", "Error Message Here"); return new ModelAndView("error_page", model); } return new ModelAndView("Welcome_page"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.