使用ajax gson增強用戶體驗
1、技術目標
- 爲項目加入gson支持
- 在struts2的Action中使用gson輸出json格式數據
- 採用jQuery的ajax方式完成CRUD操作
注意:本文所用項目爲"影片管理",參看
http://hotstrong.iteye.com/blog/1156785
2、什麼是gson?
Gson是Google的一個開源項目
可以將Java對象轉換成JSON
也可以將JSON轉換成Java對象
Gson有兩個重要的對象
Gson
GsonBuilder
Gson對象有兩個基本方法
toJson() – 轉換java對象到JSON
fromJson() – 轉換JSON到java對象
3、使用準備
3.1)在項目中增如下jar包(gson框架所需jar包),本文已提供下載:
gson-1.5.jar
3.2)站點根路徑下創建文件夾js(放置javascript代碼),js文件夾下再創建images文件夾,放置圖片素材,導入以下jQuery相關文件:
jquery.form.js
jquery.loadmask.css
jquery.loadmask.js
jquery.js
注意:本文所用jQuery版本爲v1.4.2,js、css文件以及圖片素材已提供下載
3.3)在項目中的struts.xml文件中修改Action配置,將"獲取所有影片"、"添加影片"、"修改影片"、"刪除影片"的<result ...>配置刪除,修改後的文件如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <constant name="struts.i18n.encoding" value="UTF-8" /> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.objectFactory.spring.autoWire" value="type" /> <constant name="struts.ui.theme" value="simple"></constant> <package name="film" namespace="/film" extends="struts-default"> <!-- 獲取所有影片 --> <action name="findFilm" class="filmAction" method="findFilm"> </action> <!-- 添加影片 --> <action name="insertFilm" class="filmAction" method="insertFilm"> </action> <!-- 獲取影片詳情 --> <action name="detailFilm" class="filmAction" method="detailFilm"> <result name="success">/manager/updateFilm.jsp</result> </action> <!-- 修改影片 --> <action name="updateFilm" class="filmAction" method="updateFilm"> </action> <!-- 刪除影片 --> <action name="deleteFilm" class="filmAction" method="deleteFilm"> </action> </package> </struts>
4、在FilmAction中加入outputJson(...)方法用於向客戶端輸出JSON數據,在findFilm、insertFilm、updateFilm、deleteFilm方法中使用outputJson,代碼如下:
package com.xxx.web.struts.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.xxx.pojo.Film;
import com.xxx.service.FilmService;
@SuppressWarnings("serial")
public class FilmAction extends ActionSupport implements ModelDriven<Film> {
//業務邏輯對象
@Autowired
private FilmService filmService;
//封裝查詢結果
private List<Film> filmList;
//封裝頁面提交的表單數據
private Film film = new Film();
/**
* 獲取所有的電影
* @return
* @throws Exception
*/
public String findFilm() throws Exception {
this.filmList = this.filmService.getAllFilm();
this.outputJson(this.filmList);
return null;
}
/**
* 根據影片ID獲取影片信息
* @return
* @throws Exception
*/
public String detailFilm() throws Exception {
int id = film.getId().intValue();
Film film = this.filmService.getFilmById(id);
this.film.setFname(film.getFname());
return SUCCESS;
}
/**
* 添加影片
* @return
* @throws Exception
*/
public String insertFilm() {
String result = "發佈影片成功!";
try {
this.filmService.insertFilm(film);
} catch (Exception e) {
result = "發佈影片失敗!";
}
this.outputJson(result);
return null;
}
/**
* 修改影片
* @return
* @throws Exception
*/
public String updateFilm() {
String result = "修改影片成功!";
try {
this.filmService.updateFilm(film);
} catch (Exception e) {
result = "修改影片失敗!";
}
this.outputJson(result);
return null;
}
/**
* 刪除影片
* @return
* @throws Exception
*/
public String deleteFilm() {
String result = "刪除影片成功!";
try {
int id = film.getId().intValue();
this.filmService.deleteFilm(id);
}catch (Exception e) {
result = "刪除影片失敗!";
}
this.outputJson(result);
return null;
}
/**
* 輸出JSON信息
* @param jsonObj
*/
private void outputJson(Object jsonObj){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
try {
PrintWriter pw = response.getWriter();
//將Java對象轉換爲JSON字符串
String gsonStr = new Gson().toJson(jsonObj);
//輸出JSON字符串
pw.print(gsonStr);
pw.flush();
pw.close();
} catch (IOException e) {
System.out.println("輸出GSON出錯:" + e);
}
}
public Film getModel() {
return film;
}
public List<Film> getFilmList() {
return filmList;
}
public void setFilmList(List<Film> filmList) {
this.filmList = filmList;
}
}
5、修改films.jsp頁面代碼,採用jQuery的ajax方式處理查詢、刪除,代碼如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@taglib uri="/struts-tags" prefix="s" %>
<%@ taglib prefix="security"
uri="http://www.springframework.org/security/tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>信息操作</title>
<link href="<%=basePath %>/js/jquery.loadmask.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=basePath %>/js/jquery.js"></script>
<script type="text/javascript" src="<%=basePath %>/js/jquery.form.js"></script>
<script type="text/javascript" src="<%=basePath %>/js/jquery.loadmask.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//採用jQuery的Ajax方式提交表單
$('#filmForm').submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(){
//提交表單處理期間,屏蔽整個窗口
$('#content').mask("正在提交數據,請稍候。");
//關閉提交按鈕
$('input[name=submit]').attr("disabled", true);
},
dataType: 'json',
//處理服務器響應的函數
success: function showResponse(responseObj, statusText, xhr, $form){
//取消窗口屏蔽
$('#content').unmask();
//打開提交按鈕
$('input[name=submit]').attr("disabled", false);
//將服務器返回的影片信息添加到表格中
var tableObj = document.getElementById('filmTable');
//清除表格中原有數據
var rowLength = tableObj.rows.length;
for(var i = 1; i < rowLength; i++){
tableObj.deleteRow(1);
}
//添加新的數據
for(var i = 0; i < responseObj.length; i++){
//讀取影片對象
var filmObj = responseObj[i];
//在表格中創建新行
var newRow = tableObj.insertRow(tableObj.rows.length);
//在新行中創建3個單元格
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
//給單元格加入數據
cell1.innerHTML = '' + (i + 1);
cell2.innerHTML = filmObj.fname;
cell3.innerHTML = '<a href="<%=basePath %>/film/detailFilm?id=' +
filmObj.id + '">[修改]</a> ' +
'<a href="javascript:deleteFilm(\'<%=basePath %>/film/deleteFilm?id=' +
filmObj.id + '\');">[刪除]</a>';
}
}
});
return false;
});
});
/*ajax方式提交刪除*/
function deleteFilm(deleteUrl){
if(confirm("是否刪除影片?")){
$.ajax({
type:'get',
url:deleteUrl,
data:null,
datatype:'json',
success: function(responseObj){
alert(responseObj);
}
});
}
}
</script>
</head>
<body>
<!-- 佈局DIV -->
<div id="content">
<s:form id="filmForm" action="/film/findFilm" method="post">
<s:submit value=" 獲取所有影片信息 "></s:submit>
</s:form>
<a href="<%=basePath %>/manager/insertFilm.jsp">添加影片信息</a><br />
<table id="filmTable" border="1" width="40%">
<tr>
<th>序號</th><th>影片名</th><th>操作</th>
</tr>
</table>
</div>
</body>
</html>
6、修改insertFilm.jsp頁面代碼,採用jQuery的ajax方式處理添加操作,代碼如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加影片</title>
<link href="<%=basePath %>/js/jquery.loadmask.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=basePath %>/js/jquery.js"></script>
<script type="text/javascript" src="<%=basePath %>/js/jquery.form.js"></script>
<script type="text/javascript" src="<%=basePath %>/js/jquery.loadmask.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//採用jQuery的Ajax方式提交表單
$('#insertForm').submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(){
//提交表單處理期間,屏蔽整個窗口
$('#content').mask("正在提交數據,請稍候。");
//關閉提交按鈕
$('input[name=submit]').attr("disabled", true);
},
dataType: 'json',
//處理服務器響應的函數
success: function showResponse(responseObj, statusText, xhr, $form){
//取消窗口屏蔽
$('#content').unmask();
//打開提交按鈕
$('input[name=submit]').attr("disabled", false);
//顯示服務器返回的信息
alert(responseObj);
}
});
return false;
});
});
</script>
</head>
<body>
<!-- 佈局DIV -->
<div id="content">
<s:form id="insertForm" action="/film/insertFilm" method="post">
<s:textfield name="fname" value="" />
<s:submit value=" 添加 "></s:submit>
</s:form>
<a href="<%=basePath %>/manager/films.jsp">[返回影片列表]</a>
</div>
</body>
</html>
7、修改updateFilm.jsp頁面代碼,採用jQuery的ajax方式處理修改操作,代碼如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改影片</title>
<link href="<%=basePath %>/js/jquery.loadmask.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=basePath %>/js/jquery.js"></script>
<script type="text/javascript" src="<%=basePath %>/js/jquery.form.js"></script>
<script type="text/javascript" src="<%=basePath %>/js/jquery.loadmask.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//採用jQuery的Ajax方式提交表單
$('#updateForm').submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(){
//提交表單處理期間,屏蔽整個窗口
$('#content').mask("正在提交數據,請稍候。");
//關閉提交按鈕
$('input[name=submit]').attr("disabled", true);
},
dataType: 'json',
//處理服務器響應的函數
success: function showResponse(responseObj, statusText, xhr, $form){
//取消窗口屏蔽
$('#content').unmask();
//打開提交按鈕
$('input[name=submit]').attr("disabled", false);
//顯示服務器返回的信息
alert(responseObj);
}
});
return false;
});
});
</script>
</head>
<body>
<!-- 佈局DIV -->
<div id="content">
<s:form id="updateForm" action="/film/updateFilm" method="post">
<s:hidden name="id" />
<s:textfield name="fname" />
<s:submit value=" 修改 "></s:submit>
</s:form>
<a href="<%=basePath %>/manager/films.jsp">[返回影片列表]</a>
</div>
</body>
</html>