如何在struts2中使用@Valid注释触发验证?

时间:2014-02-03 16:09:20

标签: java hibernate struts2 bean-validation struts2-jsr303-plugin

我无法在hibernate,struts2 webapp中使@javax.validation.Valid注释工作。

这是我的带有约束的简单实体:

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

    @Entity
    @Table(name = "user")
    public class User implements Serializable {

        @Id
        @GeneratedValue
        @Column(name = "user_id")
        private Long id;
        @NotEmpty
        @Length(max = 50, min = 3, message = "Name should be not less 3 and not more 50")
        @Column(name = "name", nullable = false)
        private String name;
        @Length(min = 6, max = 10)
        @Column(name = "password")
        private String password;
        @NotEmpty(message = "Please select a gender")
        @Column(name = "gender")
        private String gender;
        @NotEmpty(message = "Please select a country")
        @Column(name = "country")
        private String country;
        @Length(max = 100)
        @Column(name = "aboutYou")
        private String aboutYou;
        @Column(name = "mailinglist")
        private Boolean mailingList;

这是我使用@Valid注释的UserAction类:

public class UserAction extends ActionSupport implements ModelDriven<User> {

    @Valid
    private User user = new User();
    private UserDao dao = new UserDao();
    private List<User> users = new ArrayList<User>();

    public String addUser() {
        dao.addUser(user);
        users = dao.listUsers();
        return SUCCESS;
    }

    public List<User> getUsers() {
        return users;
    }

    public User getModel() {
        return user;
    }
}

这是我的jsp,它应该在hibernate约束失败时显示错误消息。

<h4>Add user:</h4>
    <s:actionerror/>
    <s:form action="addUser">
        <s:textfield key="name" />
        <s:password key="password" />
        <s:radio list="{'Male','Female'}" key="gender" />
        <s:select list="{'India','USA','Ukraine'}" headerKey=""
            headerValue="Select" key="country" />
        <s:textarea key="aboutYou" cols="20" rows="10" />
        <s:checkbox key="mailingList" value="true" />
        <s:submit value="Post" />
    </s:form>

当我提交空表单然后没有hibernate约束工作并且新用户被添加到数据库中,当然在jsp页面上没有显示错误。

你不知道出了什么问题吗?

修改即可。在尝试使用推荐的插件后,我得到了NullPointer,因为hibernate Session没有在@SesionTarget注释的帮助下注入。 这是我的struts.xml,它扩展了jsr303而不是hibernate-default。

<package name="default" extends="jsr303">
        <default-interceptor-ref name="jsr303ValidationStack"/>

        <action name="index" class="com.shb.action.UserAction" method="execute">
            <result name="success">/index.jsp</result>
            <result name="input">/index.jsp</result>
        </action>

        <action name="addUser" class="com.shb.action.UserAction" method="addUser">
            <result name="success">/index.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>

0 个答案:

没有答案