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 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 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 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,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>
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",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,"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,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"; }
$(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页面,然后取出,这样代码就看着清爽很多 原文链接:https://www.f2er.com/json/288909.html