Struts 2 和 Hibernate 是 Java Web 开发领域中两个非常流行的框架。Struts 2 主要负责处理 Web 层的请求,而 Hibernate 则专注于数据持久化。将这两个框架结合起来,可以构建出高效且易于维护的企业级应用。本文将通过一个具体的示例来展示如何在 Struts 2 中整合 Hibernate,以实现基本的 CRUD(创建、读取、更新、删除)操作。
首先,创建一个新的 Maven 项目,并添加 Struts 2 和 Hibernate 的依赖。在 pom.xml
文件中加入以下依赖:
<dependencies>
<!-- Struts 2 Core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.6.11</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.21.Final</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- Other dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
接下来,配置 Hibernate。在 src/main/resources
目录下创建 hibernate.cfg.xml
文件,配置数据库连接信息和其他设置。
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/struts_hibernate_crud?useSSL=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.example.model.User"/>
</session-factory>
</hibernate-configuration>
定义一个简单的实体类 User
,并为其创建 Hibernate 映射文件 User.hbm.xml
。
package com.example.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
private Long id;
private String name;
private String email;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
对应的映射文件如下:
<hibernate-mapping>
<class name="com.example.model.User" table="users">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="name" column="name"/>
<property name="email" column="email"/>
</class>
</hibernate-mapping>
现在,创建一个 DAO 接口和实现类来处理数据库操作。
package com.example.dao;
import com.example.model.User;
import java.util.List;
public interface UserDao {
void save(User user);
User findById(Long id);
List<User> findAll();
void update(User user);
void delete(Long id);
}
package com.example.dao.impl;
import com.example.dao.UserDao;
import com.example.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private EntityManager entityManager;
@Override
public void save(User user) {
entityManager.persist(user);
}
@Override
public User findById(Long id) {
return entityManager.find(User.class, id);
}
@Override
public List<User> findAll() {
return entityManager.createQuery("from User", User.class).getResultList();
}
@Override
public void update(User user) {
entityManager.merge(user);
}
@Override
public void delete(Long id) {
User user = findById(id);
if (user != null) {
entityManager.remove(user);
}
}
}
接下来,创建一个 Struts 2 的 Action 类来处理用户的请求。这里使用 Spring 来注入 DAO 实例。
package com.example.action;
import com.example.dao.UserDao;
import com.example.model.User;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Namespace("/")
@ParentPackage("struts-default")
@Result(path = "/WEB-INF/jsp/user.jsp", name = "success")
public class UserAction {
@Autowired
private UserDao userDao;
private User user;
private List<User> users;
public String execute() {
users = userDao.findAll();
return SUCCESS;
}
public String create() {
userDao.save(user);
return "success";
}
public String edit() {
user = userDao.findById(user.getId());
return "edit";
}
public String update() {
userDao.update(user);
return "success";
}
public String delete() {
userDao.delete(user.getId());
return "success";
}
// Getters and setters
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
最后,配置 Struts 2 的 struts.xml
文件,定义 Action 和视图路径。
<package name="default" namespace="/" extends="struts-default">
<action name="user" class="com.example.action.UserAction">
<result name="success">/WEB-INF/jsp/user.jsp</result>
</action>
<action name="user_create" class="com.example.action.UserAction">
<result name="success">/WEB-INF/jsp/user.jsp</result>
</action>
<action name="user_edit" class="com.example.action.UserAction">
<result name="edit">/WEB-INF/jsp/edit_user.jsp</result>
</action>
<action name="user_update" class="com.example.action.UserAction">
<result name="success">/WEB-INF/jsp/user.jsp</result>
</action>
<action name="user_delete" class="com.example.action.UserAction">
<result name="success">/WEB-INF/jsp/user.jsp</result>
</action>
</package>
在 user.jsp
页面中展示用户列表,并提供链接来编辑或删除用户。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Management</title>
</head>
<body>
<h1>User List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<c:forEach var="user" items="${users}">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
<td>
<a href="<c:url value='/user_edit.action'/>?id=${user.id}">Edit</a>
<a href="<c:url value='/user_delete.action'/>?id=${user.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
<form action="<c:url value='/user_create.action'/>" method="post">
<input type="text" name="user.name" placeholder="Enter Name" required>
<input type="text" name="user.email" placeholder="Enter Email" required>
<input type="submit" value="Create">
</form>
</body>
</html>
在 edit_user.jsp
页面中提供表单来修改用户信息。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form action="<c:url value='/user_update.action'/>" method="post">
<input type="hidden" name="user.id" value="${user.id}">
<label for="name">Name:</label>
<input type="text" name="user.name" value="${user.name}" required>
<br/>
<label for="email">Email:</label>
<input type="text" name="user.email" value="${user.email}" required>
<br/>
<input type="submit" value="Update">
</form>
</body>
</html>
通过上述步骤,你已经成功地在 Struts 2 中集成了 Hibernate,并实现了基本的 CRUD 操作。这个示例不仅展示了如何配置和使用这两个框架,还介绍了如何通过 DAO 层分离业务逻辑和数据访问逻辑,使得代码更加模块化和可维护。掌握了这些知识后,你可以进一步探索 Struts 2 和 Hibernate 的高级功能,以满足更复杂的应用需求。