Preserving model state with Post/Redirect/Get pattern

前端 未结 3 1592
名媛妹妹
名媛妹妹 2021-02-15 16:08

At the moment I am trying to implement the Post/Redirect/Get pattern with Spring MVC 3.1. What is the correct way to preserve and recover the model data + validation errors? I k

3条回答
  •  -上瘾入骨i
    2021-02-15 16:48

    public class BindingHandlerInterceptor extends HandlerInterceptorAdapter {
    
        public static final String BINDING_RESULT_FLUSH_ATTRIBUTE_KEY = BindingHandlerInterceptor.class.getName() + ".flashBindingResult";
    
        private static final String METHOD_GET = "GET";
        private static final String METHOD_POST = "POST";
    
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    
            if(METHOD_POST.equals(request.getMethod())) {
    
                BindingResult bindingResult = getBindingResult(modelAndView);
    
                FlashMap outFlash = RequestContextUtils.getOutputFlashMap(request);
    
                if(bindingResult == null || ! bindingResult.hasErrors() || outFlash == null ) {
                    return;
                }
    
                outFlash.put(BINDING_RESULT_FLUSH_ATTRIBUTE_KEY, bindingResult);
    
            }
    
            Map inFlash = RequestContextUtils.getInputFlashMap(request);
    
            if(METHOD_GET.equals(request.getMethod()) && inFlash != null && inFlash.containsKey(BINDING_RESULT_FLUSH_ATTRIBUTE_KEY)) {
    
                BindingResult flashBindingResult = (BindingResult)inFlash.get(BINDING_RESULT_FLUSH_ATTRIBUTE_KEY);
    
                if(flashBindingResult != null) {
    
                    BindingResult bindingResult = getBindingResult(modelAndView);
    
                    if(bindingResult == null) {
                        return;
                    }
    
                    bindingResult.addAllErrors(flashBindingResult);
    
                }
    
            }
    
        }
    
        public static BindingResult getBindingResult(ModelAndView modelAndView) {
    
            if(modelAndView == null) {
                return null;
            }
    
            for (Entry key : modelAndView.getModel().entrySet()) {
                if(key.getKey().startsWith(BindingResult.MODEL_KEY_PREFIX)) {
                    return (BindingResult)key.getValue();
                }
            }
    
            return null;
        }
    
    
    }
    

提交回复
热议问题