2015-12-03 102 views
0

我有一個.JSP文件,它有三種形式,其字段根據用戶與Javascript/Jquery元素的交互動態顯示/隱藏。形式是發送它們的彈簧形式操作到與控制器相匹配的URL。Spring MVC - 處理錯誤,表單提交多種形式

問題是,當我提交表單並且它沒有驗證時,表單提交的URL保留在URL中。然後,我採取的任何與URL相關的操作基本上都會損壞,因爲URL具有附加到表單的操作。

例如,如果我.JSP的正常網址是/admin/,我的春天的形式是:

<form:form id="form" method="POST" action="${pageContext.request.contextPath}/admin/createUser" modelAttribute="User"> 

如果驗證失敗,我的網址現在將/admin/createUser。如果我正在使用Javascript/Jquery進行一些操作,則URL不再是有效的導航方式。我可以只是圍繞網址工作,但似乎......不理想。

我已經嘗試使用重定向,如:"redirect:/admin/",但彈簧驗證不會與此工作,因爲你基本上只是重新加載頁面。

是否有任何最佳實踐或「優雅」的解決方案,或者我忽略了一些非常簡單的東西?

回答

0

重定向可能應該在客戶端完成反正有returnToURL的PARAM,並以此爲錯誤在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\" : ...}"' 
    } 
} 
0

如果如果出現錯誤,您可以將錯誤消息返回到自定義錯誤頁面以顯示錯誤消息。或者在你的情況下,你可以再次返回管理頁面。 這裏是一些示例代碼。


@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"); 
 
    }