繼續上一篇關於 struts 2 jQuery tag 的介紹,這裡要 demo 一個很有用的 tag --- grid ! 如下圖是執行出來的結果。
struts jQuery tag 提供的 grid 功能非常強大,可以排序、翻頁、編輯,這些進階的功能留給鄉民們自行研究,這裡只簡單的從資料庫撈出選定日期的資料,顯示在 grid 上。struts.xml 及 index.jsp 的內容沒有改變,請看上一篇的內容。其餘說明如下:
- 專案結構: 所有檔案的列表,因為這裡的股票資料是存在資料庫,整合了 spring 和 mybatis,所以多了一些 DAO、DTO 及 spring 設定檔。
- 因為要整合 spring 和 mybatis,並且引入新的 grid tag 的標籤庫,所以 pom.xml 修改如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>DemoSite</groupId> <artifactId>DemoSite</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.16.3</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.16.3</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.16.3</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.16.3</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-junit-plugin</artifactId> <version>2.3.16.3</version> </dependency> <dependency> <groupId>com.jgeppert.struts2.jquery</groupId> <artifactId>struts2-jquery-plugin</artifactId> <version>3.7.1</version> </dependency> <dependency> <groupId>com.jgeppert.struts2.jquery</groupId> <artifactId>struts2-jquery-grid-plugin</artifactId> <version>3.7.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.33</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.2</version> </dependency> </dependencies> </project>
- 修改 web.xml,整合 spring,內容如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>struts2</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:beans-config.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
- spring 設定檔: 這裡只是用 spring 整合 mybatis,以讀取資料庫,所有 DAO 會放在 idv.steven.demo.dao 這個 package 裡。datasource.properties 裡則有 JDBC 相關參數。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <context:property-placeholder location="classpath:datasource.properties" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="transactionFactory"> <bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" /> </property> <property name="mapperLocations"> <list> <value>classpath*:idv/steven/demo/dao/StockDao.xml</value> </list> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:sqlSessionFactoryBeanName="sqlSessionFactory" p:basePackage="idv.steven.demo.dao" /> </beans>
# datasource.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.0.110:3306/demosite jdbc.username=steven jdbc.password=password
- DTO 的定義如下,是用來將資料庫裡的資料傳回給程式,因為 table Stock 有六個欄位,且我們這六個欄位的值都想要,就定義了相同的名稱的六個變數,並給予 getter、setter method。
package idv.steven.demo.dto; import java.sql.Date; public class Stock implements Comparable<Stock> { private String iD; private String name; private Double fluctuation; private Integer amount; private Double price; private Date txDate; public String getID() { return iD; } public void setID(String iD) { this.iD = iD; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getFluctuation() { return fluctuation; } public void setFluctuation(Double fluctuation) { this.fluctuation = fluctuation; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Date getTxDate() { return txDate; } public void setTxDate(Date txDate) { this.txDate = txDate; } @Override public String toString() { return "Stock [iD=" + iD + ", name=" + name + ", fluctuation=" + fluctuation + ", amount=" + amount + ", price=" + price + ", txDate=" + txDate + "]"; } @Override public int compareTo(Stock o) { return this.iD.compareTo(o.getID()); } }
- DAO 的程式如下,其實我們只會用到 find method,createStock method 可以先忽略。find method 接收一個參數 -- 交易日期,並將當天的股票資料傳回,注意 @Repository 這個標註,這表示這個類別是一個 DAO。
package idv.steven.demo.dao; import idv.steven.demo.dto.Stock; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Repository public interface StockDao { public List<Stock> find(@Param("txDate") String txDate); public int createStock(Stock stock); }
- mybatis 的 O/R mapping 如下,很簡單的一個 select statement。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="idv.steven.demo.dao.StockDao"> <sql id="fields">iD, name, fluctuation, amount, price, txDate</sql> <resultMap type="idv.steven.demo.dto.Stock" id="stock"> <id column="iD" property="iD"/> <result column="name" property="name"/> <result column="fluctuation" property="fluctuation"/> <result column="amount" property="amount"/> <result column="price" property="price"/> <result column="txDate" property="txDate"/> </resultMap> <select id="find" parameterType="String" resultMap="stock"> select <include refid="fields"/> from Stock where txDate = #{txDate} </select> <insert id="createStock"> insert into Stock (<include refid="fields"/>) values (#{iD}, #{name}, #{fluctuation}, #{amount}, #{price}, #{txDate}) </insert> </mapper>
- stock.jsp: 從 index.jsp 點選「股價」的 tab 後,觸發 action 後轉進入這個畫面,這個畫面有三個元件,一個「日曆」、一個「按鈕」及一個「div」。這裡要注意的是 submit 這個 tag 的 targets attribute,它指出了結果會顯示的位置。按 submit 後會觸發的 action 是寫在 href 裡。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sj" uri="/struts-jquery-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> <sj:head jqueryui="true"/> </head> <body> <s:url var="remoteurl" action="showStock" /> <s:form id="formStock" theme="xhtml"> <sj:datepicker id="txDate" name="txDate" label="請選擇日期" displayFormat="yy/mm/dd" /> <sj:submit href="%{remoteurl}" targets="stockPrice" value="送出" indicator="indicator" button="true" /> </s:form> <sj:div id="stockPrice" /> </body> </html>
- Acton: 上面的畫面按 submit 後觸發了下面橘色的 method,這個 method 沒做什麼事,只是通知結果要顯示在 /jsp/showStock.jsp 這個網頁,至於結果是什麼? 那要看 showStock.jsp 才知道。
package idv.steven.demo.action; import java.util.List; import idv.steven.demo.dao.StockDao; import idv.steven.demo.dto.Stock; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; public class StockAction extends ActionSupport { private static final long serialVersionUID = 4242093494226883485L; final static Logger logger = LoggerFactory.getLogger(StockAction.class); @Autowired private StockDao dao; private String txDate; private List<Stock> stocks; //action method @Action(value = "/stock", results = { @Result(location = "/jsp/stock.jsp", name = "success") }) public String stock() throws Exception { return SUCCESS; } @Action(value = "/showStock", results = { @Result(location = "/jsp/showStock.jsp", name = "success") }) public String showStock() { return SUCCESS; } @Action(value = "/stockList", results = { @Result(name = "success", type = "json") }) public String stockList() { stocks = dao.find(txDate); return SUCCESS; } //getter & setter method public String getTxDate() { return txDate; } public void setTxDate(String txDate) { this.txDate = txDate; } public List<Stock> getStocks() { return stocks; } public void setStocks(List<Stock> stocks) { this.stocks = stocks; } }
- 股票列表的網頁如下,就只有一個 grid 裡顯示著股票資訊,因為 grid 是在 struts-query-grid-tags 標籤庫裡,所以綠色部份將這個標籤庫引入。至於 grid 的資料來源在那呢? 要看橘色部份,這裡指出要到 stockList action 去取得資料,淺藍色則是指出取得的資料將以什麼怎樣的資料型別傳回,這裡指定為 json,gridModel 這個設定則是資料傳回時的物件名稱,這裡設為 stocks,即表示在 action 那邊應該會有一個 getStocks() 的 method 可供 grid 取得資料。要特別注意的是灰色那一行,它指出了這個 grid 是屬於那一個 form,這樣我們才抓的到 form 裡面的交易日期。
現在回頭去看上面的 action -- StockAction.java,裡面標有 @Action("stockList") 的 method,grid 從這取得資料,程式很簡單的呼叫 DAO 取得資料放到 stocks 變數裡即返回 grid,而 grid 這時即可透過 getStocks() method 取得相關資料並顯示出來了! 注意看那個 method 上也有標注傳回的資料型別為 json,action 和 grid 間才能正確溝通。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sj" uri="/struts-jquery-tags"%> <%@ taglib prefix="sjg" uri="/struts-jquery-grid-tags"%> <s:url var="remoteurl1" action="stockList" /> <sjg:grid id="gridtable" caption="股價" dataType="json" href="/stockList" pager="true" gridModel="stocks" rowList="10,15,20" formIds="formStock" rowNum="15" rownumbers="true" viewrecords="true" shrinkToFit="true" > <sjg:gridColumn name="txDate" index="txDate" title="交易日期" sortable="false"/> <sjg:gridColumn name="ID" index="ID" title="代號" sortable="false"/> <sjg:gridColumn name="name" index="name" title="名稱" sortable="true"/> <sjg:gridColumn name="fluctuation" index="fluctuation" title="漲跌" sortable="false"/> <sjg:gridColumn name="amount" index="amount" title="交易量" sortable="true"/> <sjg:gridColumn name="price" index="price" title="成交價" sortable="true"/> </sjg:grid>
最後執行出來的,就如一開頭的畫面所示,非常的簡單,而且正如 struts2 jQuery tag 這個名稱所示的,因為是用 jQuery 透過 ajax 取得資料直接顯示於當前的網頁,所以不會有傳統網頁還要翻到新一頁才能顯示資料的問題。