博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)
阅读量:4128 次
发布时间:2019-05-25

本文共 10874 字,大约阅读时间需要 36 分钟。

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

Struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
Struts2
/*
index.jsp
2.2、在src目录下创建strust.xml文件(这个是最终的strust.xml)

false
emp-list
/emp-{1}.jsp
/success.jsp
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

3.3、src目录下创建hibernate.cfg.xml文件

splend
1230
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/sh
org.hibernate.dialect.MySQL5InnoDBDialect
true
true
update
2
true
10
5
2
2000
2000
10
100
30
3.4、编写BaseDao<T>的泛型接口

package com.splend.crud.dao;import java.util.List;public interface BaseDao
{ T get(T entity); /** * 获取全部列表 * * @return 所有T对象 */ List
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
{}
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
getAll() { List
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
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
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
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
, 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
requset; private Integer employeeId; public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } /** * 获取Request对象的方式,这里选择实现RequestAware接口。 */ @Override public void setRequest(Map
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"%>
Insert title here
ID FirstName LastName Email Edit Delete
${employeeId } ${firstName } ${lastName } ${email } Edit Delete
4.2、编写编辑页面

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%>
Insert title here
4.3、主页index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
Insert title here List All Employees
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
你可能感兴趣的文章
Missing Number
查看>>
Third Maximum Number
查看>>
Find All Numbers Disappeared in an Array(哈希表)
查看>>
Add Binary
查看>>
(a+b)/2与a+(b-a)/2的区别
查看>>
LeetCode之Math
查看>>
Isomorphic Strings
查看>>
刷题过程中的API新解
查看>>
LeetCode过程中遇到的代码错误
查看>>
关于Java对象引用的理解
查看>>
Java二维数组访问的行优先问题
查看>>
leetcode二叉树相关操作的总结
查看>>
知识表示学习相关研究
查看>>
计算机知识补充扩展
查看>>
关于共享单车的一点想法
查看>>
科研知识扩展
查看>>
object[] 不能强转 Integer[]
查看>>
论文中的生词
查看>>
一般英文论文的大体结构
查看>>
科研情报分析产品
查看>>