Hibernate和Struts2整合的增、删、改、查

时间:2022-01-30 05:06:30

1. 新建一个Web项目,准备好jar包和配置文件。

2. 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Test17</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 过滤器 -->
<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>

3. Hibernate主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接 -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">laoer123</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">test0816</property>
<!-- 数据库方案 -->
<property name="hibernate.default_schema">TEST0816</property>
<!-- 数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- 调试 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 自动建表方式 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 注册映射文件 -->
<mapping resource="com/hanqi/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

4. Struts配置文件

<?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> <!-- 覆盖默认的过滤的扩展名 -->
<constant name="struts.action.extension" value="do,action,,"></constant>
<!-- 启用配置调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<!-- 定义包 -->
<package name="index" extends="struts-default"> <action name="addUser">
<result>/WEB-INF/pages/addUser.jsp</result>
</action> <action name="addUser2">
<result>/WEB-INF/pages/addUser2.jsp</result>
</action> <!-- 保存User -->
<action name="saveUser" class="com.hanqi.action.UserAction" method="saveUser">
<result name="fail">/WEB-INF/pages/fail.jsp</result>
<result>/WEB-INF/pages/success.jsp</result>
</action>
<!-- 查询用户
<action name="selectUser" class="com.hanqi.action.UserAction" method="selectUser">
<result name="fail">/WEB-INF/pages/fail.jsp</result>
<result>/WEB-INF/pages/selectUser.jsp</result>
</action>
--> <!-- 通配符方式 -->
<action name="*" class="com.hanqi.action.UserAction" method="{1}">
<result name="fail">/WEB-INF/pages/fail.jsp</result>
<result>/WEB-INF/pages/{1}.jsp</result>
</action> <!-- 删除用户 -->
<action name="deleteUser" class="com.hanqi.action.UserAction" method="deleteUser">
<result name="fail">/WEB-INF/pages/fail.jsp</result>
<result type="redirectAction">selectUser</result>
</action> <!-- 查询单条记录 -->
<action name="updateUser" class="com.hanqi.action.UserAction" method="selectd">
<result>/WEB-INF/pages/update.jsp</result>
</action> <!-- 修改单个用户记录 -->
<action name="EditUser" class="com.hanqi.action.UserAction" method="update">
<result name="fail">/WEB-INF/pages/fail.jsp</result>
<result type="redirectAction">selectUser</result>
</action>
<!-- 驱动模型的数据保存 -->
<action name="saveUser2" class="com.hanqi.action.UserAction2" method="saveUser">
<result name="fail">/WEB-INF/pages/fail.jsp</result>
<result>/WEB-INF/pages/success.jsp</result>
</action> </package> </struts>

5. 用Hibernate创建的持久化类以及映射文件

package com.hanqi.entity;

import java.util.Date;

//实体化类
//不要使用final修饰
public class User { private Integer userID;
private String userName;
private Date birthday;
private Double money;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
// 必须提供无参的构造方法
//需要用到反射
public User() {
super();
}
public User(Integer userID, String userName) {
super();
this.userID = userID;
this.userName = userName;
}
@Override
public String toString() {
return "User [userID=" + userID + ", userName=" + userName + ", birthday=" + birthday + ", money=" + money
+ ", password=" + password + "]";
} }
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-11-7 14:40:01 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.hanqi.entity.User" table="T_USER">
<id name="userID" type="int">
<column name="USER_ID" />
<generator class="native" />
</id>
<property name="userName" type="java.lang.String">
<column name="USER_NAME" length="20" not-null="true" unique="true"/>
</property>
<property name="birthday" type="java.util.Date">
<column name="BIRTHDAY" sql-type="DATE"/>
</property>
<property name="money" type="java.lang.Double">
<column name="MONEY" sql-type="NUMBER" default="0" length="8" scale="2"/>
</property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" length="10"></column>
</property> </class>
</hibernate-mapping>

6.DAO层

