具有ModelAndView的Spring MVC验证 [英] Spring MVC Validation w/ ModelAndView

查看:84
本文介绍了具有ModelAndView的Spring MVC验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的Spring MVC应用程序添加验证。以前尝试设置验证我一直在使用ModelAndView来提供jsp页面,但不会显示错误消息。

I am trying to add validation to my Spring MVC Application. Previously to attempting to set up validation I have been using ModelAndView to serve up the jsp pages but the error messages do not display.

Model

@Entity
@Table(name = "employee")
public class Employee {


@Id
@NotEmpty(message = "Please enter your email addresss.")
@Email
private String email;

@NotEmpty
@Pattern(regexp="[a-zA-Z0-9]")
private String password;

@NotEmpty
private String firstName;

@NotEmpty
private String lastName;

@NotEmpty
private String phoneNum;


private boolean assigned;

public Employee() {

}

// getters and setters
}

控制器

@RestController
@RequestMapping("/employee")
public class EmployeeController {

private static final Logger LOGGER = LogManager
        .getLogger(EmployeeController.class.getName());

@Autowired
private EmployeeServiceImpl employeeService;

@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getRegisterView(Model m) {
    return new ModelAndView("addEmployee", "employeeForm", new Employee());
}

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView postUser(@Valid Employee employee, BindingResult result) {
    ModelAndView model;
    if (result.hasErrors()) {
        model = new ModelAndView("addEmployee", "employeeForm", employee);
    } else {
        employeeService.addEmployee(employee);
        model = new ModelAndView();
        model.setViewName("displayEmployee");
        model.addObject("employees", employeeService.getEmployees());
    }

    return model;
}
}

表格

<form:form class="form-horizontal" role="form" method="POST"
        action="register" commandName="employeeForm" modelattribute="employee">
        <div class="form-group">
            <form:label path="firstName"
                class="control-label col-lg-2 col-lg-offset-2 col-md-2 col-md-offset-2 col-sm-12"
                for="fname">First Name:</form:label>
            <div class="col-lg-6 col-md-6 col-sm-12">
                <form:input path="firstName" class="form-control" id="fname"
                    placeholder="First Name" />
                <form:errors path="firstName" />
            </div>
        </div>
        <div class="form-group">
            <form:label path="lastName"
                class="control-label col-lg-2 col-lg-offset-2 col-md-2 col-md-offset-2 col-sm-12"
                for="lname">Last Name:</form:label>
            <div class="col-lg-6 col-md-6 col-sm-12">
                <form:input path="lastName" class="form-control" id="lname"
                    placeholder="Last Name" />
                <form:errors path="lastName" />
            </div>
        </div>
        <div class="form-group">
            <form:label path="email"
                class="control-label col-lg-2 col-lg-offset-2 col-md-2 col-md-offset-2 col-sm-12"
                for="email">Email:</form:label>
            <div class="col-lg-6 col-md-6 col-sm-12">
                <form:input path="email" type="email" class="form-control"
                    id="email" placeholder="Email" />
                <form:errors path="email" cssClass="error" />
            </div>
        </div>
        <div class="form-group">
            <form:label path="phoneNum"
                class="control-label col-lg-2 col-lg-offset-2 col-md-2 col-md-offset-2 col-sm-12"
                for="phoneNum">Phone Number:</form:label>
            <div class="col-lg-6 col-md-6 col-sm-12">
                <form:input path="phoneNum" class="form-control" id="phoneNum"
                    placeholder="Phone Number" />
                <form:errors path="phoneNum" />
            </div>
        </div>
        <div class="form-group">
            <form:label path="password"
                class="control-label col-lg-2 col-lg-offset-2 col-md-2 col-md-offset-2 col-sm-12"
                for="pwd">Password:</form:label>
            <div class="col-lg-6 col-md-6 col-sm-12 controls">
                <form:input path="password" type="password" class="form-control"
                    id="pwd" placeholder="Password" />
                <form:errors path="password" />
            </div>
        </div>
        <div class="form-group form-actions">
            <div
                class="col-lg-offset-4 col-lg-1 col-md-offset-4 col-md-1 col-sm-1">
                <button type="submit" class="btn btn-primary">Register</button>
            </div>
            <div class="col-lg-1 col-md-1 col-sm-1">
                <button type="reset" class="btn btn-primary">Clear</button>
            </div>
        </div>
        <form:hidden path="assigned" value="false" />
    </form:form>


推荐答案

model = new ModelAndView("addEmployee", "employeeForm", employee);

您在代码中自行销毁模型,因此返回页面时基本上没有剩下任何内容。返回 ModelAndView 时,Spring MVC假设您已准备好并添加了自己渲染视图所需的所有内容。

You are destroying the model yourself in your code, so when returning to the page there is basically nothing left. When returning a ModelAndView Spring MVC assumes that you have prepared and added everything needed for rendering the view yourself.

@ModelAttribute(employeeForm)添加到 @Valid 注释旁边的方法参数中,并使用已存在的模型从 BindingResult 构建一个 ModelAndView

Instead add @ModelAttribute("employeeForm") to your method argument next to the @Valid annotation and use the already existing model from the BindingResult to construct a ModelAndView.

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView postUser(@Valid @ModelAttribute("employeeForm" Employee employee, BindingResult result) {
    ModelAndView model;
    if (result.hasErrors()) {
        model = new ModelAndView("addEmployee", result.getModel());

虽然这样可行但为什么不简单地返回 String 作为视图的名称,并在需要时做一些模型准备。

Although this will work why not simply return a String as the name of the view and do some Model preparation when needed.

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String postUser(@Valid @ModelAttribute("employeeForm") Employee employee, BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "addEmployee";
    } else {
        employeeService.addEmployee(employee);
        model.addObject("employees", employeeService.getEmployees());
        return "displayEmployee";
    }
}

我甚至认为填写 displayEmployee 页面的模型不属于此处,而是在为该页面准备模型的单独方法中。

I would even argue that filling the Model for the displayEmployee page doesn't belong here but in a separate method preparing the model for that page.

这篇关于具有ModelAndView的Spring MVC验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