Spring MVC - Liferay - 验证(使用 @valid 注释)

发布于 2024-10-25 18:03:07 字数 5592 浏览 5 评论 0原文

我正在尝试在带有 Spring MVC (和 Liferay 6)的控制器中使用“@Valid”注释。

我有“test-portlet.xml”:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-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="com.test.sample.sample.ipc.test" />
    <mvc:annotation-driven  />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/test/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Portlet.xml:

<portlet-app version="2.0"
    xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd
        http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd">
    <portlet>
        <portlet-name>test</portlet-name>
        <portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
        <init-param>
        <name>contextConfigLocation</name>
        <value>
            /WEB-INF/context/test-portlet.xml
        </value>
    </init-param>
        <supports>
            <mime-type>text/html</mime-type>
            <portlet-mode>view</portlet-mode>
        </supports>
        <portlet-info>
            <title>Test</title>
        </portlet-info>       

    </portlet>     
</portlet-app>

JavaBean.java(这是我的“表单”):

package com.test.sample.sample.ipc.test;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

public class JavaBean {

    private String testName;

    public void setTestName(String testName) {
        this.testName = testName;
    }

    @NotEmpty(message = "{err.test.notEmpty}")
    @NotNull(message = "{err.test.notNull}")
    @Max(message = "{err.test.max}", value = 10)
    @Min(value = 1, message = "{err.test.min}") 
    public String getTestName() {
        return testName;
    }   
}

和 TestController.java:

package com.test.sample.sample.ipc.test;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;

import com.test.auction.services.model.Test;
import com.test.auction.services.service.TestLocalServiceUtil;

@Controller
@RequestMapping("VIEW")
public class TestController {

    @RequestMapping
    public String doView(RenderRequest request, RenderResponse response) {          
        return "test";
    }

    @ActionMapping("addTest")
    public void addTestAction(@Valid JavaBean bean, BindingResult result, SessionStatus status, ActionRequest request, ActionResponse response) 
    {
        try {
            Test test = TestLocalServiceUtil.addTest(bean.getTestName());
            test.setName("test");
            request.setAttribute("testAttr", "OK");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("testAttr", "ERROR");
        }
        status.setComplete();       
    }

}

视图(test.jsp):

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="portlet" uri="http://java.sun.com/portlet" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>

<%@ page import="javax.portlet.PortletPreferences" %>

<portlet:defineObjects/>

<portlet:actionURL name="addTest" var="editURL"/>

<c:out value="${testAttr}" />

<aui:form action="<%= editURL %>" name="addTest" method="post">
    <aui:input label="Enter name of new Test Entity :" name="testName" type="text" value="" />
    <aui:button type="submit" />
</aui:form>

除了 JavaBean 对象的验证之外,一切都按预期工作。因此,当我在文本字段中输入内容时,JavaBean 对象将填充它的值。例如,如果我什么也不输入,则不会发生错误,也不会在“BindingResult”对象中看到错误。

我尝试将 @valid 注释直接放在 setter 方法或变量上,但我得到了相同的行为。

  • 我在 web-inf 下的“lib”文件夹中有库“hibernate-validator-annotation-processor-4.1.0.Final.jar”。

更新: @Min 和 @Max 注释应该用于整数,而不是像我一样的字符串!

I'm trying to use the "@Valid" annotations in a Controller with Spring MVC (and Liferay 6).

I have "test-portlet.xml" :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-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="com.test.sample.sample.ipc.test" />
    <mvc:annotation-driven  />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/test/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Portlet.xml :

<portlet-app version="2.0"
    xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd
        http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd">
    <portlet>
        <portlet-name>test</portlet-name>
        <portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
        <init-param>
        <name>contextConfigLocation</name>
        <value>
            /WEB-INF/context/test-portlet.xml
        </value>
    </init-param>
        <supports>
            <mime-type>text/html</mime-type>
            <portlet-mode>view</portlet-mode>
        </supports>
        <portlet-info>
            <title>Test</title>
        </portlet-info>       

    </portlet>     
</portlet-app>

JavaBean.java (it's my "form") :

package com.test.sample.sample.ipc.test;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

public class JavaBean {

    private String testName;

    public void setTestName(String testName) {
        this.testName = testName;
    }

    @NotEmpty(message = "{err.test.notEmpty}")
    @NotNull(message = "{err.test.notNull}")
    @Max(message = "{err.test.max}", value = 10)
    @Min(value = 1, message = "{err.test.min}") 
    public String getTestName() {
        return testName;
    }   
}

And TestController.java :

package com.test.sample.sample.ipc.test;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;

import com.test.auction.services.model.Test;
import com.test.auction.services.service.TestLocalServiceUtil;

@Controller
@RequestMapping("VIEW")
public class TestController {

    @RequestMapping
    public String doView(RenderRequest request, RenderResponse response) {          
        return "test";
    }

    @ActionMapping("addTest")
    public void addTestAction(@Valid JavaBean bean, BindingResult result, SessionStatus status, ActionRequest request, ActionResponse response) 
    {
        try {
            Test test = TestLocalServiceUtil.addTest(bean.getTestName());
            test.setName("test");
            request.setAttribute("testAttr", "OK");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("testAttr", "ERROR");
        }
        status.setComplete();       
    }

}

The view (test.jsp) :

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="portlet" uri="http://java.sun.com/portlet" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>

<%@ page import="javax.portlet.PortletPreferences" %>

<portlet:defineObjects/>

<portlet:actionURL name="addTest" var="editURL"/>

<c:out value="${testAttr}" />

<aui:form action="<%= editURL %>" name="addTest" method="post">
    <aui:input label="Enter name of new Test Entity :" name="testName" type="text" value="" />
    <aui:button type="submit" />
</aui:form>

Everything works as expected except for the validation of the JavaBean object. So, when I enter something in the text field, the JavaBean object is populated with it's value. If I enter nothing, for example, no error occurs or is visible in the "BindingResult" object.

I tried putting the @valid annotations at the setter method or at the variable directly, but I get the same behavior.

  • I have the library "hibernate-validator-annotation-processor-4.1.0.Final.jar" in the "lib" folder under web-inf.

UPDATE : The @Min and @Max annotations should be used on integers, not string like I did!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睫毛溺水了 2024-11-01 18:03:07

我让它与 heikkim 的答案一起工作
Spring portlet mvc:@Valid似乎不起作用

基本上,我将 test-portlet 中的 mvc:annotation-driven 行替换为:

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean id="configurableWebBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="validator">
                <ref bean="validator"/>
            </property>
        </bean>
    </property>
</bean>

I made it work with heikkim's answer at
Spring portlet mvc: @Valid does not seem to work

Basically, I replaced the mvc:annotation-driven line in test-portlet with :

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean id="configurableWebBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="validator">
                <ref bean="validator"/>
            </property>
        </bean>
    </property>
</bean>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文