前几天为了实现一个struts 的 ajax无刷新更新数据的例子,发现网上资料很少,很多已经过时或者链接都失效了
不过整合他们的资料,加上自己的研究,终于实现了效果
要求:1、各个学院提交学生数据到服务器,要求ajax 无刷新更新数据,
2、服务器端返回“更新成功”的提示窗口;
3、之后,使用jquery 更新input输入框的value值,为实现jquery 打印页面局部数据做准备。
此处使用struts2的第二种方法,(修改struts 配置文件,增加ajax package 的方式实现)
一、success.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@page import="org.apache.struts2.ServletActionContext"%>
<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@page import="qau.edu.entity.User"%>
<%
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="images/style.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="js/jquery-1.8.2.js"></script> //必须引入的jquery类库
</head>
<%
if (ServletActionContext.getRequest().getSession()
.getAttribute("user") == null) {
out.print("<script>alert('请登录');location.href='index.jsp'</script>");
}
%>
<body>
<div class="table">
<br />
<form action="#" method="post">
<input type="hidden" id="tuser" name="tongji.user" value="user" />
<div id="jsexport">
<br />
<p align="center">
<font size="+2">汇总结果</font>
</p>
<br />
<table border="3" align="center">
<tr>
<th width="120" rowspan="2" scope="col">学院名称</th>
<th width="86" rowspan="2" scope="col">学生总数</th>
<th width="60" rowspan="2" scope="col">返校学生数</th>
<th width="65" rowspan="2" scope="col">实习学生数</th>
<th colspan="6" scope="col">未返校学生数</th>
<th width="93" rowspan="2" scope="col">统计人签字</th>
<th width="101" rowspan="2" scope="col">学工班主任签字</th>
</tr>
<tr>
<td width="89">未购票/车次晚点</td>
<td width="40">生病</td>
<td width="50">家中有事</td>
<td width="83">休学 /退学/ 转学</td>
<td width="59">联系不上</td>
<td width="63">未返校合计</td>
</tr>
<tr>
<td style="text-align:center">${tongji.name}</td>
<td><input type="number" id="stunum"
style="border-style:none;width:90px" name="tongji.stunum"
value="${tongji.stunum}" readonly="readonly" /></td>
<td><input type="number" id="fxstu"
style="border-style:none;width:90px" name="tongji.fxstu"
value="${tongji.fxstu}" /></td>
<td><input type="number" id="sxstu"
style="border-style:none;width:90px" name="tongji.sxstu"
value="${tongji.sxstu}" /></td>
<td><input type="number" id="wgp"
style="border-style:none;width:90px" name="tongji.wgp"
value="${tongji.wgp}" /></td>
<td><input type="number" id="shengbing"
style="border-style:none;width:90px" name="tongji.shengbing"
value="${tongji.shengbing}" /></td>
<td><input type="number" id="youshi"
style="border-style:none;width:90px" name="tongji.youshi"
value="${tongji.youshi}" /></td>
<td><input type="number" id="xtzx"
style="border-style:none;width:90px" name="tongji.xtzx"
value="${tongji.xtzx}" /></td>
<td><input type="number" id="unconnect"
style="border-style:none;width:90px" name="tongji.unconnect"
value="${tongji.unconnect}" /></td>
<td><input type="number" id="wfxtotal"
style="border-style:none;width:90px" name="tongji.wfxtotal"
value="${tongji.wfxtotal}" readonly="readonly" /></td>
<td><input type="text" style="border-style:none;width:90px"
name="tongji.tjr" value="${tongji.tjr}" readonly="readonly" /></td>
<td><input type="text" style="border-style:none;width:90px"
name="tongji.bzr" value="${tongji.bzr}" readonly="readonly" /></td>
</tr>
</table>
</div>
<br />
<div style="margin:0 160px 0 0;float: right">
<input type="button" class="btn" value="提交" style="width:50px;height:25px" />
</div>
<br /> <br />
</form>
<div style="width:960px;margin: 0 auto;">
<p>
<font size="+1">未返校合计人数不包括实习生数,返校生数+实习学生数+未返校学生数=学生总数</font>
</p>
<br />
</div>
</div>
<script type="text/javascript">
$(function() {
//为返校统计
var func = function() {
var val = parseFloat($('#wgp').val())
+ parseFloat($('#shengbing').val())
+ parseFloat($('#youshi').val())
+ parseFloat($('#xtzx').val())
+ parseFloat($('#unconnect').val());
$('#wfxtotal').val(val);
};
//自动改变输入框事件(未返校)
$('#wgp,#shengbing,#youshi,#xtzx,#unconnect').change(func).keyup(
func);
//返校统计
var sumzong = function() {
var sumval = parseFloat($('#fxstu').val())
+ parseFloat($('#sxstu').val())
+ parseFloat($('#wfxtotal').val());
$('#stunum').val(sumval);
};
$(
'#fxstu,#sxstu,#wfxtotal,#wgp,#shengbing,#youshi,#xtzx,#unconnect')
.change(sumzong).keyup(sumzong);
});
</script>
<script type="text/javascript">
//JQuery防止退格键网页后退的实现代码
$(document).keydown(
function(e) {
var doPrevent;
if (e.keyCode == 8) {
var d = e.srcElement || e.target;
if (d.tagName.toUpperCase() == 'INPUT'
|| d.tagName.toUpperCase() == 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
} else
doPrevent = true;
} else
doPrevent = false;
if (doPrevent)
e.preventDefault();
});
</script>
<script type="text/javascript">
/* 提交结果,执行ajax */
function btn(){
var $btn = $("input.btn");//获取按钮元素
//给按钮绑定点击事件
$btn.bind("click",function(){
$.ajax({
url:"saveCollegeAction",//saveCollegeAge 需要用来处理ajax请求的action,save为处理的方法名,CollegeAge为action名
type:"POST",
data:{//设置数据源
stunum:$("#stunum").val(),
fxstu:$("#fxstu").val(),//这里不要加"," 不然会报错,而且根本不会提示错误地方
sxstu:$("#sxstu").val(),
wgp:$("#wgp").val(),
shengbing:$("#shengbing").val(),
youshi:$("#youshi").val(),
xtzx:$("#xtzx").val(),
unconnect:$("#unconnect").val(),
wfxtotal:$("#wfxtotal").val()
},
dataType:"json",//设置需要返回的数据类型
success:function(data){
//得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来
alert("更新成功!");
var d = eval("("+data.result+")");
$("#stunum").attr("value",""+d.stunuma+"");
$("#fxstu").attr("value",""+d.fxstua+"");
$("#sxstu").attr("value",""+d.sxstua+"");
$("#wgp").attr("value",""+d.wgpa+"");
$("#shengbing").attr("value",""+d.shengbinga+"");
$("#youshi").attr("value",""+d.youshia+"");
$("#xtzx").attr("value",""+d.xtzxa+"");
$("#unconnect").attr("value",""+d.unconnecta+"");
$("#wfxtotal").attr("value",""+d.wfxtotala+"");
//$("#stunum").text(""+d.stunuma+"");
},
error:function(data){
alert("系统异常,请稍后重试!");
}//这里不要加","
});
});
}
/* 页面加载完成,绑定事件 */
$(document).ready(function(){
btn();//点击提交,执行ajax
});
</script>
</body>
</html>
二、action页面----CollegeAction.java
这个是struts 分层中接收页面数据,并提交到 Dao类操作数据库的中间层
使用字段的get/set方法接手页面传值
package XXX.AAA.action;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import XXX.AAA.dao.CollegeDao;
import XXX.AAA.entity.Tongji;
import com.opensymphony.xwork2.Action;
public class CollegeAction implements Action {
private Tongji tongji;
//result 属性是用来ajax 返回结果集的,需要get/set方法
private String result;
public int stunum;
private int fxstu;
private int sxstu;
private int wgp;
private int shengbing;
private int youshi;
private int xtzx;
private int unconnect;
private int wfxtotal;
@Override
public String execute() throws Exception {
return getCollege();
}
public String getCollege() {
CollegeDao collegeDao = new CollegeDao();
tongji = collegeDao.getCollege();
return "success";
}
//ajax 更新数据
public String save() {
//创建map集合,获取ajax 数据
Map mapp = new HashMap();
mapp.put("stunuma",stunum);
mapp.put("fxstua",fxstu);
mapp.put("sxstua",sxstu);
mapp.put("wgpa",wgp);
mapp.put("shengbinga",shengbing);
mapp.put("youshia",youshi);
mapp.put("xtzxa",xtzx);
mapp.put("unconnecta",unconnect);
mapp.put("wfxtotala",wfxtotal);
if(ServletActionContext.getRequest().getSession().getAttribute("user")==null){
return "success";
}
CollegeDao collegeDao = new CollegeDao();
if (collegeDao.save(mapp) != 0) {
//tongji = collegeDao.getCollege();
//将map 解析到jason,方便数据返回
JSONObject json = JSONObject.fromObject(mapp);
result = json.toString();
//System.out.println(result);
return "success";
}else{
return "calcerror";
}
}
public Tongji getTongji() {
return tongji;
}
public void setTongji(Tongji tongji) {
this.tongji = tongji;
}
//ajax
public int getFxstu() {
return fxstu;
}
public void setFxstu(int fxstu) {
this.fxstu = fxstu;
}
public int getSxstu() {
return sxstu;
}
public void setSxstu(int sxstu) {
this.sxstu = sxstu;
}
public int getWgp() {
return wgp;
}
public void setWgp(int wgp) {
this.wgp = wgp;
}
public int getShengbing() {
return shengbing;
}
public void setShengbing(int shengbing) {
this.shengbing = shengbing;
}
public int getYoushi() {
return youshi;
}
public void setYoushi(int youshi) {
this.youshi = youshi;
}
public int getXtzx() {
return xtzx;
}
public void setXtzx(int xtzx) {
this.xtzx = xtzx;
}
public int getUnconnect() {
return unconnect;
}
public void setUnconnect(int unconnect) {
this.unconnect = unconnect;
}
public int getWfxtotal() {
return wfxtotal;
}
public void setWfxtotal(int wfxtotal) {
this.wfxtotal = wfxtotal;
}
public int getStunum() {
return stunum;
}
public void setStunum(int stunum) {
this.stunum = stunum;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
对于数据解析成json,需要导入jar包,大家可以根据myecplise 控制台报的错,添加相应的jar包
下面列出所使用的jar包,应该很全了
struts核心包:
json需要的包:
三、dao页面----CollegeDao.java
操作数据库
public class CollegeDao extends BaseDao implements ParameterAware {
private HttpServletRequest request;
public int save(Map mapp) {
getConnection();
int stunum = Integer.parseInt(mapp.get("stunuma").toString());
int fxstu = Integer.parseInt(mapp.get("fxstua").toString());
int sxstu = Integer.parseInt(mapp.get("sxstua").toString());
int wgp = Integer.parseInt(mapp.get("wgpa").toString());
int shengbing = Integer.parseInt(mapp.get("shengbinga").toString());
int youshi = Integer.parseInt(mapp.get("youshia").toString());
int xtzx = Integer.parseInt(mapp.get("xtzxa").toString());
int unconnect = Integer.parseInt(mapp.get("unconnecta").toString());
int wfxtotal = Integer.parseInt(mapp.get("wfxtotala").toString());
//System.out.println(stunum);
//System.out.println(fxstu);
//System.out.println(sxstu);
/*System.out.println(fxstu);
System.out.println(stunum);
System.out.println(stunum);
System.out.println(stunum);
System.out.println(stunum);*/
if ((wgp + shengbing + youshi + xtzx + unconnect == wfxtotal)
&& (fxstu + sxstu + wfxtotal == stunum)) {
try {
User user = (User) ActionContext.getContext().getSession()
.get("user");
pstm = conn
.prepareStatement("update xy_tongji set stunum=?,fxstu=?,sxstu=?,"
+ "wgp=?,shengbing=?,youshi=?,xtzx=?,unconnect=?, wfxtotal=?,"
+ "tjr=?,bzr=? where nameid=?");
pstm.setInt(1, stunum);
pstm.setInt(2, fxstu);
pstm.setInt(3, sxstu);
pstm.setInt(4, wgp);
pstm.setInt(5, shengbing);
pstm.setInt(6, youshi);
pstm.setInt(7, xtzx);
pstm.setInt(8, unconnect);
pstm.setInt(9, wfxtotal);
pstm.setString(10, "");
pstm.setString(11, "");
pstm.setInt(12, user.getId());
return pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
@Override
public void setParameters(Map<String, String[]> arg0) {
// TODO Auto-generated method stub
}
}
到此,ajax 成功