SSH框架網(wǎng)上商城項(xiàng)目第7戰(zhàn)之整合Struts2和Json
上篇我們完成了DataGrid顯示json數(shù)據(jù),但是沒有和后臺聯(lián)系在一起,只是單純地顯示了我們自己弄的json數(shù)據(jù),這一節(jié)我們將json和Struts2整合,打通EasyUI和Struts2之間的交互。
1. json環(huán)境的搭建
json環(huán)境搭建很簡單,導(dǎo)入json的jar包即可,如下:

(注:json-lib-2.4的jar包下載地址:http://xiazai.jb51.net/201605/yuanma/json-lib-2.4(jb51.net).rar )
2. 完善Action
在DataGrid控件中有個屬性是url,可以指定請求數(shù)據(jù)的url地址,在上一節(jié)我們將這個地址直接設(shè)置成了一個具體的json文件,這里我們將這個url設(shè)置成一個action,如url:'category_queryJoinAccount.action',表示會去請求categoryAction的queryJoinAccount方法(文章最后會給出query.jsp的代碼)。所以我們需要去完成categoryAction中的queryJoinAccount方法。
在Struts2和json整合前,我們先看一下之前顯示一次json數(shù)據(jù)都發(fā)了哪些請求:

因?yàn)閠ype是Category類的一個屬性,我們在BaseAction中已經(jīng)實(shí)現(xiàn)了ModelDriven<Category>接口,所以這個type會被封裝到model中,我們不需要管它,可以通過model來獲取,但是EasyUI自動發(fā)過來的page和rows參數(shù)我們需要自己獲取了,所以我們可以在BaseModel中增加兩個成員變量page和rows并實(shí)現(xiàn)get和set方法,最后還要考慮一點(diǎn),這些參數(shù)都獲得了后,我們根據(jù)這些參數(shù)去數(shù)據(jù)庫中查詢數(shù)據(jù),那么我們查出來的數(shù)據(jù)放到哪呢?而且還要打包成json格式發(fā)到前臺才能被DataGrid顯示。我們先不考慮將查詢到的數(shù)據(jù)如何打包成json格式,我們先考慮把這些數(shù)據(jù)放到一個地方,很自然的想到了使用Map,因?yàn)閖son格式的數(shù)據(jù)就是key-value形式的。想到這里,我們繼續(xù)完善BaseAction:
@Controller("baseAction")
@Scope("prototype")
public class BaseAction<T> extends ActionSupport implements RequestAware,SessionAware,ApplicationAware,ModelDriven<T> {
//page和rows和分頁有關(guān),pageMap存放查詢的數(shù)據(jù),然后打包成json格式用的
//page和rows實(shí)現(xiàn)get和set方法,pageMap只需要實(shí)現(xiàn)get方法即可,因?yàn)閜ageMap不是接收前臺參數(shù)的,是讓struts獲取的
protected Integer page;
protected Integer rows;
protected Map<String, Object> pageMap = null;//讓不同的Action自己去實(shí)現(xiàn)
//省略get和set方法……
/******************* 下面還是原來BaseAction部分 *************************/
//service對象
@Resource
protected CategoryService categoryService;
@Resource
protected AccountService accountService;
//域?qū)ο?
protected Map<String, Object> request;
protected Map<String, Object> session;
protected Map<String, Object> application;
@Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
@Override
public void setRequest(Map<String, Object> request) {
this.request = request;
}
//ModelDriven
protected T model;
@Override
public T getModel() {
ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass();
Class clazz = (Class)type.getActualTypeArguments()[0];
try {
model = (T)clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
return model;
}
}
好,完善了BaseCategory后,我們可以寫categoryAction中的queryJoinAccount方法了,我們將categoryAction中原來的方法全刪掉,因?yàn)槟切┒际侵按罱ōh(huán)境時候測試用的,都不用了,現(xiàn)在真正開始項(xiàng)目代碼了:
@Controller("categoryAction")
@Scope("prototype")
public class CategoryAction extends BaseAction<Category> {
public String queryJoinAccount() {
//用來存儲分頁的數(shù)據(jù)
pageMap = new HashMap<String, Object>();
//根據(jù)關(guān)鍵字和分頁的參數(shù)查詢相應(yīng)的數(shù)據(jù)。這個方法我們在Service中寫過了,當(dāng)時完成級聯(lián)查詢
List<Category> categoryList = categoryService.queryJoinAccount(model.getType(), page, rows);
pageMap.put("rows", categoryList); //存儲為JSON格式,從上一節(jié)的json文件可以看出,一個key是total,一個key是rows,這里先把rows存放好
//根據(jù)關(guān)鍵字查詢總記錄數(shù)
Long total = categoryService.getCount(model.getType()); //這個方法沒寫,我們等會兒去Service層完善一下
// System.out.println(total);
pageMap.put("total", total); //存儲為JSON格式,再把total存放好
return "jsonMap";
}
}
這樣Action我們就寫好了,現(xiàn)在Action拿到前臺傳來的參數(shù),然后根據(jù)參數(shù)查詢了指定type的總記錄數(shù),以及指定type的所有商品,并且按照json中指定的key(即total和rows)進(jìn)行存放,放在HashMap中了,之后只要將這個HashMap中的數(shù)據(jù)打包成json格式發(fā)送到前臺就可以被DataGrid顯示了。我們先把這個HashMap放這,先去完善了Service層的代碼后,再來打包這個HashMap中的數(shù)據(jù)。
3. 完善categoryService
從上面的categoryAction中可知,需要在categoryService中增加一個getCount方法,并且要在具體實(shí)現(xiàn)類中實(shí)現(xiàn)好,實(shí)現(xiàn)如下:
//CategoryService接口
public interface CategoryService extends BaseService<Category> {
//查詢類別信息,級聯(lián)管理員
public List<Category> queryJoinAccount(String type, int page, int size); //使用類別的名稱查詢
//根據(jù)關(guān)鍵字查詢總記錄數(shù)
public Long getCount(String type);
}
//CategoryServiceImpl實(shí)現(xiàn)類
@SuppressWarnings("unchecked")
@Service("categoryService")
public class CategoryServiceImpl extends BaseServiceImpl<Category> implements CategoryService {
@Override
public List<Category> queryJoinAccount(String type, int page, int size) {
String hql = "from Category c left join fetch c.account where c.type like :type";
return getSession().createQuery(hql)
.setString("type", "%" + type + "%")
.setFirstResult((page-1) * size) //從第幾個開始顯示
.setMaxResults(size) //顯示幾個
.list();
}
@Override
public Long getCount(String type) {
String hql = "select count(c) from Category c where c.type like :type";
return (Long) getSession().createQuery(hql)
.setString("type", "%" + type + "%")
.uniqueResult(); //返回一條記錄:總記錄數(shù)
}
}
到現(xiàn)在為止,這個數(shù)據(jù)庫中數(shù)據(jù)的獲取這條路就打通了,前面兩步完成了從前臺-->數(shù)據(jù)庫-->取數(shù)據(jù),接下來就開始打包HashMap中存放的數(shù)據(jù),然后發(fā)給前臺了。
4. 配置struts.xml
在struts.xml中通過配置就可以完成對指定數(shù)據(jù)的打包,我們先看一下struts.xml中的配置:
<struts>
<constant name="struts.devMode" value="true" />
<package name="shop" extends="json-default"><!-- jason-default繼承了struts-default -->
<global-results>
<result name="aindex">/WEB-INF/main/aindex.jsp</result>
</global-results>
<!-- class對應(yīng)的是Spring中配置該Action的id值,因?yàn)橐唤oSpring管理 -->
<action name="category_*" class="categoryAction" method="{1}">
<!-- 必須要先添加json包,然后上面繼承json-default -->
<result name="jsonMap" type="json">
<!-- 要轉(zhuǎn)換成json對象的數(shù)據(jù) -->
<param name="root">pageMap</param>
<!-- 配置黑名單,過濾不需要的選項(xiàng) ,支持正則表達(dá)式
json格式:{total:3,rows:[{account:{id:2,login:"user",name:"客服A",pass:"user"},hot:true,id:3,…}]}
-->
<param name="excludeProperties">
<!-- rows[0].account.pass-->
<!-- 這里顯示不了正則表達(dá)式, CSDN的一個bug,我接個圖放下面 -->
</param>
</result>
</action>
<action name="account_*" class="accountAction" method="{1}">
<result name="index">/index.jsp</result>
</action>
<!-- 用來完成系統(tǒng) 請求轉(zhuǎn)發(fā)的action,所有的請求都交給execute-->
<action name="send_*_*" class="sendAction">
<result name="send">/WEB-INF/{1}/{2}.jsp</result>
</action>
</package>
</struts>

