Errors/BindingResult argument is expected

2019-08-05 07:30发布

问题:

I am learning Spring MVC and I am trying to validate the form. When user search for blank string it will show error. I get following error when I execute my code

An Errors/BindingResult argument is expected to be immediately after the model attribute argument in the controller method signature: public java.lang.String com.mycompany.controller.catalog.SearchController.search(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,java.lang.String,org.springframework.validation.BindingResult,org.springframework.ui.Model) throws javax.servlet.ServletException,java.io.IOException,org.broadleafcommerce.common.exception.ServiceException

package com.mycompany.controller.catalog;

import org.broadleafcommerce.common.exception.ServiceException;

import org.broadleafcommerce.core.web.controller.catalog.Mysearchcontroller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import  org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@Controller
@RequestMapping("/search")
public class SearchController extends Mysearchcontroller {


    @RequestMapping("")
    public String search(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "q") String q,BindingResult errors,Model model) throws ServletException, IOException, ServiceException {
        return search3(model, request,response, q ,errors);
    }

}

回答1:

The BindingResult argument can only be used in conjuction with a @ModelAttribute annotated method. Without a model attribute there is going to be no binding and as such no BindingResult instance is going to be available. So in your case you have to remove the BindingResult argument, as it will never work in your case, due to the lack of a model attribute.

A model attribute is NOT the same as the Model (as was hinted on). The model attribute is part of the Model.



回答2:

If q is optional the modify @RequestParam(value = "q") String q to (@RequestParam(required = false) String q

 @RequestMapping("")
 public String search(HttpServletRequest request, HttpServletResponse response,
        (@RequestParam(required = false) String q,BindingResult errors,Model model) throws ServletException, IOException, ServiceException {
        return search3(model, request,response, q ,errors);
 }