為了比較直觀的學習,這裡建立一個web工程為:struts2textfield。整個工程的目錄結構如下:
在Struts2中,<s:textfield>文字範例, 例如,可以宣告「s:textfield」鍵屬性或標籤和名稱屬性。
<s:textfield key="username" /> // 或 <s:textfield label="Username" name="username" />
<td class="tdLabel"> <label for="registerUser_username" class="label">Username:</label> </td> <td> <input type="text" name="username" value="" id="registerUser_username"/> </td>
global.properties
#Global messages username = 使用者名 submit = 提交
RegisterAction.properties
#error message username.required = 使用者名不可以為空
RegisterAction.java
package com.yiibai.user.action; import com.opensymphony.xwork2.ActionSupport; public class RegisterAction extends ActionSupport{ private String username; 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")); } } }
register.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>Struts 2 - textbox 範例</h1> <s:form action="registerUser" namespace="/user"> <s:textfield key="username" /> <s:submit key="submit" name="submit" /> </s:form> </body> </html>
welcome.jsp
<%@ page contentType="text/html;charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <h1>Struts 2 - textbox 範例</h1> <h2><s:property value="username"/></h2> or <h2><s:property value="%{username}"/></h2> </body> </html>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="global" /> <constant name="struts.devMode" value="true" /> <package name="user" namespace="/user" extends="struts-default"> <action name="register"> <result>/pages/register.jsp</result> </action> <action name="registerUser" class="com.yiibai.user.action.RegisterAction"> <result name="SUCCESS">/pages/welcome.jsp</result> <result name="input">/pages/register.jsp</result> </action> </package> </struts>
http://localhost:8080/struts2textfield/user/register.action