带有验证的休眠编辑表单

时间:2016-08-17 13:17:04

标签: spring-mvc hibernate-validator

我准备了一个在spring(MVC)中执行CRUD操作的应用程序

使用Hibernate Validator。

我已成功在“添加”页面上应用验证,我也能够

在更新页面上应用它们

错误:由于

,更新JSP页面上的表单确实已提交

验证但验证消息未显示在视图上 updatePerson.jsp

下面是我的代码:

//////////////////////////////控制器//////////////// ////////////

package com.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;




import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.model.Person;
import com.service.PersonService;

@Controller
public class MainController {

    @Autowired
    private PersonService ps;

    @RequestMapping("/")
    public ModelAndView listPersons(ModelAndView model) throws IOException {
        List<Person> listper = ps.list();
        model.addObject("personsList", listper);
        model.setViewName("index");
        return model;

    }

    @RequestMapping(value = "/newPerson", method = RequestMethod.GET)
    public ModelAndView newPerson(ModelAndView model) throws IOException {
        @SuppressWarnings("unused")
        Person p = new Person();
        model.addObject("person", new Person());
        model.setViewName("AddPerson");

        return new ModelAndView("AddPerson", "person", new Person());

    }

    @RequestMapping(value="/save")
    public String save(@ModelAttribute @Valid Person p, BindingResult result) {

        if(result.hasErrors())
        {

            return "AddPerson";
        }
        else
        {       
        ps.save(p);

        return "redirect:http://localhost:8080/MainAssignment3/";

        }
    }


    @RequestMapping("/removePerson")
    public String remove(HttpServletRequest req) {
        int id = Integer.parseInt(req.getParameter("id"));
        ps.removePerson(id);
        return "redirect:http://localhost:8080/MainAssignment3/";

    }

    @RequestMapping("/update")
    public String update(@ModelAttribute @Valid Person p1,BindingResult result,Model p) {
        System.out.println(p1.getName());
        int id=p1.getId();
        // ps.getPersonById(p.getId());

        if(result.hasErrors())
        {
            p.addAttribute("p1", p1);
            p.addAttribute("id", id);
            p.addAttribute("name", p1.getName());
            p.addAttribute("gender", p1.getGender());
            p.addAttribute("address", p1.getAddress());
            p.addAttribute("salary", p1.getSalary());
            return "redirect:http://localhost:8080/MainAssignment3/updatePerson";
        }
        else{           

        ps.save(p1);

        return "redirect:http://localhost:8080/MainAssignment3/";

    }}

    @RequestMapping("/updatePerson")
    public ModelAndView updatePerson(HttpServletRequest req, ModelMap p1,Model  p) {
        p1.addAttribute("p1",new Person());
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        String address = req.getParameter("address");
        String gender = req.getParameter("gender");
        String salary = req.getParameter("salary");

        p1.addAttribute("id", id);
        p1.addAttribute("name", name);
        p1.addAttribute("gender", gender);
        p1.addAttribute("address", address);
        p1.addAttribute("salary", salary);
        p1.addAttribute("p1",new Person());
        return new ModelAndView("updatePerson", "person", p1);

    }

}

//////////////////////////// MODEL ////////////////// /////////////

package com.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;


import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;


@Entity
public class Person {

    @Id     
    @GeneratedValue(strategy=GenerationType.AUTO)   
    private Integer id;
    @Valid @NotNull(message="(Please enter a value)") @Column(nullable = false)@Size(min = 6, max = 15)
    private String name;
    @Min(value=5, message="(Must be greater than 5 characters)")//@NotNull(message="(Please enter a value)") @Column(nullable = false)
    private String address;
    @Valid @NumberFormat(style=Style.CURRENCY) @NotNull(message="(Please enter a value)") @Column(nullable = false)
    private Integer salary;
    @Max(value=5, message="(Must not be greater than 6 characters)")
    private String gender;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getSalary() {
        return salary;
    }
    public void setSalary(Integer salary) {
        this.salary = salary;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }




}

////////////////////////////验证属性///////////////// ////

NotNull.p.salary=invalid
NotNull.p.name=invalid

Size.p.name=Name must be between {6} and {15} characters long
Max.p.gender=Must not be more than {6} characters
Min.p.address=Must be greater than {5} characters


////////////////////////////////index.jsp//////////////////////

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
 <%@ taglib uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>


<html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head> 
    <body>
    <h2>Hello World!</h2>