從上面的配置可以看出,首先package要繼承json-default,因?yàn)閖son-default繼承了struts-default,因?yàn)樵趈son的jar包里有個struts2-json-plugin-2.3.24.1.jar,打開即可看到里面有個struts-plugin.xml,打開即可看到j(luò)son-default是繼承了struts-default:

接下來我配置<result>,name是剛剛action返回的字符串,type一定要配成json。然后就是result中的參數(shù)了,首先必須要配的就是name為root的參數(shù),這個參數(shù)要配成剛剛需要轉(zhuǎn)換的HashMap對象,即我們定義的pageMap,有了這個參數(shù)的配置,struts才會將pageMap中的數(shù)據(jù)打包成json格式。然后就是配置黑名單,黑名單的意思就是告訴struts在打包的時候,哪些字段不需要打包,比如管理員密碼之類的信息,由上面注釋中的jason格式可以看出rows[0].account.pass表示密碼字段,但是數(shù)據(jù)肯定不止一條,所以我們得用正則表達(dá)式來表示,這樣所有密碼都不會被打包到j(luò)son中。
5. 修改query.jsp內(nèi)容
到此,我們已經(jīng)將數(shù)據(jù)打包成了json格式了,接下來我們完善一下前臺query.jsp的內(nèi)容就可以讓DataGrid正確顯示了:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ include file="/public/head.jspf" %>
<script type="text/javascript">
$(function(){
$('#dg').datagrid({
//url地址改為請求categoryAction
url:'category_queryJoinAccount.action',
loadMsg:'Loading......',
queryParams:{type:''},//type參數(shù),這里不需要傳具體的type,因?yàn)槲覀円@示所有的
//width:300,
fitColumns:true,
striped:true,
nowrap:true,
singleSelect:true,
pagination:true,
rowStyler: function(index,row){
console.info("index" + index + "," + row)
if(index % 2 == 0) {
return 'background-color:#fff;';
} else {
return 'background-color:#ff0;';
}
},
frozenColumns:[[
{field:'checkbox',checkbox:true},
{field:'id',title:'編號',width:200} //這里的field字段要和數(shù)據(jù)庫中的一樣,也就是要跟json數(shù)據(jù)中的一樣
]],
columns:[[
{field:'type',title:'類別名稱',width:100, //字段type
formatter: function(value,row,index){
return "<span title=" + value + ">" + value + "</span>";
}
},
{field:'hot',title:'熱賣',width:100, //字段hot
formatter: function(value,row,index){
if(value) { //如果是hot,該值為true,value是boolean型變量
return "<input type='checkbox' checked='checked' disabled='true'"; //勾選
} else {
return "<input type='checkbox' disable='true'"; //不勾選
}
}
},
{field:'account.login',title:'所屬管理員',width:200, //account.login管理員登錄名
formatter: function(value,row,index){
if(row.account != null && row.account.login != null) {
return row.account.login; //如果登錄名不為空,顯示登錄名
} else {
return "此類別沒有管理員";
}
}
}
]]
});
});
</script>
</head>
<body>
<table id="dg"></table>
</body>
</html>
6. 測試顯示結(jié)果
最后我們測試一下DataGrid的顯示結(jié)果,如下:

