Struts2 <s:password>密碼示例
在這一章節中,我們創建一個Web工程爲:struts2passwd,演示<s:password>的使用。完整的工程目錄結構如下:
在Struts2中,可以使用<s:password>來創建HTML密碼字段。例如,可以聲明「s:password」鍵屬性或者標籤和名稱屬性。
<s:password key="password" />
//or
<s:textfield label="Password" name="password" />
兩者都產生相同的HTML輸出(在默認的XHTML主題)。
Struts2 <s:password> 示例
一個頁面,「密碼」和「確認密碼」字段,並做了驗證,以確保「確認密碼」是與「密碼」相匹配。
1. 屬性文件
global.properties
#Global messages
username = 用名名
password = 密碼
confirmPassword = 確認密碼
submit = 提交
RegisterAction.properties
#error message
username.required = Username is required
password.required = Password is required
cpassword.required = Confirm password is required
cpassword.notmatch = Confirm password is not match
2. 動作 - Action
RegisterAction.java
package com.yiibai.user.action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private String username;
private String password;
private String confirmPassword;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
//business logic
public String execute() {
return "SUCCESS";
}
//simple validation
public void validate(){
if("".equals(getUsername())){
addFieldError("username", getText("username.required"));
}
if("".equals(getPassword())){
addFieldError("password", getText("password.required"));
}
if("".equals(getConfirmPassword())){
addFieldError("confirmPassword", getText("cpassword.required"));
}
if(!(getPassword().equals(getConfirmPassword()))){
addFieldError("confirmPassword", getText("cpassword.notmatch"));
}
}
}
3. 視圖頁面
結果頁面使用 Struts2 的「s:password」標籤來創建一個HTML密碼字段。
register.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 - password 示例
<s:form action="registerUser" namespace="/user">
<s:textfield key="username" />
<s:password key="password" />
<s:password key="confirmPassword" />
<s:submit key="submit" name="submit" />
welcome.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 - password 示例
Password :
Confirm Password :
4. struts.xml
5. 運行示例
http://localhost:8080/struts2passwd/user/register.action
*
*