Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)
程序员文章站
2022-05-03 15:18:04
...
1、基本的环境
1.1、开发工具:Myeclipse 2017 CI
1.2、struts2:struts-2.3.34
1.3、hibernate:hibernate-release-5.2.10.Final
1.4、tomcat: apache-tomcat-8.5.15
1.5、mysql驱动:mysql-connector-java-5.1.42-bin
1.7、C3P0数据源
1.8、数据库MYSQL5.1以上
2、搭建基本strust2运行环境
2.1、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2.2、在src目录下创建strust.xml文件(这个是最终的strust.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<bean name="employeeDao" type="com.splend.crud.dao.EmployeeDao"
class="com.splend.crud.dao.EmployeeDaoImpl"></bean>
<bean name="employeeService" type="com.splend.crud.service.EmployeeService"
class="com.splend.crud.service.EmployeeServiceImpl"></bean>
<!-- Overwrite Convention -->
<package name="default" extends="struts-default" namespace="/">
<interceptors>
<interceptor-stack name="splend">
<interceptor-ref name="paramsPrepareParamsStack">
<param name="prepare.alwaysInvokePrepare">false</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="splend"></default-interceptor-ref>
<action name="emp-*" class="com.splend.crud.handler.EmployeeAction"
method="{1}">
<result name="success" type="redirectAction">emp-list</result>
<result name="{1}">/emp-{1}.jsp</result>
</action>
<action name="test" class="com.splend.crud.handler.HelloWorld">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
3、用hibernate编写dao层
3.1、写一个Employee的javabean
package com.splend.crud.entity;
public class Employee {
private Integer employeeId;
private String firstName;
private String lastName;
private String email;
public Employee() {
}
public Employee(Integer employeeId, String firstName, String lastName, String email) {
super();
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3.2、在Employee.java类目录下创建Employee.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 package="com.splend.crud.entity">
<class name="Employee" table="Employee">
<id name="employeeId" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="firstName" type="java.lang.String">
<column name="firstName" />
</property>
<property name="lastName" type="java.lang.String">
<column name="lastName" />
</property>
<property name="email" type="java.lang.String">
<column name="email" />
</property>
</class>
</hibernate-mapping>
3.3、src目录下创建hibernate.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- configure the database setting -->
<property name="connection.username">splend</property>
<property name="connection.password">1230</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/sh</property>
<!-- configure the hibernate setting -->
<!-- transaction is supported by org.hibernate.dialect.MySQLInnoDBDialect -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- show sql in the console -->
<property name="show_sql">true</property>
<!-- fromat_sql -->
<property name="format_sql">true</property>
<!-- create and update the database automaticlly -->
<property name="hbm2ddl.auto">update</property>
<!-- 事务隔离级别 -->
<property name="connection.isolation">2</property>
<!-- 删除对象后使其 OID 为null -->
<property name="use_identifier_roolback">true</property>
<!-- C3P0数据源设置 -->
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.idle_test_period">2000</property>
<property name="hibernate.c3p0.timeout">2000</property>
<property name="hibernate.c3p0.acquire_increment"></property>
<property name="hibernate.c3p0.max_statements">10</property>
<!-- 对oracle有效,mysql无效 -->
<!-- 设定JDBC的 statement 读取数据时候每次从数据库中取出的记录条数 -->
<property name="hibernate.jdbc.fetch_size">100</property>
<!-- 设定对数据批量删除 批量更新和批量插入时候的批次大小 -->
<property name="jdbc.batch_size">30</property>
<!-- 指定map -->
<mapping resource="com/splend/crud/entity/Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
3.4、编写BaseDao<T>的泛型接口
package com.splend.crud.dao;
import java.util.List;
public interface BaseDao<T> {
T get(T entity);
/**
* 获取全部列表
*
* @return 所有T对象
*/
List<T> getAll();
/**
* 持久化实例
* @param entity
* @return 成功返回true,失败返回false
*/
boolean save(T entity);
/**
* 更新一个T实例
* @param entity
* @return 更新成功返回True否则false
*/
boolean update(T entity);
/**
* 删除T实例
* @param entity
* @return 成功返回true,失败false
*/
boolean delete(T entity);
}
3.5、EmployeeDao.java
package com.splend.crud.dao;
import com.splend.crud.entity.Employee;
public interface EmployeeDao extends BaseDao<Employee> {
}
3.6、编写EmployeeDaoImpl实现类
package com.splend.crud.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import com.splend.crud.entity.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
public EmployeeDaoImpl() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
session = sessionFactory.openSession();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
e.printStackTrace();
System.out.println("EmployeeDaoImpl error");
}finally {
if (session != null) {
session.close();
}
}
}
@Override
public Employee get(Employee entity) {
Employee employee = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
employee = session.find(Employee.class, entity.getEmployeeId());
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
employee = null;
e.printStackTrace();
System.out.println("public Employee get(Employee entity) error");
}finally {
if (session != null) {
session.close();
}
}
return employee;
}
@SuppressWarnings("unchecked")
@Override
public List<Employee> getAll() {
List<Employee> employees = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
employees = session.createQuery("FROM Employee").list();
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
employees = null;
e.printStackTrace();
System.out.println("public List<Employee> getAll error");
}finally {
if (session != null) {
session.close();
}
}
return employees;
}
@Override
public boolean save(Employee entity) {
boolean result = false;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(entity);
transaction.commit();
result = true;
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
result = false;
e.printStackTrace();
System.out.println("public boolean save(Employee entity) error");
}finally {
if (session != null) {
session.close();
}
}
return result;
}
@Override
public boolean update(Employee entity) {
boolean result = false;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.saveOrUpdate(entity);
transaction.commit();
result = true;
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
result = false;
e.printStackTrace();
System.out.println("public boolean update(Employee entity) error");
}finally {
if (session != null) {
session.close();
}
}
return result;
}
@Override
public boolean delete(Employee entity) {
boolean result = false;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.delete(entity);
transaction.commit();
result = true;
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
result = false;
e.printStackTrace();
System.out.println("public boolean delete(Employee entity) error");
}finally {
if (session != null) {
session.close();
}
}
return result;
}
}
3.7 编写EmployeeService
package com.splend.crud.service;
import java.util.List;
import com.splend.crud.entity.Employee;
public interface EmployeeService {
Employee get(Employee employee);
List<Employee> getEmployees();
boolean save(Employee employee);
boolean update(Employee employee);
boolean delete(Employee employee);
}
3.8 编写EmployeeServiceImpl.java
package com.splend.crud.service;
import java.util.List;
import com.opensymphony.xwork2.inject.Inject;
import com.splend.crud.dao.EmployeeDao;
import com.splend.crud.entity.Employee;
public class EmployeeServiceImpl implements EmployeeService {
@Inject(value="employeeDao",required=true)
private EmployeeDao employeeDao;
@Override
public Employee get(Employee employee) {
return employeeDao.get(employee);
}
@Override
public List<Employee> getEmployees() {
return employeeDao.getAll();
}
@Override
public boolean save(Employee employee) {
return employeeDao.save(employee);
}
@Override
public boolean update(Employee employee) {
return employeeDao.update(employee);
}
@Override
public boolean delete(Employee employee) {
return employeeDao.delete(employee);
}
}
4、编写Action以及相关jsp
package com.splend.crud.handler;
import java.util.Map;
import org.apache.struts2.interceptor.RequestAware;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.inject.Inject;
import com.splend.crud.entity.Employee;
import com.splend.crud.service.EmployeeService;
public class EmployeeAction implements RequestAware, ModelDriven<Employee>, Preparable {
@Inject(value = "employeeService", required = true)
private EmployeeService employeService;
private Employee employee;
public String edit() {
return "edit";
}
public void prepareEdit() {
Employee emp = new Employee();
emp.setEmployeeId(employeeId);
employee = employeService.get(emp);
}
public String update() {
employeService.update(employee);
return "success";
}
public void prepareUpdate() {
employee = new Employee();
}
public String save() {
employeService.save(employee);
return "success";
}
public void prepareSave() {
employee = new Employee();
}
public String delete() {
Employee emp = new Employee();
emp.setEmployeeId(employeeId);
employeService.delete(emp);
return "success";
}
public String list() {
requset.put("emps", employeService.getEmployees());
return "list";
}
private Map<String, Object> requset;
private Integer employeeId;
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
/**
* 获取Request对象的方式,这里选择实现RequestAware接口。
*/
@Override
public void setRequest(Map<String, Object> request) {
this.requset = request;
}
/**
* 使用ModelDriven把employee对象放到值栈栈顶。
*/
@Override
public Employee getModel() {
return employee;
}
@Override
public void prepare() throws Exception {
// TODO Auto-generated method stub
}
}
4.1、写显示页面emp-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:debug></s:debug>
<s:form action="emp-save">
<s:textfield name="firstName" label="FirstName"></s:textfield>
<s:textfield name="lastName" label="LastName"></s:textfield>
<s:textfield name="email" label="Email"></s:textfield>
<s:submit></s:submit>
</s:form>
<table cellpadding="10" cellspacing="0" border="1">
<thead>
<tr>
<td>ID</td>
<td>FirstName</td>
<td>LastName</td>
<td>Email</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</thead>
<tbody>
<s:iterator value="#request.emps">
<tr>
<td>${employeeId }</td>
<td>${firstName }</td>
<td>${lastName }</td>
<td>${email }</td>
<td><a href="emp-edit?employeeId=${employeeId }">Edit</td>
<td><a href="emp-delete?employeeId=${employeeId }">Delete</td>
</tr>
</s:iterator>
</tbody>
</table>
</body>
</html>
4.2、编写编辑页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:form action="emp-update">
<s:hidden name="employeeId"></s:hidden>
<s:textfield name="firstName" label="FirstName"></s:textfield>
<s:textfield name="lastName" label="LastName"></s:textfield>
<s:textfield name="email" label="Email"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
4.3、主页index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="emp-list">List All Employees</a>
</body>
</html>
5、运行结果
5.1、运行index.jsp
5.2、List All Employees
5.3、Edit
6、总结
在学习了Hibernate后也没有进行怎么的运用,在这里学习Struts2后,也算是对学的进行简单的应用和总结一下
在运用的过程中也出现了一些问题,比如把hibernate的jar包没放在WEB-INF/lib下的话,就会显示tomcat的web应用
类加载器无法加载hibernate相关类,回想起之前看《深入理解Java虚拟机:JVM高级特性与最佳实践》的时候好像有
讲过一些类加载问题,然后把jar包放到WEB-INF/lib下就解决了这个问题。
如果这个其中有什么bug或者讲的不对的对方,请多多指教。
源代码下载:https://pan.baidu.com/s/1i6NrZYd
上一篇: 介绍css3过渡和动画有哪些区别
下一篇: 在java中如何使用反射获取泛型信息
推荐阅读
-
jdbc连接sql server2017进行简单的增、删、改、查操作
-
dbcp 数据库连接池配置及对数据库的增、删、改、查 jdbcjavadbcp
-
简单的php数据库操作类代码(增,删,改,查)
-
简单的php数据库操作类代码(增,删,改,查)_PHP
-
简单的php数据库操作类代码(增,删,改,查)_PHP教程
-
使用LitePal操作数据库(实现对数据的增、删、改、查)
-
简单的php数据库操作类代码(增,删,改,查)_PHP
-
简单的php数据库操作类代码(增,删,改,查)
-
jdbc连接sql server2017进行简单的增、删、改、查操作
-
简单的php数据库操作类代码(增,删,改,查)_php实例