一.项目介绍
该项目是我在学习struts2,hibernate3,spring4时写的一个项目,是这三个框架整合的,分别有表单提交请求,Ajax提交请求,通过Get和Post方式提交,所以这个项目有三大块,表单用Get方式提交请求,表单用Post方式提交请求,Ajax提交请求。
二.项目目录结构
三.需要的JAR包
这是我用的所有JAR包,可以自己去官网上下载struts2和hibernate3和spring4的压缩包,在lib目录里有JAR包.
四.详细代码
1.表单用get方式提交请求(Post与Get方式提交代码一样,只是提交方式不一样,在这里只写Get方式提交的代码)
Jsp页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<title>ssh整合</title>
<base href="<%=basePath%>" />
<link type="text/css" rel="stylesheet" href="css/style.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div class="bodyDiv" align="center">
<a href="indexAjax.jsp">转到Ajax请求</a>
<a href="indexPost.jsp">转到Post请求</a>
<hr />
Get
<form action="" method="get" name="getForm">
<table class="buttonTable">
<tr>
<td><input type="submit" value="查询" onclick="selectFun()"></td>
<td><input type="submit" value="新增" onclick="insertFun()"></td>
<td><input type="submit" value="修改" onclick="updateFun()"></td>
<td><input type="submit" value="删除" onclick="deleteFun()"></td>
<td><input type="submit" value="搜索" onclick="queryFun()"></td>
</tr>
</table>
<table>
<tr height="50">
<td width="50">姓名:</td>
<td width="223">
<input type="text" name="people.name" id="name">
</td>
<td width="50">年龄:</td>
<td width="223">
<input type="text" name="people.age" id="age">
</td>
<td width="50">部门:</td>
<td width="173">
<input type="text" name="people.department" id="department">
<input type="hidden" name="people.id" id="number" value="">
<input type="hidden" name="people.deleteFlag" id="deleteFlag" value="false">
<input type="hidden" name="people.deleteTime" id="deleteTime" value="">
<input type="hidden" name="people.creationTime" id="creationTime" value="">
</td>
</tr>
</table>
</form>
<hr />
<br />
<table class="showTable">
<tr align="center" height="30">
<td width="50">选择</td>
<td width="50">序号</td>
<td width="80">姓名</td>
<td width="50">年龄</td>
<td width="150">部门</td>
<td width="100">删除标志</td>
<td width="200">删除时间</td>
<td width="200">创建时间</td>
</tr>
<c:forEach items="${list}" var="item">
<tr align="center" height="30">
<td><input name="radio" type="radio" onclick="radioFun()"></td>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.department}</td>
<td>${item.deleteFlag}</td>
<td>${item.deleteTime}</td>
<td>${item.creationTime}</td>
</tr>
</c:forEach>
<!-- <s:iterator value="#request.list">
<tr align="center" height="30">
<td><input name="radio" type="radio" onclick="radioFun()"></td>
<td><s:property value="%{id}" /></td>
<td><s:property value="%{name}" /></td>
<td><s:property value="%{age}" /></td>
<td><s:property value="%{department}" /></td>
<td><s:property value="%{deleteFlag}" /></td>
<td><s:property value="%{deleteTime}" /></td>
<td><s:property value="%{creationTime}" /></td>
</tr>
</s:iterator> -->
</table>
</div>
</body>
</html>
Js代码
function selectFun() {
document.getForm.action = "get/selectAction.do";
}
function insertFun() {
document.getForm.action = "get/insertAction.do";
var dateStr = getDate();
$("#creationTime").val(dateStr);
}
function updateFun() {
document.getForm.action = "get/updateAction.do";
}
function deleteFun() {
document.getForm.action = "get/deleteAction.do";
var dateStr = getDate();
$("#deleteTime").val(dateStr);
$("#deleteFlag").val(true);
}
function queryFun() {
document.getForm.action = "get/queryAction.do";
}
function getDate() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (hours < 10) {
var hours = "0" + hours;
}
if (minutes < 10) {
var minutes = "0" + minutes;
}
if (seconds < 10) {
var seconds = "0" + seconds;
}
var dateStr = year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
return dateStr;
}
function radioFun() {
var number = $("input:checked").parents("tr").find("td").eq(1).text();
$("#number").val(number);
var name = $("input:checked").parents("tr").find("td").eq(2).text();
$("#name").val(name);
var age = $("input:checked").parents("tr").find("td").eq(3).text();
$("#age").val(age);
var department = $("input:checked").parents("tr").find("td").eq(4).text();
$("#department").val(department);
var deleteFlag = $("input:checked").parents("tr").find("td").eq(5).text();
$("#deleteFlag").val(deleteFlag);
var deleteTime = $("input:checked").parents("tr").find("td").eq(6).text();
$("#deleteTime").val(deleteTime);
var creationTime = $("input:checked").parents("tr").find("td").eq(7).text();
$("#creationTime").val(creationTime);
}
css代码
@charset "UTF-8";
.bodyDiv {
width: 900px;
height: auto;
border: solid #BBB 1px;
padding: 20px;
margin: auto;
position: absolute;
left: 0;
right: 0;
}
.bodyDivPost {
width: 1080px;
height: auto;
border: solid #BBB 1px;
padding: 20px;
margin: auto;
position: absolute;
left: 0;
right: 0;
}
table {
cellspacing: 0px;
cellpadding: 0px;
border-width: 1px 0px 0px 1px;
border-collapse: collapse;
}
table td {
padding: 0;
border-width: 0px 1px 1px 0px;
}
.buttonTable tr {
height: 50px;
text-align: center;
}
.buttonTable td {
width: 154px;
}
.showTable {
border: solid #BBB 1px;
}
web.xml文件代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Struts 2</display-name>
<!-- 自定义Spring主配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:bean.xml</param-value>
</context-param>
<!-- 使用ContextLoaderListener初始化Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
log4j.properties文件代码
# Root logger option
log4j.rootLogger=INFO,stdout,FILE
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.Append=true
log4j.appender.FILE.File=../logs/log4jtest.log
log4j.appender.FILE.Threshold=INFO
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c -%F(%L) -%m%n
表结构
create table ssh_people
(
id serial,
name varchar,
age integer,
department varchar,
deleteFlag boolean,
deleteTime varchar,
creationTime varchar
)
struts.xml文件代码
<?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.devMode" value="true" />
<constant name="struts.action.extension" value="do,action," />
<constant name="struts.objectFactory" value="spring" />
<package name="get" namespace="/get" extends="struts-default">
<action name="selectAction" class="peopleAction" method="selectData">
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="insertAction" class="peopleAction" method="insertData">
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateAction" class="peopleAction" method="updateData">
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteAction" class="peopleAction" method="deleteData">
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="queryAction" class="peopleAction" method="queryData">
<result name="success">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
bean.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:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.highgo.ssh.dao,com.highgo.ssh.service,com.highgo.ssh.action"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="highgo123" />
</bean>
<!-- 注册sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingLocations">
<list>
<value>classpath:com/highgo/ssh/model/People.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>
</props>
</property>
</bean>
<bean id="peopleDao" class="com.highgo.ssh.dao.PeopleDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="peopleService" class="com.highgo.ssh.service.PeopleServiceImpl">
<property name="peopleDao" ref="peopleDao" />
</bean>
<bean id="peopleAction" class="com.highgo.ssh.action.PeopleAction"
scope="prototype">
<property name="peopleService" ref="peopleService" />
</bean>
</beans>
实体类People.java代码
package com.highgo.ssh.model;
public class People {
private int id;
private String name;
private int age;
private String department;
private boolean deleteFlag;
private String deleteTime;
private String creationTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public boolean getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(boolean deleteFlag) {
this.deleteFlag = deleteFlag;
}
public String getDeleteTime() {
return deleteTime;
}
public void setDeleteTime(String deleteTime) {
this.deleteTime = deleteTime;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public People() {
}
public People(Integer id, String name, int age, String department, boolean deleteFlag, String deleteTime,
String creationTime) {
this.id = id;
this.name = name;
this.age = age;
this.department = department;
this.deleteFlag = deleteFlag;
this.deleteTime = deleteTime;
this.creationTime = creationTime;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", department=" + department + ", deleteFlag="
+ deleteFlag + ", deleteTime=" + deleteTime + ", creationTime=" + creationTime + "]";
}
}
映射文件People.hbm.xml代码
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.highgo.ssh.model.People" table="ssh_people">
<id name="id" column="id" type="int">
<generator class="identity" />
<!-- 自动增长identity 采用数据库生成的主键 -->
<!-- sequence 需要主键值时可以调用seq_name.nextval或者seq_name.curval得到 -->
<!-- hilo 使用一个高/低位算法生成 -->
<!-- native 根据底层数据库的能力,从identity、sequence、hilo中选择一个,灵活性更强 -->
</id>
<property name="name" column="name" type="string" />
<property name="age" column="age" type="int" />
<property name="department" column="department" type="string" />
<property name="deleteFlag" column="deleteFlag" type="boolean" />
<property name="deleteTime" column="deleteTime" type="string" />
<property name="creationTime" column="creationTime" type="string" />
</class>
</hibernate-mapping>
PeopleAction.java代码
package com.highgo.ssh.action;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.highgo.ssh.model.People;
import com.highgo.ssh.service.PeopleServiceImpl;
public class PeopleAction {
Logger logger = LoggerFactory.getLogger(getClass());
private People people = new People();
// private People people;
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
private PeopleServiceImpl peopleService;
public PeopleServiceImpl getPeopleService() {
return peopleService;
}
public void setPeopleService(PeopleServiceImpl peopleService) {
this.peopleService = peopleService;
}
// insert data
public String insertData() {
String returnValue = "error";
try {
if (people == null) {
returnValue = "error";
} else {
peopleService.insertData(people);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// select data
public String selectData() {
String returnValue = "error";
boolean deleteFlag;
try {
if (people == null) {
deleteFlag = false;
} else {
deleteFlag = people.getDeleteFlag();
}
List<People> list = peopleService.getList(deleteFlag);
// 得到原生的request
HttpServletRequest hsr = ServletActionContext.getRequest();
hsr.setAttribute("list", list);
returnValue = "success";
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// update data
public String updateData() {
String returnValue = "error";
try {
if (people == null) {
returnValue = "error";
} else {
peopleService.updateData(people);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// deleted data
public String deleteData() {
String returnValue = "error";
try {
// int id = people.getId();
//
// // physically deleted data
// new PeopleService().deleteData(id);
if (people == null) {
returnValue = "error";
} else {
// logically deleted data
peopleService.deleteData(people);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// condition query data
public String queryData() {
String returnValue = "error";
try {
if (people == null) {
returnValue = "error";
} else {
String name = people.getName();
int age = people.getAge();
String department = people.getDepartment();
List<People> list = peopleService.getPeopleList(name, age, department);
// 得到原生的request
HttpServletRequest hsr = ServletActionContext.getRequest();
hsr.setAttribute("list", list);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
}
Service接口类PeopleService.java代码
package com.highgo.ssh.service;
import java.util.List;
import com.highgo.ssh.model.People;
public interface PeopleService {
public void insertData(People people) throws Exception;
public List<People> getList(boolean deleteFlag) throws Exception;
public void updateData(People people) throws Exception;
public void deleteData(People people) throws Exception;
public List<People> getPeopleList(String name, int age, String department) throws Exception;
}
Service接口实现类PeopleServiceImpl.java代码
package com.highgo.ssh.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.highgo.ssh.dao.PeopleDaoImpl;
import com.highgo.ssh.model.People;
public class PeopleServiceImpl implements PeopleService {
private PeopleDaoImpl peopleDao;
public PeopleDaoImpl getPeopleDao() {
return peopleDao;
}
public void setPeopleDao(PeopleDaoImpl peopleDao) {
this.peopleDao = peopleDao;
}
// insert data
public void insertData(People people) throws Exception {
peopleDao.insertData(people);
}
// select data
public List<People> getList(boolean deleteFlag) throws Exception {
List<People> list = peopleDao.getList(deleteFlag);
return list;
}
// update data
public void updateData(People people) throws Exception {
peopleDao.updateData(people);
}
// // physically deleted data
// public void deleteData(int id) {
//
// new PeopleDao().deleteData(id);
//
// }
// logically deleted data
public void deleteData(People people) throws Exception {
peopleDao.deleteData(people);
}
// condition query data
public List<People> getPeopleList(String name, int age, String department) throws Exception {
List<People> list = peopleDao.getPeopleList(name, age, department);
return list;
}
}
Dao接口类PeopleDao.java代码
package com.highgo.ssh.dao;
import java.util.List;
import com.highgo.ssh.model.People;
public interface PeopleDao {
public void insertData(People people) throws Exception;
public List<People> getList(boolean deleteFlag) throws Exception;
public void updateData(People people) throws Exception;
public void deleteData(People people) throws Exception;
public List<People> getPeopleList(String name, int age, String department) throws Exception;
}
Dao接口实现类PeopleDaoImpl.java代码
package com.highgo.ssh.dao;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.highgo.ssh.model.People;
public class PeopleDaoImpl implements PeopleDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session session = null;
private Transaction transaction = null;
private void init() {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
private void destory() {
transaction.commit();
session.close();
sessionFactory.close();
}
// insert data
public void insertData(People people) throws Exception {
init();
session.save(people);
destory();
}
// select data
public List<People> getList(boolean deleteFlag) throws Exception {
init();
String hql = "from People where deleteFlag = ? order by id";
Query query = session.createQuery(hql);
query.setParameter(0, deleteFlag);
List<People> list = query.list();
destory();
return list;
}
// update data
public void updateData(People people) throws Exception {
init();
session.update(people);
destory();
}
// // physically deleted data
// public void deleteData(int id) {
// init();
//
// People people = (People) session.get(People.class, id);
//
// session.delete(people);
//
// destory();
// }
// logically deleted data
public void deleteData(People people) throws Exception {
init();
session.update(people);
destory();
}
// condition query data
public List<People> getPeopleList(String name, int age, String department) throws Exception {
init();
String hql = "from People where name = ? and age = ? and department = ? order by id";
Query query = session.createQuery(hql);
query.setParameter(0, name);
query.setParameter(1, age);
query.setParameter(2, department);
List<People> list = query.list();
destory();
return list;
}
}
error.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>错误页面</title>
</head>
<body>
发生错误!
</body>
</html>
2.Ajax请求,在这里只写不一样的代码,一样的就不写了,一些变量名和类名不一样,只是命名的时候加了个Ajax,数据库名也不一样但结构一样。
Jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<title>ssh整合</title>
<base href="<%=basePath%>" />
<link type="text/css" rel="stylesheet" href="css/style.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div class="bodyDiv" align="center">
<a href="index.jsp">转到Get请求</a>
<a href="indexPost.jsp">转到Post请求</a>
<hr />
Ajax
<table class="buttonTableAjax">
<tr>
<td><input type="button" value="查询" onclick="selectAjaxFun()"></td>
<td><input type="button" value="新增" onclick="insertAjaxFun()"></td>
<td><input type="button" value="修改" onclick="updateAjaxFun()"></td>
<td><input type="button" value="删除" onclick="deleteAjaxFun()"></td>
<td><input type="button" value="搜索" onclick="searchAjaxFun()"></td>
</tr>
</table>
<table>
<tr height="50">
<td width="50">姓名:</td>
<td width="223">
<input type="text" name="nameAjax"id="nameAjax">
</td>
<td width="50">年龄:</td>
<td width="223">
<input type="text" name="ageAjax" id="ageAjax">
</td>
<td width="50">部门:</td>
<td width="173">
<input type="text" name="departmentAjax" id="departmentAjax">
<input type="hidden" name="idAjax" id="numberAjax" value="">
<input type="hidden" name="deleteFlagAjax" id="deleteFlagAjax" value="false">
<input type="hidden" name="deleteTimeAjax" id="deleteTimeAjax" value="">
<input type="hidden" name="creationTimeAjax" id="creationTimeAjax" value="">
</td>
</tr>
</table>
<hr />
<br />
<table id="showTableAjax">
<tr align="center" height="30">
<td width="50">选择</td>
<td width="50">序号</td>
<td width="80">姓名</td>
<td width="50">年龄</td>
<td width="150">部门</td>
<td width="100">删除标志</td>
<td width="200">删除时间</td>
<td width="200">创建时间</td>
</tr>
</table>
</div>
</body>
</html>
Js页面
function errorPopup(status) {
if (status == 404) {
alert("找不到页面");
} else if (status == 500) {
alert("内部服务器出错");
}
}
function getDate() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (hours < 10) {
var hours = "0" + hours;
}
if (minutes < 10) {
var minutes = "0" + minutes;
}
if (seconds < 10) {
var seconds = "0" + seconds;
}
var dateStr = year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
return dateStr;
}
function radioFun() {
var number = $("input:checked").parents("tr").find("td").eq(1).text();
$("#numberAjax").val(number);
var name = $("input:checked").parents("tr").find("td").eq(2).text();
$("#nameAjax").val(name);
var age = $("input:checked").parents("tr").find("td").eq(3).text();
$("#ageAjax").val(age);
var department = $("input:checked").parents("tr").find("td").eq(4).text();
$("#departmentAjax").val(department);
var deleteFlag = $("input:checked").parents("tr").find("td").eq(5).text();
$("#deleteFlagAjax").val(deleteFlag);
var deleteTime = $("input:checked").parents("tr").find("td").eq(6).text();
$("#deleteTimeAjax").val(deleteTime);
var creationTime = $("input:checked").parents("tr").find("td").eq(7).text();
$("#creationTimeAjax").val(creationTime);
}
function PeopleAjax() {
var peopleAjax = {
"peopleAjax.nameAjax" : $("#nameAjax").val(),
"peopleAjax.ageAjax" : $("#ageAjax").val(),
"peopleAjax.departmentAjax" : $("#departmentAjax").val(),
"peopleAjax.idAjax" : $("#numberAjax").val(),
"peopleAjax.deleteFlagAjax" : $("#deleteFlagAjax").val(),
"peopleAjax.deleteTimeAjax" : $("#deleteTimeAjax").val(),
"peopleAjax.creationTimeAjax" : $("#creationTimeAjax").val()
};
return peopleAjax;
}
function selectAjaxFun() {
$("#deleteFlagAjax").val(false);
var peopleAjax = PeopleAjax();
$.ajax({
url : "Ajax/selectAction.do",
type : "post",
data : peopleAjax,
success : function(resp) {
// console.log(resp);
$("#showTableAjax tr:gt(0)").remove();
var dataArray = JSON.parse(resp);
for (var i = 0; i < dataArray.length; i++) {
var str = '<tr align="center" height="30">'
+ '<td><input name="radio" type="radio" onclick="radioFun()"></td><td>'
+ dataArray[i].idAjax + '</td><td>'
+ dataArray[i].nameAjax + '</td><td>'
+ dataArray[i].ageAjax + '</td><td>'
+ dataArray[i].departmentAjax + '</td><td>'
+ dataArray[i].deleteFlagAjax + '</td><td>'
+ dataArray[i].deleteTimeAjax + '</td><td>'
+ dataArray[i].creationTimeAjax + '</td></tr>';
$("#showTableAjax").append(str);
}
},
error : function(resp) {
var status = resp.status;
errorPopup(status);
}
});
}
function insertAjaxFun() {
$("#deleteFlagAjax").val(false);
var dateStr = getDate();
$("#creationTimeAjax").val(dateStr);
var peopleAjax = PeopleAjax();
$.ajax({
url : "Ajax/insertAction.do",
type : "post",
data : peopleAjax,
success : function(resp) {
selectAjaxFun();
},
error : function(resp) {
var status = resp.status;
errorPopup(status);
}
});
}
function updateAjaxFun() {
$("#deleteFlagAjax").val(false);
var peopleAjax = PeopleAjax();
$.ajax({
url : "Ajax/updateAction.do",
type : "post",
data : peopleAjax,
success : function(resp) {
selectAjaxFun();
},
error : function(resp) {
var status = resp.status;
errorPopup(status);
}
});
}
function deleteAjaxFun() {
$("#deleteFlagAjax").val(true);
var dateStr = getDate();
$("#deleteTimeAjax").val(dateStr);
var peopleAjax = PeopleAjax();
$.ajax({
url : "Ajax/deleteAction.do",
type : "post",
data : peopleAjax,
success : function(resp) {
selectAjaxFun();
},
error : function(resp) {
var status = resp.status;
errorPopup(status);
}
});
}
function searchAjaxFun() {
var peopleAjax = PeopleAjax();
$("#deleteFlagAjax").val(false);
$.ajax({
url : "Ajax/queryAction.do",
type : "post",
data : peopleAjax,
success : function(resp) {
// console.log(resp);
$("#showTableAjax tr:gt(0)").remove();
var dataArray = JSON.parse(resp);
for (var i = 0; i < dataArray.length; i++) {
var str = '<tr align="center" height="30">'
+ '<td><input name="radio" type="radio" onclick="radioFun()"></td><td>'
+ dataArray[i].idAjax + '</td><td>'
+ dataArray[i].nameAjax + '</td><td>'
+ dataArray[i].ageAjax + '</td><td>'
+ dataArray[i].departmentAjax + '</td><td>'
+ dataArray[i].deleteFlagAjax + '</td><td>'
+ dataArray[i].deleteTimeAjax + '</td><td>'
+ dataArray[i].creationTimeAjax + '</td></tr>';
$("#showTableAjax").append(str);
}
},
error : function(resp) {
var status = resp.status;
errorPopup(status);
}
});
}
struts.xml文件代码
<?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.devMode" value="true" />
<constant name="struts.action.extension" value="do,action," />
<constant name="struts.objectFactory" value="spring" />
<package name="Ajax" namespace="/Ajax" extends="json-default">
<action name="selectAction" class="peopleAjaxAction" method="selectData">
<result name="success" type="json">
<param name="root">result</param>
</result>
</action>
<action name="insertAction" class="peopleAjaxAction" method="insertData">
<result name="success">/indexAjax.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateAction" class="peopleAjaxAction" method="updateData">
<result name="success">/indexAjax.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteAction" class="peopleAjaxAction" method="deleteData">
<result name="success">/indexAjax.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="queryAction" class="peopleAjaxAction" method="queryData">
<result name="success" type="json">
<param name="root">result</param>
</result>
</action>
</package>
</struts>
PeopleAjaxAction.java代码
package com.highgo.ssh.action;
import java.util.List;
import org.slf4j.*;
import net.sf.json.JSONArray;
import com.highgo.ssh.model.PeopleAjax;
import com.highgo.ssh.service.PeopleAjaxServiceImpl;
public class PeopleAjaxAction {
Logger logger = LoggerFactory.getLogger(getClass());
private PeopleAjax peopleAjax = new PeopleAjax();
public PeopleAjax getPeopleAjax() {
return peopleAjax;
}
public void setPeopleAjax(PeopleAjax peopleAjax) {
this.peopleAjax = peopleAjax;
}
private PeopleAjaxServiceImpl peopleAjaxService;
public PeopleAjaxServiceImpl getPeopleAjaxService() {
return peopleAjaxService;
}
public void setPeopleAjaxService(PeopleAjaxServiceImpl peopleAjaxService) {
this.peopleAjaxService = peopleAjaxService;
}
private String result;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
// insert data
public String insertData() {
String returnValue = "error";
try {
if (peopleAjax == null) {
returnValue = "error";
} else {
peopleAjaxService.insertData(peopleAjax);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// select data
public String selectData() {
String returnValue = "error";
boolean deleteFlag;
try {
if (peopleAjax == null) {
deleteFlag = false;
} else {
deleteFlag = peopleAjax.getDeleteFlagAjax();
}
List<PeopleAjax> list = peopleAjaxService.getList(deleteFlag);
result = JSONArray.fromObject(list).toString();
returnValue = "success";
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// update data
public String updateData() {
String returnValue = "error";
try {
if (peopleAjax == null) {
returnValue = "error";
} else {
peopleAjaxService.updateData(peopleAjax);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// deleted data
public String deleteData() {
String returnValue = "error";
try {
// int id = peopleAjax.getId();
//
// // physically deleted data
// new PeopleAjaxService().deleteData(id);
// logically deleted data
if (peopleAjax == null) {
returnValue = "error";
} else {
peopleAjaxService.deleteData(peopleAjax);
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
// condition query data
public String queryData() {
String returnValue = "error";
try {
if (peopleAjax == null) {
returnValue = "error";
} else {
String name = peopleAjax.getNameAjax();
int age = peopleAjax.getAgeAjax();
String department = peopleAjax.getDepartmentAjax();
List<PeopleAjax> list = peopleAjaxService.getPeopleList(name, age, department);
result = JSONArray.fromObject(list).toString();
returnValue = "success";
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
returnValue = "error";
}
return returnValue;
}
}
五.学习总结
学习了ssh整合,感觉写代码容易了很多,但是很多地方是需要注意的,并且好多地方因为不知道内部是怎么操作的,所以不太好理解,所以要认真学习。