struts2 和 標籤
阿新 • • 發佈:2019-01-05
在表單中使用<s:radio> 和 <s:select>
標籤 繫結action屬性,查詢資料
開始介面如下, 通過提交的資料去對應的action查詢
jsp程式碼, <s:radio> 和 <s:select>
標籤中的 list 表示資料的來源, value表示給定此標籤一個預設值, name表示與action中對應的屬性
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
</head>
<%
TreeMap<String ,String> searchType = new TreeMap<String, String>();
searchType.put("男", "男");
searchType.put("女", "女");
request.setAttribute("searchType",searchType);
TreeMap<String ,String> age = new TreeMap<String, String>();
age.put("1","1歲");
age.put("2","2歲");
age.put("3","3歲");
age.put("4","4歲");
age.put("5","5歲");
request.setAttribute("age",age);
%>
<body>
<s:form action="submit.action?">
<s:textfield name ="info.name" label="姓名"></s:textfield>
<s:radio
list="#request.searchType" label="性別" value="%{'男'}" name="info.sex">
</s:radio>
<s:select
list="#request.age" label="年齡" value="%{'1'}" name="info.age">
</s:select>
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>
對應的action類如下, 將結果集放入list,存入request中
public class Action extends ActionSupport{
static TreeMap<String,Info> data = new TreeMap<String, Info>();
Map<Object, Object> request = new TreeMap<Object, Object>();
Info info ;
@Override
public String execute() throws Exception {
System.out.println(info);
ActionContext context = ActionContext.getContext();
request = (Map<Object, Object>) context.get("request");
List<Info> infos = new ArrayList<Info>();
for (Info v : data.values()){
if (v.getName().equals(info.getName()) && v.getAge().equals(info.getAge()) && v.getSex().equals(info.getSex())){
System.out.println(v);
infos.add(v);
}
}
System.out.println(infos.size());
request.put("infos", infos);
return SUCCESS;
}
static{
data.put("1", new Info(1, "張三", "男", 1));
data.put("2", new Info(2, "張三", "男", 1));
data.put("3", new Info(3, "趙四", "男", 2));
data.put("4", new Info(4, "王五", "女", 3));
data.put("5", new Info(5, "六六", "女", 4));
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public Map<Object, Object> getRequest() {
return request;
}
public void setRequest(Map<Object, Object> request) {
this.request = request;
}
}
在SUCCESS jsp頁面程式碼如下, 取出request中的list, 用iterator 標籤遍歷
<body>
<s:set name="infos" value="#request.infos"></s:set>
<s:iterator status="infosStatus" value="infos">
<s:property value="id"/>
<s:property value="name"/>
<s:property value="sex"/>
<s:property value="age"/><br>
</s:iterator>
</body>
select的屬性