验证弹簧服务层

时间:2013-12-11 09:44:31

标签: java spring jsp validation service

我有一个表单,我通过实现Spring Validator接口进行验证。 验证仅涉及表单中的字段。我没有这个问题,但我想做的事情我不知道如何继续是在我的控制器中调用一个服务方法,如果这个方法返回一个特定的值,返回到表单页面并显示jsp页面中的错误消息。

验证

public class TrunkValidator implements Validator{

@Override
public boolean supports(Class<?> clazz) {
    return Trunk.class.equals(clazz);
}

public void validate(Object obj, Errors errors) {
    Trunk trunk = (Trunk) obj;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "compagnyName", "field.required", "Nom emtreprise est obligatoire");

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "pbxName", "field.required", "Nom Pbx est obligatoire");


    if ( ! errors.hasFieldErrors("compagnyName")) {
        if ("trunk".equals(trunk.getCompagnyName()))
            errors.rejectValue("compagnyName", "sssss", "déja existant");
    }       
    }
}

控制器:

@RequestMapping(value = "/createTrunk", method = RequestMethod.POST)
    protected ModelAndView createTrunk(@Valid Trunk trunk,
            BindingResult bindingResult) {
                // form validation
        if (bindingResult.hasErrors()) {
            ModelAndView model = new ModelAndView("/jsp/createTrunk.jsp");
            model.addObject(ATTRIBUTE_BASE_URL, baseUrl);
            return model;
        } else {

                   //  if service method retun error message or exception
                   // display form with error message 

        }
    }

JSP:

<form:form method="POST" commandName="trunk" action="${baseUrl}/createTrunk">
    <form:errors path="*" cssClass="errorblock" element="div" />
    <table>
        <tr>
            <td>Nom de l'entreprise :</td>
            <td><form:input path="compagnyName" /></td>
            <td><form:errors path="compagnyName" cssClass="error" /></td>
        </tr>
        <tr>
            <td>Nom de PBX :</td>
            <td><form:input path="pbxName" /></td>
            <td><form:errors path="pbxName" cssClass="error" /></td>
        </tr>

        <tr>
            <td>N° de commande :</td>
            <td><form:input path="orderNum" /></td>
            <td><form:errors path="orderNum" cssClass="error" /></td>
        </tr>



        <tr>
            <td>LDI :</td>
            <td><form:input path="ldi" /></td>
            <td><form:errors path="ldi" cssClass="error" /></td>
        </tr>

        <tr>
            <td>INSEE :</td>
            <td><form:input path="insee" /></td>
            <td><form:errors path="insee" cssClass="error" /></td>
        </tr>

2 个答案:

答案 0 :(得分:0)

在控制器中添加@InitBinder

@InitBinder("trunk")
public void initBinderAll(WebDataBinder binder) {
        binder.setValidator(new TrunkValidator());
}

答案 1 :(得分:0)

使用spring的注释和@Autowired功能:

像这样设置你的servlet.xml ......

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="sk.eglu.khl" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:resources mapping="/resources/**" location="/resources/mytheme/" />

<mvc:annotation-driven />

...然后你可以使用注释 - 所以创建“TrunkValidator”的界面并添加到你的服务层注释中:

public interface TrunkValidatorInt {

    boolean validate(Object obj, Errors errors);

}

@Service
public class TrunkValidatorImpl implements TrunkValidatorInt {

    @Override
    boolean validate(Object obj, Errors errors){
         return true;
    }

}

@Controller
@RequestMapping("/welcome")
public class HelloWorldController{

        @Autowired(required = true)
        TrunkValidatorInt trunkValidator;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView helloWorld(){

    final ModelAndView model = new ModelAndView("HelloWorldPage");

            if(trunkValidator.validate(someValue)){
        model.addObject("msg", "good!");
            } else {
        model.addObject("msg", "bad!");
            }
    return model;
    }
}

另外,您可以查看这个Java的起始项目,您可以在其中看到层的通信方式:

https://github.com/majusko/GeneralJavaRest