Struts2 <s:radio>單選按鈕例子
在Struts2,可以使用<s:radio>標籤來創建一個HTML單選按鈕。有很多方法來填充數據到單選按鈕,可以通過List, OGNL 或 Object。請查看下面的例子就知道了。
Struts2 <s:radio> 示例
舉個例子來說明如何使用列表,OGNL和對象數據填充到Struts2中,使用<s:radio>標籤創建一個單選按鈕。
1. 動作 - Action
Action類來創建性別和語言值單選按鈕列表。
RadioButtonAction.java
package com.yiibai.common.action;
import java.util.ArrayList;
import java.util.List;
import com.yiibai.common.model.Language;
import com.opensymphony.xwork2.ActionSupport;
public class RadioButtonAction extends ActionSupport{
private List<String> genders;
private List<Language> languages ;
private String yourGender;
private String yourAnswer;
private String yourLanguage;
private static final String MALE = "male";
private static final String FEMALE = "female";
private static final String UNKNOWN = "unknown";
public RadioButtonAction(){
genders = new ArrayList<String>();
genders.add(MALE);
genders.add(FEMALE);
genders.add(UNKNOWN);
languages = new ArrayList<Language>();
languages.add( new Language("EN", "English") );
languages.add( new Language("FR", "France") );
languages.add( new Language("CN\_ZH", "Chinese") );
languages.add( new Language("DE", "German") );
}
//return default gender value
public String getDefaultGenderValue(){
return UNKNOWN;
}
//return default language value
public String getDefaultLanguageValue(){
return "CN\_ZH";
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}
//getter ad setter methods
}
Language.java
**package com.yiibai.common.model;
public class Language{
private String languageCode;
private String languageDisplay;
public String getLanguageCode() {
return languageCode;
}
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
public String getLanguageDisplay() {
return languageDisplay;
}
public void setLanguageDisplay(String languageDisplay) {
this.languageDisplay = languageDisplay;
}
public Language(String languageCode, String languageDisplay) {
this.languageCode = languageCode;
this.languageDisplay = languageDisplay;
}
}**
2. 結果頁面
結果頁面是使用Struts2 「s:radio」 通過List, OGNL 和 object來創建的三個單選按鈕。
radiobutton.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 radio button example
<s:form action="resultAction" namespace="/">
<s:submit value="submit" name="submit" />
aresult.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 radio button example
Your Selected Gender :
Your Selected Language :
Your Selected Answer :
3. struts.xml
<action name="radioButtonAction"
class="com.yiibai.common.action.RadioButtonAction" method="display">
<result name="none">/pages/radiobutton.jsp</result>
</action>
<action name="resultAction" class="com.yiibai.common.action.RadioButtonAction">
<result name="success">/pages/result.jsp</result>
</action>
5. 示例
http://localhost:8080/struts2radio/radioButtonAction.action
http://localhost:8080/struts2radio/resultAction.action
要了解如何預選值,讀這篇文章 – 在Struts2的單選按鈕預選值