0

検証にバリデータークラスを使用した春の検証で問題に直面していますが、検証は適切に行われていますがint and date、フォームフィールドに文字列などの異なるタイプを指定するとexception、jspページに全体が貼り付けられます。適切なメッセージ形式を提供したいと思います。もう1つやりたいことこのバリデータークラスで正規表現を使用したいこのバリデータークラスで実装できるように、任意の例で正規表現のコードスニペットを提供してください

これは私のコントローラーです

    package com.nousinfo.tutorial.controllers;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.ServletRequestDataBinder;
    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.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    import com.nousinfo.tutorial.model.EmployeeForm;
    import com.nousinfo.tutorial.service.impl.EmployeeServiceImpl;
    import com.nousinfo.tutorial.service.impl.ProjectServiceImpl;
    import com.nousinfo.tutorial.service.model.EmployeeBO;
    import com.nousinfo.tutorial.validator.EmployeeValidator;

    /**
     * 
     * @author ankurj
     * 
     */
    @Controller
    @RequestMapping("employee")
    public class EmployeeController {

        private EmployeeServiceImpl employeeServiceImpl;
        private ProjectServiceImpl projectServiceImpl;
        private EmployeeValidator employeeValidator;

        public void setEmployeeServiceImpl(EmployeeServiceImpl employeeServiceImpl) {
            this.employeeServiceImpl = employeeServiceImpl;
        }

        /**
         * Set the view to Employee Form
         * 
         * @param model
         *            is the entity mapped to form object
         * @return view
         * @throws Exception
         */
        @RequestMapping(value = "/searchspring", method = RequestMethod.GET)
        public String view(Model model) throws Exception {
            EmployeeBO employeeBO = new EmployeeBO();
            model.addAttribute("employeeBO", employeeBO);
            return "EmployeeForm";
        }

        public void setEmployeeValidator(EmployeeValidator employeeValidator) {
            this.employeeValidator = employeeValidator;
        }

        /**
         * set the view to "AboutUS"
         * 
         * @return VIEW
         */
        @RequestMapping(value = "/aboutUs", method = RequestMethod.GET)
        public String aboutUsView() {
            return "AboutNous";
        }

        /**
         * This method is used to insert the detail of employee or simply create new
         * employee with detail
         * 
         * @param employeeForm
         *            is the model entity mapped to form object
         * @param bindingResult
         * @param model
         * @return
         * @throws Exception
         */
        @RequestMapping(value = "/createEmployee", method = RequestMethod.POST)
        public ModelAndView createEmployee(
                @ModelAttribute("employeeBO") EmployeeBO employeeBO,
                BindingResult bindingResult) throws Exception {
            ModelAndView model = new ModelAndView();
            employeeValidator.validate(employeeBO, bindingResult);
            System.out.println(bindingResult);
            System.out.println(employeeBO.getEmployeeNumber());
            if (bindingResult.hasErrors()) {
                model.setViewName("EmployeeForm");
                return model;
            }
            model.addObject("employeeBO", employeeBO);

            if (employeeBO.getUpdateStatus() == 'A') {
                boolean flag = employeeServiceImpl.actionDecider(employeeBO);
                if (flag == false) {
                    model.setViewName("DBError");

                } else
                    model.setViewName("Success");
            }

            return model;
        }
}

これは私のバリデータークラスです

package com.nousinfo.tutorial.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.nousinfo.tutorial.service.model.EmployeeBO;

public class EmployeeValidator implements Validator {

    public boolean supports(Class<?> arg0) {
        return EmployeeBO.class.isAssignableFrom(arg0);
    }

