2015年9月18日 星期五

修改驗證和內置對象 (Struts2.3.x 五)

※修改驗證

ActionSupport其實早就有validate()了,可以利用它來做驗證,會比較漂亮 struts.properties
login.success=login success
login.fail=login fail

LoginAction
private User user = new User();
public User getUser() {
    return user;
}

@Override
public String execute() throws Exception {
    return SUCCESS;
}

@Override
public void validate() {
    if (user.getUserName().trim().isEmpty()) {
        super.addFieldError("s", super.getText("login.success"));
    }

    if (user.getUserPassword().trim().isEmpty()) {
        super.addFieldError("f", super.getText("login.fail"));
    }
}


struts.xml
<action name="login" class="login.LoginAction" method="execute">
    <result name="success">/struts2/login.jsp</result>
    <result name="input">/struts2/login.jsp</result>
</action>

login.jsp
${fieldErrors}
<s:property value="displayMessage" />
<form action="login.action">
    <input type="text" name="user.userName" />${FieldErrors["s"][0]}<br />
    <input type="password" name="user.userPassword" />${FieldErrors["f"][0]}<br />
    <input type="reset" />
    <input type="submit" />
</form>

User.java
private String userName;
private String userPassword;
//setter/getter...
在jsp的${fieldErrors},主要是印出來,才知道是陣列,也才會知道要用${FieldErrors["s"][0]}

※內置對象

Servlet有四個內置對象:request、response、session、application,
可在execute()加程式碼,驗證成功就會印出
HttpServletRequest request = ServletActionContext.getRequest() ;
HttpServletResponse response = ServletActionContext.getResponse() ;
HttpSession session = request.getSession() ;
ServletContext context = ServletActionContext.getServletContext() ;

System.out.println("虛擬路徑=" + request.getContextPath());
System.out.println("編碼=" + response.getCharacterEncoding());
System.out.println("Session ID=" + session.getId());
System.out.println("真實路徑=" + context.getRealPath("/"));

沒有留言:

張貼留言