Hibernate学习项目总结

一.项目介绍

这个项目是在我学了struts2和hibernate3之后做的,是用这两个框架整合的,分别有表单提交请求,Ajax提交请求,通过Get和Post方式提交,所以这个项目有三大块,表单用Get方式提交请求,表单用Post方式提交请求,Ajax提交请求。

二.项目目录结构

在这里插入图片描述
在这里插入图片描述

三.需要的JAR包

在这里插入图片描述
在这里插入图片描述
这是我用的所有JAR包,可以自己去官网上下载struts2和hibernate的压缩包,在lib目录里有JAR包,如果不想自己下载,我上传了资源可以去下载,地址:https://download.csdn.net/download/sun_ting_chuan/10830515.

四.详细代码

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;
}

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>
   
   <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," />

	<package name="get" namespace="/get" extends="struts-default">

		<action name="selectAction" class="com.highgo.ssh.action.PeopleAction"
			method="selectData">

			<result name="success">/index.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="insertAction" class="com.highgo.ssh.action.PeopleAction"
			method="insertData">

			<result name="success">/index.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="updateAction" class="com.highgo.ssh.action.PeopleAction"
			method="updateData">

			<result name="success">/index.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="deleteAction" class="com.highgo.ssh.action.PeopleAction"
			method="deleteData">

			<result name="success">/index.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="queryAction" class="com.highgo.ssh.action.PeopleAction"
			method="queryData">

			<result name="success">/index.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

	</package>
</struts>
hibernate.cfg.xml文件代码
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!-- 数据库连接 -->
		<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
		<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property>
		<property name="hibernate.connection.username">postgres</property>
		<property name="hibernate.connection.password">highgo123</property>

		<!-- 数据库方言,为被选择的数据生成适当的SQL -->
		<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

		<!-- 操作数据库时,向控制台打印SQL语句 -->
		<property name="hibernate.show_sql">true</property>
		
		<!-- 打印SQL语句之前,将SQL语句格式化 -->
		<property name="hibernate.format_sql">true</property>

		 <!-- hbm2ddl.auto: 生成表结构的策略配置
             update(最常用的取值): 如果当前数据库中不存在表结构,那么自动创建表结构。
						                    如果存在表结构,并且表结构与实体一致,那么不做修改。
						                    如果存在表结构,并且表结构与实体不一致,那么会修改表结构.会保留原有列。
             create(很少):无论是否存在表结构.每次启动Hibernate都会重新创建表结构.(数据会丢失)。
             create-drop(极少): 无论是否存在表结构.每次启动Hibernate都会重新创建表结构.每次Hibernate运行结束时,删除表结构.
             validate(很少):不会自动创建表结构.也不会自动维护表结构.Hibernate只校验表结构. 如果表结构不一致将会抛出异常.
          -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 事务自动提交  -->
        <property name="hibernate.connection.autocommit">true</property>
		

		<!-- 注册映射文件 -->
		<mapping class="com.highgo.ssh.model.People" />
		<mapping resource="com/highgo/ssh/model/PeoplePost.hbm.xml" />
		<mapping resource="com/highgo/ssh/model/PeopleAjax.hbm.xml" />
	</session-factory>
</hibernate-configuration>
实体类People.java代码
package com.highgo.ssh.model;

import javax.persistence.*;

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 + "]";
	}
}
PeopleAction.java代码
package com.highgo.ssh.action;

import java.util.*;
import org.slf4j.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

import com.highgo.ssh.model.People;
import com.highgo.ssh.service.PeopleService;

public class PeopleAction {

	Logger logger = LoggerFactory.getLogger(getClass());

	private People people;

	public People getPeople() {
		return people;
	}

	public void setPeople(People people) {
		this.people = people;
	}