    public void validate(Object object, Errors errors) {
        boolean found = false;
        Pattern pattern = Pattern.compile("[0-9]");

        ValidationUtils.rejectIfEmpty(errors, "firstName",
                "employeeBO.firstName");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title",
                "employeeBO.title");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city",
                "employeeBO.city");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "state",
                "employeeBO.state");

        EmployeeBO employeeBO = (EmployeeBO) object;

        if (pattern.matcher(employeeBO.getFirstName()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("firstName", "employeeregex.string");
        }

        if (pattern.matcher(employeeBO.getLastName()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("lastName", "employeeregex.string");
        }

        if (pattern.matcher(employeeBO.getCity()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("city", "employeeregex.string");
        }
        if (pattern.matcher(employeeBO.getState()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("state", "employeeregex.string");
        }
        if (employeeBO.getEmployeeNumber() == null) {

            errors.rejectValue("employeeNumber", "employeeBO.employeeNumber");

        }
        if (employeeBO.getPincode() == null) {
            errors.rejectValue("pincode", "employeeBO.pincode");

        }

        if (employeeBO.getTelephoneNumber() == null) {
            errors.rejectValue("telephoneNumber", "employeeBO.telephoneNumber");

        }
        if (employeeBO.getMobileNumber() == null)
            errors.rejectValue("mobileNumber", "employeeBO.mobileNumber");

    }

}

これは私のjspであり、これによって入力を提供します

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/taglibs/input-1.0"
    prefix="input"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!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>Create Employee</title>
<script>
    function home() {
        window.location.href = "/EmployeeWebSpring/search/searchspring";

    }
</script>
</head>

<body background="../images/flower.jpg">

    <table width="1254" height="74" border="0" align="center">

        <tr>

            <td width="20" height="68" align="center" bgcolor="#FFFFFF"><img
                src="../images/Header.png" width="1300" height="92" /></td>
        </tr>
    </table>
    <p>
        <br />
    </p>
    <hr size="1" width="1254">
    <h1 align="center">
        <font color="FFA54F">Employee Form</font>
    </h1>
    <form:form id="form" method="post"
        action="/EmployeeWebSpring/employee/createEmployee"
        commandName="employeeBO">
        <table align="center" class="table">
            <tr>
                <form:hidden path="updateStatus" value="A" />
            </tr>
            <tr>
                <td>EmployeeNumber:</td>


                <td><form:input path="employeeNumber" /><font color="red"><form:errors
                            path="employeeNumber" /></font></td>
            </tr>
            <tr>
                <td>First_Name:</td>

                <td><form:input path="firstName" /><font color="red"><form:errors
                            path="firstName" /></font></td>
            </tr>

            <tr>
                <td>Last_Name:</td>

                <td><form:input path="lastName" /><font color="red"><form:errors
                            path="lastName" /></font></td>
            </tr>
            <tr>
                <td>Title:</td>

                <td><form:input path="title" /><font color="red"><form:errors
                            path="title" /></font></td>
            </tr>
            <tr>
                <td>Department_Id:</td>

                <td><form:input path="departmentId" /></td>
            </tr>
            <tr>
                <td>Address1:</td>

                <td><form:input path="address1" /></td>
            </tr>
            <tr>
                <td>Address2:</td>

                <td><form:input path="address2" /></td>
            </tr>
            <tr>
                <td>City:</td>

                <td><form:input path="city" /><font color="red"><form:errors
                            path="city" /></font></td>
            </tr>

            <tr>
                <td>State:</td>

                <td><form:input path="state" /><font color="red"><form:errors
                            path="state" /></font></td>
            </tr>
            <tr>

                <td>Pincode:</td>

                <td><form:input path="pincode" /><font color="red"><form:errors
                            path="pincode" /></font></td>
            </tr>
            <tr>
                <td>Telephone_Number:</td>

                <td><form:input path="telephoneNumber" /><font color="red"><form:errors
                            path="telephoneNumber" /></font></td>
            </tr>

            <tr>
                <td>Mobile_Number:</td>

                <td><form:input path="mobileNumber" /><font color="red"><form:errors
                            path="mobileNumber" /></font></td>
            </tr>
            <tr>
                <td>Date_Of_Birth:</td>

                <td><form:input path="dateOfBirth" /><font color="red"><form:errors
                            path="dateOfBirth" /></font></td>
            </tr>
            <tr>
                <td>Date_Of_Anniversary:</td>

                <td><form:input path="dateOfAnniversary" /><font color="red"><form:errors
                            path="dateOfAnniversary" /></font></td>
            </tr>

            <tr>
                <td>Date_Of_Joining:</td>

                <td><form:input path="dateOfJoining" /><font color="red"><form:errors
                            path="dateOfJoining" /></font></td>
            </tr>
            <tr>
                <td>Date_Of_Leaving:</td>

                <td><form:input path="dateOfLeaving" /><font color="red"><form:errors
                            path="dateOfLeaving" /></font></td>
            </tr>
            <tr>
                <td>Reason_For_Leaving:</td>

                <td><form:input path="reasonForLeaving" /></td>
            </tr>
        </table>

        <br>
        <br />
        <p>&nbsp;</p>
        <br>

        <table align="center">
            <tr>
                <td><input type="submit" name="method" value="Save" /></td>
                <td><input type="button" value="Cancel" onclick="home()" /></td>
            </tr>
        </table>
        <hr size="1" width="786">
        <p>&nbsp;</p>
    </form:form>
</body>
</html>

ここに画像の説明を入力してください

ここに画像の説明を入力してください

4

1 に答える 1

0

問題は、コントローラーのコンバーターを初期化しなかったことが原因だと思います。

最初に追加する必要があるのInitBinderは、コントローラー内です。

@InitBinder public void initBinder(WebDataBinder binder) {
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");  //Select the format you want
 dateFormat.setLenient(false); 
 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

何をしたいかに応じて、異なるCustomEditorが必要になります。

 binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); //Trim strings
 binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); //to handle file upload

EmployeeBO使用するタイプに応じて、次の注釈を追加することもできます。

@Temporal(TemporalType.TIMESTAMP) 
@DateTimeFormat(style = "S-")  //format: 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-'.
private Date dateOfBirth;

@NumberFormat(style=Style.NUMBER)
private Long employeeNumberamount;
于 2013-01-28T10:26:51.093 に答える