若還沒有看過前面幾篇文章的話建議先去看Struts2 架構配置教學、Struts2+Spring架構配置教學(Spring)、Struts2+Spring+Hibernate架構配置教學(Hibernate)上、Struts2+Spring+Hibernate架構配置教學(Hibernate+JNDI)下、Spring+Hibernate用法教學
再來看這篇文章
討厭鬼會用到struts2 tag的時候
多判是用來套版面的時候~
當然也可以拿來做一些畫面開始必需要做的事情
在這邊要教的東西不多~
只會教一些常用的東西
像是 if iterator 等等之類常用的東西
那麼癈話就不多說了~開始吧
在用Srtus2 tag之前~我們要先重資料庫撈資料出來
先在index()裡查詢
並設置一個全域變數來接收
並了能讓jsp拿到這個變數
需要實作getter
範列
public class IndexAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
@Resource
private LeatherService leatherService;
List<LeatherType> leatherTypeList;
public String index() {
leatherTypeList = leatherService.doQueryLeatherTypeList();
return SUCCESS;
}
public List<LeatherType> getLeatherTypeList() {
return leatherTypeList;
}
}
在jsp中加入下列就可以列出資料了
我的資料;車中有3筆資料
其中兩筆price >=200
所以下列就只會列出兩筆
<table>
<s:iterator value="leatherTypeList" status="i">
<tr>
<s:if test="price >= 200">
<td><s:property value="typeName"/></td>
<td><s:property value="price"/></td>
</s:if>
</tr>
</s:iterator>
</table>
範列
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>討厭鬼的教學</title>
</head>
<body>
<table>
<s:iterator value="leatherTypeList" status="i">
<tr>
<s:if test="price >= 200">
<td><s:property value="typeName"/></td>
<td><s:property value="price"/></td>
</s:if>
</tr>
</s:iterator>
</table>
</body>
</html>
而像select跟radio的用法也很簡單
可以直接在List的地方寫死如下
<s:select list="#{1:'大皮',2:'中皮',3:'小皮',4:'死皮'}" />
或是直接用map型態的物件就可以了~如下
<s:select list="typeMap" />
而property的用法也可以很多種
例如我在action有物件叫userName與hello也設定getter了~如下
String userName = "nerdy";
String hello = "你好嗎?";
public String getUserName(){
return userName;
}
public String getHello(){
return hello;
}
那我的Struts2 tag
就可以寫成<s:property name="userName"/><s:property name="hello"/>
結果就會變成"nerdy你好嗎?"
也可以寫成<s:property name="userName+hello"/>
結果一樣是"nerdy你好嗎?"
當然也可以用substring
如果型態是int的話~也可以用來加減乘除
切記~如果要讓jsp拿到值
一定要在action的地方設定getter不然的話是取不到值的
基本上在做套版的只要用到if跟iterator就可以做到大部份的事
能用到Struts2 tag的地方盡量用
如果我要做一個連回首頁的
<s:a action="index">連回首頁</s:a>
還有一點是需要注意一點
在使用if時若是判斷字串
應該為
<s:if test='userName == "nerdy" '>
而非
<s:if test="userName == 'nerdy' ">
差別就在於若是用單引號
會認為這是char而判斷錯誤
用雙引號就不會有問題了
預計下次會發Spring transactionmanager的教學
留言列表