【问题标题】:handling Ajax Call in Spring MVC在 Spring MVC 中处理 Ajax 调用
【发布时间】:2018-08-20 11:18:35
【问题描述】:

是的,我知道这是一个愚蠢的问题,但我在过去 3 小时内一直在努力解决这个问题。如果bindingResult.hasErrors() 解析为true,我想从我的控制器返回ModelAndView,否则我希望我的方法返回对ajax 调用的响应。我知道如果我希望我的控制器生成响应,我需要用 @ResponseBody 注释我的方法,但我不明白 如何让我的方法返回一个 ModelAndView 对象(当验证失败时)或一个带注释的字符串与@ResponseBody(在一切顺利时的其他部分)。有人可以指导我吗?

这是我的控制器方法。

@PostMapping("/problem/submit")
    public ModelAndView getProblemDetails(@Valid @ModelAttribute("problem") Problem problem,
                                        BindingResult bindingResult,ModelAndView modelAndView,Model model){
        modelAndView.setViewName("home");
        if(bindingResult.hasErrors()){
            return modelAndView;
        }
        else{
            //return response for ajax call where my method return type should be String and it should be annotated with @ResponseBody
        }
    }

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    正如外星人建议的那样,给你:-

    @PostMapping("/problem/submit")
    public void getProblemDetails(@Valid @ModelAttribute("problem") Problem problem,BindingResult bindingResult,HttpServletResponse response){
        try {
            JSONObject resultJson = new JSONObject();
            resultJson.put("beanValidationFailed", false);
            if(bindingResult.hasErrors()){
                resultJson.put("beanValidationFailed", true);
                //private function to get bindingResult erros as key/value Pair
                resultJson = getFieldErrors(bindingResult,resultJson); 
            }else{
                //here retrunJson object is case of no errors
            }
            //This will bind this json directly to your AJAX response
            //You can use this json object to show error( in case of bindingResult erros as well send other data if there are no error) 
            response.getWriter().write(resultJson.toString());
        }
        catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    private JSONObject getFieldErrors(BindingResult bindingResult, JSONObject resultJson){
        try {
           List<FieldError> fieldErrors = bindingResult.getFieldErrors();
           for ( FieldError error: fieldErrors) {
              resultJson.put(error.getField(),error.getDefaultMessage());
           } 
        }catch (JSONException e) {
            e.printStackTrace();
        }
        return resultJson;
    }
    

    【讨论】:

      【解决方案2】:

      简而言之,您不能这样做。

      您可以使用javascript/jquery 验证。如果一切都验证成功,那么您提交表单,否则不会。

      如果控制器没有返回绑定错误,则将逻辑写入您的视图页面。

      http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-28
        • 2012-08-02
        • 1970-01-01
        • 2011-01-02
        • 1970-01-01
        • 1970-01-01
        • 2012-10-23
        • 1970-01-01
        相关资源
        最近更新 更多