How to implement validations using annotations in

2019-05-20 06:36发布

问题:

I am trying to implement validation using annotations, but these validations don't work and the form gets submitted with null values. I don't know what is missing, how to implement validations using annotations in struts2 in action that implements ModelDriven interface? This is my struts.xml

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="saveOrUpdateUser" method="saveOrUpdate1" class="com.vaannila.web.Userqqqq">
            <result name="success" type="redirect">listUser</result>
            <result name="input">/register.jsp</result>
        </action>
        <action name="listUser" method="list" class="com.vaannila.web.Userqqqq">
            <result name="success">/register.jsp</result>
            <result name="input">/register.jsp</result>
        </action>
        <action name="editUser" method="edit" class="com.vaannila.web.Userqqqq">
            <result name="success">/register.jsp</result>
            <result name="input">/register.jsp</result>
        </action>
        <action name="deleteUser" method="delete" class="com.vaannila.web.Userqqqq">
            <result name="success" type="redirect">listUser</result>
            <result name="input">/register.jsp</result>
        </action>
    </package>
</struts>

This is my jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
@import url(style.css);
</style>
</head>
<body>
<s:actionerror/>
<s:form action="saveOrUpdateUser" validate="true">


    <s:push value="user">
        <s:hidden name="id" />
        <s:textfield name="name" label="User Name"  required="true"/>
        <s:radio name="gender" label="Gender" list="{'Male','Female'}" />
        <s:select name="country" list="{'India','USA','UK'}" headerKey=""
            headerValue="Select" label="Select a country" />
        <s:textarea name="aboutYou" label="About You" />
        <s:checkbox name="mailingList"
            label="Would you like to join our mailing list?" />
        <s:submit />
    </s:push>
</s:form>

<s:if test="userList.size() > 0">
    <div class="content">
    <table class="userTable" cellpadding="5px">
        <tr class="even">
            <th>Name</th>
            <th>Gender</th>
            <th>Country</th>
            <th>About You</th>
            <th>Mailing List</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
        <s:iterator value="userList" status="userStatus">
            <tr
                class="<s:if test="#userStatus.odd == true ">odd</s:if><s:else>even</s:else>">
                <td><s:property value="name" /></td>
                <td><s:property value="gender" /></td>
                <td><s:property value="country" /></td>
                <td><s:property value="aboutYou" /></td>
                <td><s:property value="mailingList" /></td>
                <td><s:url id="editURL" action="editUser">
                    <s:param name="id" value="%{id}"></s:param>
                </s:url> <s:a href="%{editURL}">Edit</s:a></td>
                <td><s:url id="deleteURL" action="deleteUser">
                    <s:param name="id" value="%{id}"></s:param>
                </s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
            </tr>
        </s:iterator>
    </table>
    </div>
</s:if>
</body>
</html>

This is my action class

package com.vaannila.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.vaannila.dao.UserDAO;
import com.vaannila.domain.User;

public class UserAction extends ActionSupport implements ModelDriven<User> {

    private static final long serialVersionUID = -6659925652584240539L;

    private User user = new User();
    private List<User> userList = new ArrayList<User>();
    private UserDAO userDAO = new UserDAO();

    @Override
    public User getModel() {
        return user;
    }

    /**
     * To save or update user.
     * @return String
     */
    public String saveOrUpdate()
    {    
        System.out.println(user.getName());
        userDAO.saveOrUpdateUser(user);
        return SUCCESS;
    }

    /**
     * To list all users.
     * @return String
     */
    public String list()
    {
        userList = userDAO.listUser();
        return SUCCESS;
    }

    /**
     * To delete a user.
     * @return String
     */
    public String delete()
    {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        userDAO.deleteUser(Long.parseLong(request.getParameter("id")));
        return SUCCESS;
    }

    /**
     * To list a single user by Id.
     * @return String
     */
    public String edit()
    {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        user = userDAO.listUserById(Long.parseLong(request.getParameter("id")));
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

}

This is my BEAN

package com.vaannila.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;


@Entity
@Table(name="USER1")
public class User {

    private Long id;
    private String name;
    private String gender;
    private String country;
    private String aboutYou;
    private Boolean mailingList;

    @Id
    @GeneratedValue
    @Column(name="USER_ID") 
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "name",    message = "User Name field is empty.")
    @Column(name="USER_NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "gender",  message = "gender field is empty.")
    @Column(name="USER_GENDER")
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }

    @Column(name="USER_COUNTRY")
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="USER_ABOUT_YOU")
    public String getAboutYou() {
        return aboutYou;
    }
    public void setAboutYou(String aboutYou) {
        this.aboutYou = aboutYou;
    }

    @Column(name="USER_MAILING_LIST")
    public Boolean getMailingList() {
        return mailingList;
    }
    public void setMailingList(Boolean mailingList) {
        this.mailingList = mailingList;
    }

}

回答1:

You need to add @VisitorFieldValidator annotation to user getter inside your action class.

@VisitorFieldValidator(appendPrefix = false)
public User getUser() {
  return user;
}

Note that you need to set appendPrefix to false if your are using field names without user. prefix in JSP.

Also, you are probably want @RequiredStringValidator not @RequiredFieldValidator inside your bean.

@RequiredStringValidator(message = "User Name field is empty.")
@Column(name="USER_NAME")
public String getName() {
  return name;
}