ssh+json開發例項

阿木俠發表於2017-05-25

ssh整合+json實現增刪改查,一個標準的Demo,可以按這個模式開發,感覺蠻方便的,記錄下來,避免忘記。

資料庫:Oracle;平臺:myeclipse

專案結構:


POJO類和對映檔案:

package org.jvsun.pojo;

/**
 * UserInfo entity. @author MyEclipse Persistence Tools
 */

public class UserInfo implements java.io.Serializable {

	// Fields

	private Integer userId;
	private String userName;
	private String userPassword;
	private String userRemark;
	private String userEmail;
	private String userTel;

	// Constructors

	/** default constructor */
	public UserInfo() {
	}

	/** full constructor */
	public UserInfo(String userName, String userPassword, String userRemark,
			String userEmail, String userTel) {
		this.userName = userName;
		this.userPassword = userPassword;
		this.userRemark = userRemark;
		this.userEmail = userEmail;
		this.userTel = userTel;
	}

	// Property accessors

	public Integer getUserId() {
		return this.userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return this.userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPassword() {
		return this.userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public String getUserRemark() {
		return this.userRemark;
	}

	public void setUserRemark(String userRemark) {
		this.userRemark = userRemark;
	}

	public String getUserEmail() {
		return this.userEmail;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	public String getUserTel() {
		return this.userTel;
	}

	public void setUserTel(String userTel) {
		this.userTel = userTel;
	}

}

對映檔案:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="org.jvsun.pojo.UserInfo" table="USER_INFO" schema="ssh">
        <id name="userId" type="java.lang.Integer">
            <column name="USER_ID" precision="10" scale="0" />
            <generator class="sequence" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="USER_NAME" length="30" />
        </property>
        <property name="userPassword" type="java.lang.String">
            <column name="USER_PASSWORD" length="30" />
        </property>
        <property name="userRemark" type="java.lang.String">
            <column name="USER_REMARK" length="200" />
        </property>
        <property name="userEmail" type="java.lang.String">
            <column name="USER_EMAIL" length="30" />
        </property>
        <property name="userTel" type="java.lang.String">
            <column name="USER_TEL" length="15" />
        </property>
    </class>
</hibernate-mapping>

DAO介面類:

package org.jvsun.dao;

import java.util.List;

import org.jvsun.pojo.UserInfo;

public interface UserInfoDAO {
	public boolean doIns(UserInfo pojo);

	public boolean doDel(int sId);

	public boolean doUpd(UserInfo pojo);

	public UserInfo findById(int sId);

	public List<UserInfo> findByUserName(String userName, int currentPage,
			int pageSize);

	public int findCountByUserName(String userName);
}

DAO介面實現類

package org.jvsun.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.jvsun.dao.UserInfoDAO;
import org.jvsun.pojo.UserInfo;

public class UserInfoDAOImpl implements UserInfoDAO {
	SessionFactory sessionFactoy;

	public SessionFactory getSessionFactoy() {
		return sessionFactoy;
	}

	public void setSessionFactoy(SessionFactory sessionFactoy) {
		this.sessionFactoy = sessionFactoy;
	}

	public boolean doDel(int sId) {
		boolean bool = false;
		try {
			UserInfo user = (UserInfo) this.sessionFactoy.getCurrentSession()
					.get(UserInfo.class, sId);
			this.sessionFactoy.getCurrentSession().delete(user);
			bool = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bool;
	}

	public boolean doIns(UserInfo pojo) {
		boolean bool = false;
		try {
			this.sessionFactoy.getCurrentSession().save(pojo);
			bool = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bool;
	}

	public boolean doUpd(UserInfo pojo) {
		boolean bool = false;
		try {
			UserInfo user = (UserInfo) this.sessionFactoy.getCurrentSession()
					.get(UserInfo.class, pojo.getUserId());
			user.setUserEmail(pojo.getUserEmail());
			user.setUserName(pojo.getUserName());
			user.setUserPassword(pojo.getUserPassword());
			user.setUserRemark(pojo.getUserRemark());
			user.setUserTel(pojo.getUserTel());
			bool = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bool;
	}

	public UserInfo findById(int sId) {
		UserInfo user = null;
		try {
			user = (UserInfo) this.sessionFactoy.getCurrentSession().get(
					UserInfo.class, sId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	public List<UserInfo> findByUserName(String userName, int currentPage,
			int pageSize) {
		List<UserInfo> list = null;
		String hql = "from UserInfo where userName like '%" + userName + "%'";
		try {
			Query query = this.sessionFactoy.getCurrentSession().createQuery(
					hql);
			query.setFirstResult((currentPage - 1) * pageSize);
			query.setMaxResults(pageSize);
			list = query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public int findCountByUserName(String userName) {
		int count = 0;
		String hql = "select count(userId) from UserInfo where userName like '%"
				+ userName + "%'";
		try {
			Query query = this.sessionFactoy.getCurrentSession().createQuery(
					hql);
			count = Integer.parseInt(query.list().get(0).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

}

Services介面類

package org.jvsun.services;

import java.util.List;

import org.jvsun.pojo.UserInfo;

public interface UserInfoServices {
	public boolean doIns(UserInfo pojo);

	public boolean doDel(int sId);

	public boolean doUpd(UserInfo pojo);

	public UserInfo findById(int sId);

	public List<UserInfo> findByUserName(String userName, int currentPage,
			int pageSize);

	public int findCountByUserName(String userName);
}

Services介面實現類

package org.jvsun.services.impl;

import java.util.List;

import org.jvsun.dao.UserInfoDAO;
import org.jvsun.pojo.UserInfo;
import org.jvsun.services.UserInfoServices;

public class UserInfoServicesImpl implements UserInfoServices {
	UserInfoDAO dao;
	
	public UserInfoDAO getDao() {
		return dao;
	}

	public void setDao(UserInfoDAO dao) {
		this.dao = dao;
	}

	public boolean doDel(int sId) {
		return this.dao.doDel(sId);
	}

	public boolean doIns(UserInfo pojo) {
		return this.dao.doIns(pojo);
	}

	public boolean doUpd(UserInfo pojo) {
		return this.dao.doUpd(pojo);
	}

	public UserInfo findById(int sId) {
		return this.dao.findById(sId);
	}

	public List<UserInfo> findByUserName(String userName, int currentPage,
			int pageSize) {
		return this.dao.findByUserName(userName, currentPage, pageSize);
	}

	public int findCountByUserName(String userName) {
		return this.dao.findCountByUserName(userName);
	}
}

Action類

package org.jvsun.action;

import java.util.Iterator;
import java.util.List;

import org.jvsun.pojo.UserInfo;
import org.jvsun.services.UserInfoServices;

import com.opensymphony.xwork2.ActionSupport;

public class UserInfoAction extends ActionSupport {
	private static final long serialVersionUID = 2936921783530514074L;
	private UserInfoServices service;
	private String user_name;
	private int pagecur;
	private int pagesize;
	private String resultContent;
	private int id;
	private String username;
	private String password;
	private String remark;
	private String email;
	private String usertel;
	private UserInfo pojo;
	private int user_id;

	public UserInfoServices getService() {
		return service;
	}

	public void setService(UserInfoServices service) {
		this.service = service;
	}

	public int getUser_id() {
		return user_id;
	}

	public void setUser_id(int userId) {
		user_id = userId;
	}

	public UserInfo getPojo() {
		return pojo;
	}

	public void setPojo(UserInfo pojo) {
		this.pojo = pojo;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getUsertel() {
		return usertel;
	}

	public void setUsertel(String usertel) {
		this.usertel = usertel;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getResultContent() {
		return resultContent;
	}

	public void setResultContent(String resultContent) {
		this.resultContent = resultContent;
	}

	public String getUser_name() {
		return user_name;
	}

	public void setUser_name(String userName) {
		user_name = userName;
	}

	public int getPagecur() {
		return pagecur;
	}

	public void setPagecur(int pagecur) {
		this.pagecur = pagecur;
	}

	public int getPagesize() {
		return pagesize;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	public String findAll() {
		int count = this.service.findCountByUserName(user_name);
		List<UserInfo> list = this.service.findByUserName(user_name, pagecur,
				pagesize);
		StringBuffer sb = new StringBuffer();
		sb.append("<input type='hidden' id='count' value='" + count + "'>");
		sb.append("<table border='1'>");
		sb.append("<tr><th>使用者名稱</th><th>密碼</th><th>使用者角色</th><th>郵件</th><th>電話</th><th>操作</th</tr>");
		Iterator<UserInfo> it = list.iterator();
		while (it.hasNext()) {
			UserInfo pojo = it.next();
			sb.append("<tr><td>" + pojo.getUserName() + "</td><td>"
					+ pojo.getUserPassword() + "</td>" + "<td>"
					+ pojo.getUserRemark() + "</td><td>" + pojo.getUserEmail()
					+ "</td>" + "<td>" + pojo.getUserTel()
					+ "</td><td><a href='#' onclick='goUpd(" + pojo.getUserId()
					+ ")'>更新</a><a href='#' onclick='goDel(" + pojo.getUserId()
					+ ")'>刪除</a></td></tr>");
		}
		sb.append("</table>");
		this.setResultContent(sb.toString());
		return "success";
	}

	public String doDel() {
		boolean bool = this.service.doDel(id);
		this.setResultContent(Boolean.toString(bool));
		return "success";
	}

	public String doIns() {
		UserInfo pojo = new UserInfo(username, password, remark, email, usertel);
		boolean bool = this.service.doIns(pojo);
		this.setResultContent(Boolean.toString(bool));
		return "success";
	}

	public String findById() {
		UserInfo abc = this.service.findById(id);
		this.setPojo(abc);
		return "suc";
	}

	public String doUpd() {
		UserInfo pojo = new UserInfo(username, password, remark, email, usertel);
		pojo.setUserId(user_id);
		boolean bool = this.service.doUpd(pojo);
		this.setResultContent(Boolean.toString(bool));
		return "success";
	}
}

配置檔案有struts.xml和applicationContext.xml,沒有hibernate.xml,由spring代理hibernate,資料庫資訊全部配置在applicationContext.xml中。

ApplicationContext.xml配置資訊

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
						http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
						  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  	<!-- 資料庫資訊資料來源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="oracle.jdbc.driver.OracleDriver">
		</property>
		<property name="url"
			value="jdbc:oracle:thin:@localhost:1521:dalin">
		</property>
		<property name="username" value="ssh"></property>
		<property name="password" value="123"></property>
	</bean>
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
				<prop key="hibernate.show_sql">true</prop>
    			<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		<property name="mappingResources">
			<list>
				<value>org/jvsun/pojo/UserInfo.hbm.xml</value>
			</list>
		</property>
	</bean>
	<bean id="UserInfoAction" class="org.jvsun.action.UserInfoAction">
		<property name="service" ref="UserInfoServces"></property>
	</bean>
	<bean id="UserInfoServces" class="org.jvsun.services.impl.UserInfoServicesImpl">
		<property name="dao" ref="UserInfoDAO"></property>
	</bean>
	<bean id="UserInfoDAO" class="org.jvsun.dao.impl.UserInfoDAOImpl">
		<property name="sessionFactoy" ref="sessionFactory"></property>
	</bean>
	
	<bean id="myTxManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	
	<!--propagation="REQUIRED",事務的衍生方式為必需,即事務的傳播方式。有則用現成事務無則建立新的-->
	<tx:advice id="txAdvice" transaction-manager="myTxManager">
		<tx:attributes>
			<tx:method name="do*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	
	<aop:config>
		<aop:pointcut id="productServiceMethods"
			expression="execution(* org.jvsun.services.impl.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods" />
	</aop:config>
</beans>

Struts.xml配置檔案

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="test" namespace="/" extends="json-default">
		<action name="user_*" class="UserInfoAction" method="{1}">
			<result name="success" type="json">
				<param name="root">resultContent</param>
			</result>
			<result name="suc">/jsp/update.jsp</result>
		</action>
	</package>
</struts>    


接下來是前臺jsp頁面

Add.jsp


<%@page contentType="text/html; charset=utf-8"%>
<%
	String path = request.getContextPath();
%>
<html>
<head>
	<script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.js"></script>
</head>
	<body>
		<form action="" method="post" name="f">
			使用者名稱:
			<input type="text" name="username" />
			<br />
			密碼:
			<input type="password" name="password" />
			<br />
			描述:
			<input type="text" name="remark" />
			<br />
			郵箱:
			<input type="text" name="email" />
			<br />
			電話:
			<input type="text" name="usertel" />
			<br />
			<input type="button" value="確認" onclick="configR()">
			<input type="button" value="返回" onclick="back()">
		</form>
	</body>
	<script type="text/javascript">
var xmlhttp;
function createxmlhttp() {
	if (window.XMLHttpRequest) {//如果瀏覽器是類似於FireFox
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHttp");//使用的是IE的機制
	}
}
function configR() {
	var username = f.username.value;
	var password = f.password.value;
	var remark = f.remark.value;
	var email = f.email.value;
	var usertel = f.usertel.value;
	$(document).ready(function() {
		$.post("<%=path%>/user_doIns", {
			username : username,
			password : password,
			remark : remark,
			email : email,
			usertel : usertel
		}, function(data) {
			if (data.indexOf("true") != -1) {
				alert("新增成功");
				back();
			} else {
				alert("新增失敗");
				back();
			}
		});

	});

}
function back() {
	window.dialogArguments.query();//重新整理之前頁面	
	window.close();//關閉當前頁面
}
</script>
</html>

Update.jsp

<%@page contentType="text/html; charset=utf-8"%>
<% 
	String path =request.getContextPath();//取得系統的跟路徑
%>
<html>
<head>
	<script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.js"></script>
</head>

	<body>
		<form action="" method="post" name="f">
			<input type="hidden" name="user_id" value="${pojo.userId}"/>
			使用者名稱:
			<input type="text" name="username" value="${pojo.userName}"/>
			<br />
			密碼:
			<input type="password" name="password" value="${pojo.userPassword}"/>
			<br />
			描述:
			<input type="text" name="remark" value="${pojo.userRemark}"/>
			<br />
			郵箱:
			<input type="text" name="email" value="${pojo.userEmail}"/>
			<br />
			電話:
			<input type="text" name="usertel" value="${pojo.userTel}"/>
			<br />
			<input type="button" value="確認" onclick="configR()">
			<input type="button" value="返回" onclick="back()">
		</form>
	</body>
	<script type="text/javascript">
var xmlhttp;
function createxmlhttp() {
	if (window.XMLHttpRequest) {//如果瀏覽器是類似於FireFox
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHttp");//使用的是IE的機制
	}
}
function configR() {
	createxmlhttp();
	var user_id = f.user_id.value;
	var username = f.username.value;
	var password = f.password.value;
	var remark = f.remark.value;
	var email = f.email.value;
	var usertel = f.usertel.value;
	$(document).ready(function() {
		$.post("<%=path%>/user_doUpd", {
			username : username,
			password : password,
			remark : remark,
			email : email,
			usertel : usertel,
			user_id:user_id
		}, function(data) {
			if (data.indexOf("true") != -1) {
				alert("修改成功");
			} else {
				alert("修改失敗");
			}
		});

	});
	
}
function back() {
	window.dialogArguments.query();//重新整理之前頁面	
	window.close();//關閉當前頁面
}
</script>
</html>

Query.jsp

<%@page contentType="text/html; charset=utf-8" %>
<%
	String path = request.getContextPath();
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.js"></script>
</head>
<body>
	<center>
		<form action="" method="post" name="form1">
			使用者名稱:<input type="text" name="userName" id="userName">
			<input type="button" value="查詢" onclick="query(1)">
			<input type="button" value="新增" onclick="goIns()">
		</form>
	
	<hr/>
	<div id="showTable"></div>
	<hr/>
	<span id="page_message"></span>
	<input type="button" value="首頁" id="first" onclick="query(5)">
	<input type="button" value="上一頁" id="up"  onclick="query(2)">
	<input type="button" value="下一頁" id="end"  onclick="query(3)">
	<input type="button" value="尾頁" id="down"  onclick="query(4)">
	</center>
</body>
<script type="text/javascript">
var xmlhttp;
var user_name = "";//查詢條件
var count = 0;//總共有多少筆資料
var page_count = 0;//總共多少頁
var pagesize = 5;//一頁顯示多少比
var pagecur = 1;//當前第幾頁
query(1);
//go();

/*
	取得Ajax核心類的物件
*/
function createxmlhttp() {
	if (window.XMLHttpRequest) {//如果瀏覽器是類似於FireFox
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHttp");//使用的是IE的機制
	}
}
/*
	查詢
*/
function query(a) {
	createxmlhttp();//取得xmlhttp物件
	user_name = form1.userName.value;
	if(a==1){
		pagecur = 1;
	}else if(a==2){//查詢上一頁
		pagecur = pagecur-1;
	}else if(a==3){//查詢下一頁
		pagecur = pagecur+1;
	}else if(a==4){//最後一頁
		pagecur = page_count;
	}else if(a==5){//首頁
		pagecur = 1;
		//pagesize = document.getElementById("sel").value;
	}
	$(document).ready(function (){
		$.post("<%=path%>/user_findAll",{user_name:user_name,pagecur:pagecur,pagesize:pagesize},function(data){
			document.getElementById("showTable").innerHTML = data;
			calc();//計算總頁數,控制按鈕是否可用
		});
		
	});
}
/*
	按鈕控制
*/
function calc(){
	count = document.getElementById("count").value;
	if(count%pagesize==0){
		page_count = count/pagesize;
	}else{
		var v = count%pagesize;
		page_count = (count-v)/pagesize + 1;
		
		
	}
	if(pagecur == 1&&page_count!=1){
		document.getElementById("first").disabled = true;//按鈕不可用
		document.getElementById("up").disabled = true;
		document.getElementById("end").disabled = false;
		document.getElementById("down").disabled = false;
	}else if(pagecur == page_count&&page_count!=1){
		document.getElementById("first").disabled = false;
		document.getElementById("up").disabled = false;
		document.getElementById("end").disabled = true;
		document.getElementById("down").disabled = true;
	}else if(page_count==1){
		document.getElementById("first").disabled = true;
		document.getElementById("up").disabled = true;
		document.getElementById("end").disabled = true;
		document.getElementById("down").disabled = true;
	}else if(pagecur<page_count&&pagecur>1){
		document.getElementById("first").disabled = false;
		document.getElementById("up").disabled = false;
		document.getElementById("end").disabled = false;
		document.getElementById("down").disabled = false;
	}
	//document.getElementById("sel_page").options.length=0;
	//for(var i=1;i<=page_count;i++){
	//	document.getElementById("sel_page").options.add(new Option(i,i));
	//}
	document.getElementById("page_message").innerHTML="<font color='blue'>當前第"+pagecur+"頁  總共"+count+"筆,共"+page_count+"頁</font>";
	//document.getElementById("sel_page").value=pagecur;
}
/*
	新增
*/
function goIns(){
	window.open("add.jsp",window,"dialogHeight:300px;dialogWidth:280px;")
}
/*
	修改
*/
function goUpd(id_key){
	window.open("<%=path%>/user_findById?id="+id_key,window,"dialogHeight:300px;dialogWidth:280px;")
}
/*
	刪除
*/
function goDel(id_key){
	if(confirm("確認刪除?")){
		$(document).ready(function (){
		$.post("<%=path%>/user_doDel",{id:id_key},function(data){
			if(data.indexOf("true")!=-1){
				alert("刪除成功");
				query(0);
			}else{
				alert("刪除失敗");
			}
		});
		
	});
	}
	
}	
</script>
</html>

大部分人有了ssh所需的包,這裡是Json包的下載地址:http://download.csdn.net/detail/weixin_36380516/9851590

或者這個Demo的下載地址:https://github.com/guodalin8/SSHTest



改進一下,部分html頁面在action中寫讓程式碼看起來有點亂,現在把他扔回jsp裡,可以這樣寫:

action中

public String findAll() {  
        int count = this.services.findCountById(buyId);  
        List<Buy> list = this.services.findById(buyId, currentPage, pageSize);
        jsonA = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count", count);
        jsonA.add(jsonObject);
        for (int i = 0; i < list.size(); i++) {
			Buy pojo = list.get(i);
			JSONObject jsonO = new JSONObject();
			jsonO.put("buyId", pojo.getBuyId());
			jsonO.put("userid",pojo.getUserId());
			jsonO.put("buyDate",DataConverter.dataToString(DataConverter.toShortDate(pojo.getBuyDate()), "yyyy-MM-dd"));
			jsonA.add(jsonO);
		}
        
        return "succ";  
    }  


jsp獲取頁面:

$(document).ready(function (){
		$.post("<%=path%>/buy_findAll",{buyId:bid,currentPage:pagecur,pageSize:pagesize},
			function(data){//Servlet執行完之後執行方法,data表示的servlet返回資料內容
	 				var object = eval(data);//將字串轉換成json型別
	 				var showT = "<table>  <tr> <th>採購單編號</th> <th>採購員</th> <th>採購時間</th> <th>操作</th> </tr>";
	 				for(var i = 1;i<object.length;i++){
	 					var item = object[i];
	 					showT = showT+"<tr><td>"+item.buyId+"</td><td >"+item.userid+"</td><td>"+item.buyDate+"</td><td><a href='#' onclick='goUpd(" + item.buyId + ")'>更新</a><a href='#' onclick='goDel("
					+ item.buyId + ")'>刪除</a></td></tr>";
	 				}
	 				showT = showT + "</table>";
	 				$("#showTable").html(showT);
	 				count=object[0].count;
	 				calc();//計算總頁數,控制按鈕是否可用
	 			});
			
		});


使用json把結果集送到jsp頁面,然後取出,這樣程式碼就看著清爽很多



相關文章