我可以在Spring MVC中向Model添加任何对象吗?

时间:2014-11-11 03:06:39

标签: spring spring-mvc

我想在Spring MVC Controller中添加一个bean来建模。但是,抛出了验证器异常:

  

非法国家例外。

有人可以指导我提交表格并显示表格提交后我得到的内容吗?在这种情况下,我需要使用bean来显示我在视图中的所有信息。

像:

model.addAttribute("simple", new Student());

但是,我一直在从验证器获取IllegaStateException。

下载:

https://sites.google.com/site/jimjicky/SpringFormValidation.rar?attredirects=0&d=1

控制器:

@Controller
public class EmployeeController {

    private static final Logger logger = LoggerFactory
            .getLogger(EmployeeController.class);

    private Map<Integer, Employee> emps = null;

    @Autowired
    @Qualifier("employeeValidator")
    private Validator validator;

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    public EmployeeController() {
        emps = new HashMap<Integer, Employee>();
    }

    @ModelAttribute("employee")
    public Employee createEmployeeModel() {
        // ModelAttribute value should be same as used in the empSave.jsp
        return new Employee();
    }

    @ModelAttribute("student")
    public Student createStudentModel() {
        // ModelAttribute value should be same as used in the empSave.jsp
        return new Student();
    }

    @RequestMapping(value = "/emp/save", method = RequestMethod.GET)
    public String saveEmployeePage(Model model) {
        logger.info("Returning empSave.jsp page");
        return "empSave";
    }

    @RequestMapping(value = "/emp/save.do", method = RequestMethod.POST)
    public String saveEmployeeAction(
            @ModelAttribute("employee") @Validated Employee employee,@ModelAttribute("student")Student student,
            BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            logger.info("Returning empSave.jsp page");
            return "empSave";
        }
        logger.info("Returning empSaveSuccess.jsp page");
        model.addAttribute("emp", employee);
        model.addAttribute("student", createStudentModel());
        emps.put(employee.getId(), employee);
        return "empSaveSuccess";
    }
}

验证

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.journaldev.spring.form.model.Employee;

public class EmployeeFormValidator implements Validator {

    //which objects can be validated by this validator
    @Override
    public boolean supports(Class<?> paramClass) {
        return Employee.class.equals(paramClass);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required");

        Employee emp = (Employee) obj;
        if(emp.getId() <=0){
            errors.rejectValue("id", "negativeValue", new Object[]{"'id'"}, "id can't be negative");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.required");
    }
}

堆栈跟踪

java.lang.IllegalStateException: Invalid target for Validator [com.journaldev.spring.form.validator.EmployeeFormValidator@1625cd8]: com.journaldev.spring.form.model.Student@bd8550
    org.springframework.validation.DataBinder.assertValidators(DataBinder.java:495)
    org.springframework.validation.DataBinder.setValidator(DataBinder.java:486)
    com.journaldev.spring.form.controllers.EmployeeController.initBinder(EmployeeController.java:38)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.method.annotation.InitBinderDataBinderFactory.initBinder(InitBinderDataBinderFactory.java:62)
    org.springframework.web.bind.support.DefaultDataBinderFactory.createBinder(DefaultDataBinderFactory.java:53)
    org.springframework.web.method.annotation.ModelFactory.updateBindingResult(ModelFactory.java:222)
    org.springframework.web.method.annotation.ModelFactory.updateModel(ModelFactory.java:206)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.getModelAndView(RequestMappingHandlerAdapter.java:852)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:755)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

1 个答案:

答案 0 :(得分:0)

根据提供的信息,尝试将InitBinder更改为以下内容:

@InitBinder("employee")
private void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}

这可行的原因是由于提供的值,在这种情况下,值为“employee”。

public abstract String[] value

    The names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to. 

在您的表单中,您有多个对象,而没有建议@InitBinder验证它的哪个对象也试图验证您的Student对象,因此失败,因为它不符合类要求。

通过指定“employee”,它基本上确保它只对Employee对象应用了验证。