到這里,我們成功整合了Struts2和json,現(xiàn)在可以和前臺傳輸json格式的數(shù)據(jù)了。
(注:到最后我會提供整個項(xiàng)目的源碼下載!歡迎大家收藏或分享)
原文地址:http://blog.csdn.net/eson_15/article/details/51332758
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java全面細(xì)致講解Cookie與Session及kaptcha驗(yàn)證碼的使用
web開發(fā)階段我們主要是瀏覽器和服務(wù)器之間來進(jìn)行交互。瀏覽器和服務(wù)器之間的交互就像人和人之間進(jìn)行交流一樣,但是對于機(jī)器來說,在一次請求之間只是會攜帶著本次請求的數(shù)據(jù)的,但是可能多次請求之間是會有聯(lián)系的,所以提供了會話機(jī)制2022-06-06
SpringBoot如何讀取配置文件中的數(shù)據(jù)到map和list
這篇文章主要介紹了SpringBoot如何讀取配置文件中的數(shù)據(jù)到map和list,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
簡單了解Spring Cloud Alibaba相關(guān)知識
這篇文章主要介紹了簡單了解Spring Cloud Alibaba相關(guān)知識,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10
java實(shí)現(xiàn)excel導(dǎo)入數(shù)據(jù)的工具類
這篇文章主要介紹了java實(shí)現(xiàn)的excel導(dǎo)入數(shù)據(jù)的工具類,需要的朋友可以參考下2014-03-03
解決SpringBoot運(yùn)行Test時報錯:SpringBoot Unable to find
這篇文章主要介紹了SpringBoot運(yùn)行Test時報錯:SpringBoot Unable to find a @SpringBootConfiguration,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Spring?BeanFactory容器的構(gòu)建和使用示例詳解
BeanFactory是Spring框架中的一部分,它提供了IoC(控制反轉(zhuǎn))的實(shí)現(xiàn)機(jī)制,下面小編就來和大家簡單聊聊BeanFactory容器的構(gòu)建和使用示例吧2023-07-07
利用SpringMVC接收復(fù)雜對象和多個文件(前端使用JQuery)
這篇文章主要介紹了利用SpringMVC接收復(fù)雜對象和多個文件(前端使用JQuery),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
SpringCloud?服務(wù)注冊中的nacos實(shí)現(xiàn)過程
這篇文章主要介紹了SpringCloud?服務(wù)注冊之nacos實(shí)現(xiàn)過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03

