2011-03-21 39 views
1

我想驗證Spring 3 MVC表單。當元素無效時,我想用驗證消息重新顯示錶單。迄今爲止這非常簡單。蹭的是,當用戶在無效提交後點擊刷新時,我不希望他們發佈POST,我希望他們GET。這意味着我需要從POST(提交)表單重做一個重定向來重新顯示帶有驗證消息的表單(表單通過POST提交)。Spring MVC驗證 - 避免POST回

我在想最好的方法是使用SessionAttributeStore.retrieveAttribute來測試表單是否已經在用戶的會話中。如果是,請使用商店表單,否則請創建一個新表單。

聽起來不錯?有一個更好的方法嗎?

回答

1

爲了解決這個問題,我在一個POST重定向之後將錯誤對象存儲在會話中。然後,在GET上,我將它放回到模型中。這裏有一些漏洞,但它應該工作99.999%的時間。

public class ErrorsRedirectInterceptor extends HandlerInterceptorAdapter { 
    private final static Logger log = Logger.getLogger(ErrorsRedirectInterceptor.class); 

    private final static String ERRORS_MAP_KEY = ErrorsRedirectInterceptor.class.getName() 
      + "-errorsMapKey"; 

    @Override 
    public void postHandle(HttpServletRequest request, HttpServletResponse response, 
      Object handler, ModelAndView mav) 
     throws Exception 
    { 
     if (mav == null) { return; } 

     if (request.getMethod().equalsIgnoreCase(HttpMethod.POST.toString())) { 
      // POST 
      if (log.isDebugEnabled()) { log.debug("Processing POST request"); } 
      if (SpringUtils.isRedirect(mav)) { 
       Map<String, Errors> sessionErrorsMap = new HashMap<String, Errors>(); 
       // If there are any Errors in the model, store them in the session 
       for (Map.Entry<String, Object> entry : mav.getModel().entrySet()) { 
        Object obj = entry.getValue(); 
        if (obj instanceof Errors) { 
         if (log.isDebugEnabled()) { log.debug("Adding errors to session errors map"); } 
         Errors errors = (Errors) obj; 
         sessionErrorsMap.put(entry.getKey(), errors); 
        } 
       } 
       if (!sessionErrorsMap.isEmpty()) { 
        request.getSession().setAttribute(ERRORS_MAP_KEY, sessionErrorsMap); 
       } 
      } 
     } else if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.toString())) { 
      // GET 
      if (log.isDebugEnabled()) { log.debug("Processing GET request"); } 
      Map<String, Errors> sessionErrorsMap = 
        (Map<String, Errors>) request.getSession().getAttribute(ERRORS_MAP_KEY); 
      if (sessionErrorsMap != null) { 
       if (log.isDebugEnabled()) { log.debug("Adding all session errors to model"); } 
       mav.addAllObjects(sessionErrorsMap); 
       request.getSession().removeAttribute(ERRORS_MAP_KEY); 
      } 
     } 
    } 
} 
0

從您的問題中不清楚,但它聽起來像您的GET和POST操作映射到相同的處理程序。在這種情況下,你可以這樣做:

if ("POST".equalsIgnoreCase(request.getMethod())) { 
    // validate form 
    model.addAttribute(form); 
    return "redirect:/me.html"; 
} 
model.addAttribute(new MyForm()); 
return "/me.html"; 

在JSP檢查,如果需要有窗體上的任何錯誤和顯示。

+0

不,我打算對GET和POST使用不同的方法。我想我的問題一定不清楚。我會編輯它。 – 2011-03-24 20:42:47

0

這種方法被稱爲PRG(POST /重定向/ GET)設計模式,我解釋了它在幾天前的一個答案:

Spring MVC Simple Redirect Controller Example

希望它能幫助:)

+0

對不起,這不是我要找的。您的示例適用於標準表單提交。我正在查看顯示回用戶的無效表單。當用戶點擊刷新時,我不希望他們發佈,我希望他們獲得。 – 2011-03-24 20:41:03