从jsp中可用的struts 2生成变量

时间:2013-06-17 08:52:42

标签: java jsp struts2

我正在尝试有条件地设置元素的css。这是jsp中的一行:

<s:textfield name="registerBean.email" placeholder="Email Address*" cssClass="INSERT userNameError here" required="" />
<s:textfield name="registerBean.userName" placeholder="Username*" cssClass="INSERT emailError here" required="" />

在我的动作课中,我有类似的东西:

package actions;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import service.implementations.UserServiceImplementation;
import service.interfaces.UserService;
import util.REGISTER_RESULT;

import com.opensymphony.xwork2.ActionSupport;

import entities.User;

public class Register extends ActionSupport {

    private User registerBean;
    private String userNameError = "register";
    private String emailError = "register";

    @Override
    public String execute()
    {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ExamModulePu");
        EntityManager em = emf.createEntityManager();
        UserService service = new UserServiceImplementation(em);
        REGISTER_RESULT result = service.registerUser(registerBean);


        if(result.isDuplicateEmail())
            setEmailError("register error");
        if(result.isDuplicateUserName())
            setUserNameError("register error");
        em.close();
        emf.close();
        return result.toString();
    }

    public User getRegisterBean() {
        return registerBean;
    }

    public void setRegisterBean(User registerBean) {
        this.registerBean = registerBean;
    }

    public String getEmailError() {
        return emailError;
    }

    public void setEmailError(String emailError) {
        this.emailError = emailError;
    }

    public String getUserNameError() {
        return userNameError;
    }

    public void setUserNameError(String userNameError) {
        this.userNameError = userNameError;
    }
}

我如何才能将这些变量提供给jsp?或者有更好的方法来完成我想要做的事情吗?

1 个答案:

答案 0 :(得分:1)

为了给验证失败的字段提供一些CSS类,您可以使用cssErrorClass属性。

<s:textfield name="registerBean.userName" placeholder="Username*" cssErrorClass="register error" required="" />

在您的操作中,使用addFieldError方法将错误添加到特定字段。