	// 添加数据
	public String insertData() {

		String returnValue = "error";

		try {
			if (people == null) {

				returnValue = "error";

			} else {

				new PeopleService().insertData(people);

				returnValue = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 查询数据
	public String selectData() {

		String returnValue = "error";

		boolean deleteFlag;
		try {

			if (people == null) {

				deleteFlag = false;

			} else {

				deleteFlag = people.getDeleteFlag();
			}

			List<People> list = new PeopleService().getList(deleteFlag);

			// 得到原生的request
			HttpServletRequest hsr = ServletActionContext.getRequest();

			hsr.setAttribute("list", list);

			returnValue = "success";

		} catch (Exception e) {

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 修改数据
	public String updateData() {

		String returnValue = "error";

		try {
			if (people == null) {

				returnValue = "error";

			} else {

				new PeopleService().updateData(people);

				returnValue = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 删除数据
	public String deleteData() {

		String returnValue = "error";

		try {
			// int id = people.getId();
			//
			// // 物理删除
			// new PeopleService().deleteData(id);

			if (people == null) {

				returnValue = "error";

			} else {
				// 逻辑删除
				new PeopleService().deleteData(people);

				returnValue = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 条件查询数据
	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 = new 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;
	}
}
PeopleService.java代码
package com.highgo.ssh.service;

import java.util.List;
import com.highgo.ssh.dao.PeopleDao;
import com.highgo.ssh.model.People;

public class PeopleService {

	// 添加数据
	public void insertData(People people) throws Exception {

		new PeopleDao().insertData(people);
	}

	// 查询数据
	public List<People> getList(boolean deleteFlag) throws Exception {

		List<People> list = new PeopleDao().getList(deleteFlag);

		return list;
	}

	// 修改数据
	public void updateData(People people) throws Exception {

		new PeopleDao().updateData(people);

	}

	// // 物理删除数据
	// public void deleteData(int id) {
	//
	// new PeopleDao().deleteData(id);
	//
	// }

	// 逻辑删除数据
	public void deleteData(People people) throws Exception {

		new PeopleDao().deleteData(people);

	}

	// 条件查询
	public List<People> getPeopleList(String name, int age, String department) throws Exception {

		List<People> list = new PeopleDao().getPeopleList(name, age, department);

		return list;
	}
}
PeopleDao.java代码
package com.highgo.ssh.dao;

import java.util.*;
import org.hibernate.*;
import org.hibernate.service.*;
import org.hibernate.cfg.Configuration;

import com.highgo.ssh.model.People;

public class PeopleDao {

	private Configuration configuration = null;
	private ServiceRegistry serviceRegistry = null;

	private SessionFactory sessionFactory = null;
	private Session session = null;
	private Transaction transaction = null;

	public PeopleDao() {
		configuration = new Configuration().configure();
		serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
				.buildServiceRegistry();
	}

	private void init() {
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}

	private void destory() {
		transaction.commit();
		session.close();
		sessionFactory.close();
	}

	// 添加数据
	public void insertData(People people) throws Exception {

		init();

		session.save(people);

		destory();
	}

	// 查询数据
	public List<People> getList(boolean deleteFlag) throws Exception {
		List<People> list = new ArrayList<People>();

		init();

		String hql = "from com.highgo.ssh.model.People where deleteFlag = ? order by id";
		Query query = session.createQuery(hql);
		query.setParameter(0, deleteFlag);
		list = query.list();

		destory();

		return list;
	}

	// 修改数据
	public void updateData(People people) throws Exception {
		init();

		session.update(people);

		destory();
	}

	// // 物理删除数据
	// public void deleteData(int id) {
	// init();
	//
	// People people = (People) session.get(People.class, id);
	//
	// session.delete(people);
	//
	// destory();
	// }

	// 逻辑删除数据
	public void deleteData(People people) throws Exception {
		init();

		session.update(people);

		destory();
	}

	// 条件查询
	public List<People> getPeopleList(String name, int age, String department) throws Exception {
		List<People> list = new ArrayList<People>();

		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 = query.list();

		destory();

		return list;
	}
}
映射文件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="native" />
		</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>
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>
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.PeopleAjaxService;

public class PeopleAjaxAction {

	Logger logger = LoggerFactory.getLogger(getClass());

	private PeopleAjax peopleAjax;
	private String result;

	public PeopleAjax getPeopleAjax() {
		return peopleAjax;
	}

	public void setPeopleAjax(PeopleAjax peopleAjax) {
		this.peopleAjax = peopleAjax;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	// 添加数据
	public String insertData() {

		String returnValue = "error";

		try {
			if (peopleAjax == null) {

				returnValue = "error";

			} else {
				new PeopleAjaxService().insertData(peopleAjax);

				returnValue = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 查询数据
	public String selectData() {

		String returnValue = "error";

		boolean deleteFlag;

		try {

			if (peopleAjax == null) {

				deleteFlag = false;

			} else {

				deleteFlag = peopleAjax.getDeleteFlagAjax();
			}

			List<PeopleAjax> list = new PeopleAjaxService().getList(deleteFlag);

			result = JSONArray.fromObject(list).toString();

			returnValue = "success";

		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 修改数据
	public String updateData() {

		String returnValue = "error";

		try {
			if (peopleAjax == null) {

				returnValue = "error";

			} else {
				new PeopleAjaxService().updateData(peopleAjax);

				returnValue = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 删除数据
	public String deleteData() {

		String returnValue = "error";

		try {
			// int id = peopleAjax.getId();
			//
			// // 物理删除
			// new PeopleAjaxService().deleteData(id);

			// 逻辑删除

			if (peopleAjax == null) {

				returnValue = "error";

			} else {
				new PeopleAjaxService().deleteData(peopleAjax);

				returnValue = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();

			logger.info(e.getMessage());

			returnValue = "error";
		}
		return returnValue;
	}

	// 条件查询数据
	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 = new 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;
	}
}
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," />

	<package name="Ajax" namespace="/Ajax" extends="json-default">

		<action name="selectAction" class="com.highgo.ssh.action.PeopleAjaxAction"
			method="selectData">

			<result name="success" type="json"></result>

		</action>

		<action name="insertAction" class="com.highgo.ssh.action.PeopleAjaxAction"
			method="insertData">

			<result name="success">/indexAjax.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="updateAction" class="com.highgo.ssh.action.PeopleAjaxAction"
			method="updateData">

			<result name="success">/indexAjax.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="deleteAction" class="com.highgo.ssh.action.PeopleAjaxAction"
			method="deleteData">

			<result name="success">/indexAjax.jsp</result>
			<result name="error">/error.jsp</result>

		</action>

		<action name="queryAction" class="com.highgo.ssh.action.PeopleAjaxAction"
			method="queryData">

			<result name="success" type="json"></result>

		</action>

	</package>

</struts>
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);
//			 console.log(resp.result);
			
			$("#showTableAjax tr:gt(0)").remove();
			
			var dataArray = JSON.parse(resp.result);
			
			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);
//			console.log(resp.result);
			
			$("#showTableAjax tr:gt(0)").remove();
			
			var dataArray = JSON.parse(resp.result);
			
			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);
		}
	});
}

五.学习总结

已经学习了两个框架了,感觉代码越来越少,但是好多地方不好理解,所以要想学好,就要仔细研究,我出的问题一般都是因为jar包的问题,所以代码虽然少了,但更要仔细认真。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值