Hibernate和Struts2整合的增、删、改、查
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>
Hibernate和Struts2整合的增、删、改、查的更多相关文章
- 好用的SQL TVP~~独家赠送[增-删-改-查]的例子
以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化. 本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...
- iOS FMDB的使用(增,删,改,查,sqlite存取图片)
iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...
- iOS sqlite3 的基本使用(增 删 改 查)
iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...
- django ajax增 删 改 查
具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...
- ADO.NET 增 删 改 查
ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...
- MVC EF 增 删 改 查
using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...
- python基础中的四大天王-增-删-改-查
列表-list-[] 输入内存储存容器 发生改变通常直接变化,让我们看看下面列子 增---默认在最后添加 #append()--括号中可以是数字,可以是字符串,可以是元祖,可以是集合,可以是字典 #l ...
- 简单的php数据库操作类代码(增,删,改,查)
这几天准备重新学习,梳理一下知识体系,同时按照功能模块划分做一些东西.所以.mysql的操作成为第一个要点.我写了一个简单的mysql操作类,实现数据的简单的增删改查功能. 数据库操纵基本流程为: 1 ...
- MongoDB增 删 改 查
增 增加单篇文档 > db.stu.insert({sn:'001', name:'lisi'}) WriteResult({ "nInserted" : 1 }) > ...
随机推荐
- Displaying Bitmaps Efficiently 显示图片相关
http://developer.android.com/training/displaying-bitmaps/index.html .手机内存资源有限 .Bitmap占用的内存大 .App有时需要 ...
- UTF-8编码的字符串拆分成单字、获取UTF-8字符串的字符个数的代码及原理
一.字符编码简介 1. ASCII码 在计算机内部,所有的信息最终都表示为一个二进制的字符串.每一个二进制位(bit)有0和1两种状态,因此八个二进制位就可以组合出256种状态,这被称为一个字节(by ...
- ruby中tes-unitt数据初始化方法整理
在用ruby做测试时,很多时候需要一些数据初始化以及事后的数据恢复还原之类的操作,下面整理了这些方法.require "test/unit" class TestAnion < ...
- SQL语句之备份表
SELECT INTO 语句:表示从一个表中选取数据,然后把数据插入另一个表中,常用来备份一张表 1.全表结构备份: SELECT * INTO new_table_name FROM old_tab ...
- OAF_文件系列7_实现OAF处理Excel的JXL包介绍(概念)
20150714 Created By BaoXinjian
- Convert Excel data to MDB file
所需组件: microsoft ado ext. 2.8 for ddl and security 或者更新的组件. 添加: using ADOX;using System.Runtime.Inter ...
- (原)Android理论梳理-No1异步处理之Handler相关机制
1 Handler的基本概念: 什么是handler? Handler是安卓系统的一种回调机制. handler的作用? 他的作用是用于不同线程之间的通讯.一是可以用于子线程与UI线程的数据通信,因为 ...
- Google Developing for Android 二 - Memory 最佳实践 // lightSky‘Blog
Google Developing for Android 二 - Memory 最佳实践 | 分类于 Android最佳实践 原文:Developing for Android, II Th ...
- 视频演示eworkflow集成定制aspx页面的过程
eworkflow自定义工作流系统,集成eform自定义表单,可以做到在线编辑流程,在线编辑表单.eform也提供在线建立业务表,维护表字段等,所以通过eworkflow+eform可以在线完成业务流 ...
- asp.net 手工调用 WS(Get)方法:
asp.net 手工调用 WS(Get)方法: 通过手工HttpWebRequest,HttpWebResponse来模拟调用.核心代码:string strurl="http://loca ...