<h3><a href="/MainAssignment3/newPerson">Add Person</a></h3>
    <table border="1">
<tr>
    <th>id</th>
    <td>name<springForm:errors path='${p.name}' /></td> 
    <td>address<springForm:errors path='${p.address}' /></td>   
    <td>gender<springForm:errors path='${p.gender}' /></td> 
    <td>salary<springForm:errors path='${p.salary}' /></td> 
</tr>   
 <c:forEach var="p" items='${personsList}' varStatus="status">
    <tr>

        <td>${p.id}</td>
        <td>${p.name}</td>
        <td>${p.address}</td>
        <td>${p.gender}</td>
        <td>${p.salary}</td>
        <td>
        <a href="/MainAssignment3/updatePerson?id=${p.id}&name=${p.name}&address=${p.address}&gender=${p.gender}&salary=${p.salary}">Edit</a>
            <a href="/MainAssignment3/removePerson?id=${p.id}">Delete</a>
        </td>

    </tr>

</c:forEach> 


</table>

    </body>
</html>

///////////////////////// AddPerson.jsp /////////////////// //////////

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Employee Here</title>
</head>
<body>
<h1>Employee Registration Form</h1>


    <springForm:form action="/MainAssignment3/save" method="POST"
        commandName="person">

        <table style="border: thin; border: ridge;">

            <tr>
                <td>Enter Name:</td>
                <td bordercolor="#FF0000" ><springForm:input path="name" id="name"
                        placeholder="Enter Name" /></td>

                <td><springForm:errors path="name" /></td>

            </tr>
            <tr>
                <td>Enter address:</td>
                <td><input type="text" name="address" placeholder="Enter Address" ></td>
                <td><springForm:errors path="address" /></td>
            </tr>
            <tr>
                <td>Enter gender:</td>
                <td><springForm:input path="gender" id="gender" placeholder="Enter Gender" /></td>
                <td><springForm:errors path="gender" /></td>
            </tr>
            <tr>
                <td>Enter salary:</td>
                <td><input type="text" name="salary" placeholder="Enter Salary" ></td>
                <td><springForm:errors path="salary" /></td>            
                <td style="padding-left: 110px;"></td>

            </tr>
            <tr>
            <td><input type="submit"value="submit"></td>
            </tr>

        </table>
    </springForm:form>
</body>
</html>

//////////////////////////////////// updatePerson.jsp //////// //////////////

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Employee</title>
</head>
<body>



    <springForm:form action="/MainAssignment3/update" method="POST" commandName="p1">

        <table style="border: thin; border: ridge;">        
        <tr>
            <td><input type="hidden" name="id" value="${id}"></td>
            </tr>
            <tr>
                <td>Enter Name:</td>
                <td bordercolor="#FF0000" ><springForm:input path="name" value='${name}'
                        placeholder="Enter Name" /></td>

                <td><springForm:errors path='${p1.name}'/></td>

            </tr>
            <tr>
                <td>Enter address:</td>
                <td><springForm:input path="address" id="address"  placeholder="Enter Address" value='${address}'/></td>
                <td><springForm:errors path='${p1.address}'/></td>
            </tr>
            <tr>
                <td>Enter gender:</td>
                <td><springForm:input path="gender" id="gender"  placeholder="Enter Gender" value='${gender}'/></td>
                <td><springForm:errors path='${p1.gender}'/></td>
            </tr>
            <tr>
                <td>Enter salary:</td>
                <td><springForm:input path="salary" id="salary"  placeholder="Enter Salary" value='${salary}'/></td>
                <td><springForm:errors path='${p1.salary}' /></td>          
                <td style="padding-left: 110px;"></td>

            </tr>
            <tr>
            <td><input type="submit"value="submit"></td>
            </tr>

        </table>
    </springForm:form>

</body>
</html>

//////////////////////////////的pom.xml ////////////// //////

<dependencies>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> 
            <version>4.3.2.RELEASE</version> </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.4.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.3</version>
        </dependency>
        <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> 
            <version>1.1</version> </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <!-- Other Web dependencies -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>


        <!-- Test Artifacts -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

1 个答案:

答案 0 :(得分:0)

您应该以与添加页面相同的方式使用错误。您只需要使用p1内的路径进行访问。

而不是<springForm:errors path='${p1.name}'/>您应该使用<springForm:errors path='name'/>

添加页面做同样的事情