package com.hanqi.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry; import com.hanqi.entity.User; public class UserDAO { private Configuration cfg =null;
private ServiceRegistry sr =null; private SessionFactory sf = null;
private Session se =null;
private Transaction ts =null;
public UserDAO()
{
//初始化Hibernate
cfg = new Configuration().configure(); sr = new StandardServiceRegistryBuilder().
applySettings(cfg.getProperties()).build(); }
//
private void init()
{
sf= cfg.buildSessionFactory(sr); se = sf.openSession(); ts = se.beginTransaction();
}
private void destory()
{
ts.commit();
se.close();
sf.close(); }
//保存User
public User insert(User user)
{ init();
se.save(user);
destory();
return user;
}
//查询列表
public List<User>getAll()
{
List<User> rtn = new ArrayList<>(); init(); rtn=se.createQuery("from User ")
.list(); destory(); return rtn;
}
//删除
public void delete(int userID)
{
init(); //获取对象
User u=(User)se.get(User.class, userID); se.delete(u); destory();
}
//查询单个
public User selectUser(int userID)
{
init();
//获取对象
User u = (User)se.get(User.class, userID); destory(); return u;
}
//修改
public User update(User user)
{
init(); // 获取对象
// User u =(User)se.get(User.class,userID);
// //修改数据
// u.setUserID(user.getUserID());
// u.setUserName(user.getUserName());
// u.setPassword(user.getPassword());
// u.setMoney(user.getMoney());
// u.setBirthday(user.getBirthday()); se.update(user); destory(); return user; } }

7. Service层

package com.hanqi.service;

import java.util.List;

import com.hanqi.dao.UserDAO;
import com.hanqi.entity.User; public class UserService { // 添加User的方法
public User add(User user)
{ return new UserDAO().insert(user);
}
//全表查询 public List<User> getAll()
{
return new UserDAO().getAll();
}
//删除记录
public void delete(int userID)
{
new UserDAO().delete(userID);
} //查询单个
public User select(int userID)
{
return new UserDAO().selectUser(userID);
}
//修改记录
public User update(User user)
{
return new UserDAO().update(user);
}
}

8.Action类

package com.hanqi.action;

import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.hanqi.entity.User;
import com.hanqi.service.UserService;
import com.opensymphony.xwork2.ActionContext; public class UserAction { //域模型方式
private User user; public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
}
public String insertUser()
{
return saveUser();
}
//处理保存User的方法
public String saveUser()
{
String rtn ="fail"; System.out.println(user);
try{
// 调用Service层(模型层,业务逻辑层)
User u1=new UserService().add(user); //使用request转发到下一个页面
ActionContext ac = ActionContext.getContext(); Map<String,Object>mo=(Map<String,Object>)ac.get("request"); mo.put("user", u1); rtn="success";
}
catch(Exception e)
{
e.printStackTrace();
}
return rtn;
}
//查询
public String selectUser()
{
String rtn ="fail";
try
{
//调用查询的方法
List<User> lu = new UserService().getAll();
//得到原生的request
HttpServletRequest hsr=ServletActionContext.getRequest();
hsr.setAttribute("userlist", lu);
rtn = "success";
}
catch(Exception e)
{
e.printStackTrace();
}
return rtn;
}
//删除
public String deleteUser()
{
String rtn="fail";
try
{
//获取userid;
//得到原生的request
HttpServletRequest hsr=ServletActionContext.getRequest();
String uid = hsr.getParameter("userid");
//执行删除
new UserService().delete(Integer.parseInt(uid)); rtn = "success";
}
catch(Exception e)
{
e.printStackTrace();
}
return rtn;
}
//查询单条记录
public String selectd()
{
String rtn="fail";
try
{
//得到原生的request
HttpServletRequest hsr=ServletActionContext.getRequest();
String uid=hsr.getParameter("userid");
int userid = Integer.parseInt(uid);
User u= new UserService().select(userid);
hsr.setAttribute("user", u);
rtn="success";
}
catch(Exception e)
{
e.printStackTrace();
}
return rtn;
}
//修改单个用户记录
public String update()
{
String rtn="fail";
try
{
// HttpServletRequest hsr=ServletActionContext.getRequest();
// String uid=hsr.getParameter("userid");
//执行修改
new UserService().update(user); rtn="success";
}
catch(Exception e)
{
e.printStackTrace();
}
return rtn;
}
// 分页查询
public String selectUserf()
{
String rtn="fail";
try
{
//得到原生的request
HttpServletRequest hsr= ServletActionContext.getRequest();
int page= Integer.parseInt(hsr.getParameter("pages"));
//调用查询的方法
List<User>list=new UserService().selectf(page);
hsr.setAttribute("pages", page+1);
hsr.setAttribute("fselect", list);
rtn="success";
}
catch(Exception e)
{
e.printStackTrace();
} return rtn;
}
}
package com.hanqi.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hanqi.entity.User;
import com.hanqi.service.UserService;
import com.opensymphony.xwork2.ModelDriven; // 使用模型驱动的方式
// 实现接口ModelDriven<实体类>
public class UserAction2 implements ModelDriven<User>{
//必须要实例化
private User user = new User();
// 返回实体类的实例
@Override
public User getModel() {
// 返回的必须是模型的 实例 return user;
} // 保存数据
public String saveUser()
{
String rtn ="fail"; try
{
//保存
new UserService().add(user);
HttpServletRequest hsr = ServletActionContext.getRequest();
hsr.setAttribute("user", user); rtn="success";
}
catch(Exception e)
{
e.printStackTrace();
} return rtn;
} }

9. 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="addUser">添加用户</a> <br>
<br>
<a href="selectUser?pages=1">用户列表</a>
<br>
<br>
<a href="addUser2">添加用户2</a>
</body>
</html>

添加用户界面

<%@page import="com.hanqi.service.UserService"%>
<%@page import="com.hanqi.entity.User"%>
<%@ 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> 添加用户
<br>
<br>
<form action="saveUser!insertUser.action" method="post">
用户名:<input type="text" name="user.userName">
<br>
密码:<input type="password" name="user.password">
<br>
生日:<input type="text" name="user.birthday">
<br>
薪酬:<input type="text" name="user.money">
<br><br>
<input type="submit" value="保存"> </form>
</body>
</html>

跳转成功的界面

<%@ 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> 操作成功!
<br>
User =${user }
<br>
</body>
</html>

跳转失败的界面

<%@ 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> 操作失败 </body>
</html>

查询用户的界面

<%@page import="com.hanqi.entity.User"%>
<%@page import="java.util.List"%>
<%@ 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> <% List<User>lu = (List<User>)request.getAttribute("userlist"); for(User u:lu)
{
out.print(u+"【<a href='deleteUser?userid="+u.getUserID()+"'>删除</a>】【<a href='updateUser?userid="+u.getUserID()+"'>修改</a>】<br>");
int pages = Integer.parseInt(request.getParameter("pages"));
} %>
<br><br>
</body>
</html>

修改用户的界面

<%@page import="com.hanqi.entity.User"%>
<%@ 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>
<% User us = (User)request.getAttribute("user"); %> <br>
<br>
<form action="EditUser" method="post"> 用户ID:<input type="text" readonly="readonly" name="user.userID" value="<% out.print(us.getUserID());%>"> 用户名:<input type="text" name="user.userName" value="<% out.print(us.getUserName());%>">
<br>
密码:<input type="password" name="user.password" value="<% out.print(us.getPassword());%>">
<br>
生日:<input type="text" name="user.birthday" value="<% out.print(us.getBirthday());%>">
<br>
薪酬:<input type="text" name="user.money" value="<%out.print(us.getMoney());%>">
<br><br>
<input type="submit" value="保存"> </form>
</body>
</html>

用模型驱动方式添加用户的界面

<%@page import="com.hanqi.service.UserService"%>
<%@page import="com.hanqi.entity.User"%>
<%@ 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> 添加用户-模型驱动方式
<br>
<br>
<form action="saveUser2" method="post">
用户名:<input type="text" name="userName">
<br>
密码:<input type="password" name="password">
<br>
生日:<input type="text" name="birthday">
<br>
薪酬:<input type="text" name="money">
<br><br>
<input type="submit" value="保存"> </form>
</body>
</html>