1.先把struts2,Hibernate,mysql架包加载到web project中来
jar包下载地址:
http://download.csdn.net/detail/hoho_12/9524001
2.User.java部分代码,一个简单的javabean和表字段一致
package com.hibernate.wxh;
public class User {
private int id;
private String username;
private String userpwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
}
3.User.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">
<!-- Generated 2016-5-12 16:50:11 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.hibernate.wxh.User" table="USER">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="userpwd" type="java.lang.String">
<column name="USERPWD" />
</property>
</class>
</hibernate-mapping>
4.HibernateUtil.java工具类
package com.hibernate.wxh;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
// 创建线程局部变量threadLocal,用来保存Hibernate的Session
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// 使用静态代码块初始化Hibernate
static {
try {
Configuration cfg = new Configuration().configure(); // 读取配置文件hibernate.cfg.xml
sessionFactory = cfg.buildSessionFactory(); // 创建SessionFactory
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
// 获得SessionFactory实例
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
// 获得ThreadLocal 对象管理的Session实例.
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
// 通过SessionFactory对象创建Session对象
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
// 将新打开的Session实例保存到线程局部变量threadLocal中
threadLocal.set(session);
}
return session;
}
// 关闭Session实例
public static void closeSession() throws HibernateException {
// 从线程局部变量threadLocal中获取之前存入的Session实例
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
// 重建SessionFactory
public static void rebuildSessionFactory() {
try {
configuration.configure("/hibernate.cfg.xml"); // 读取配置文件hibernate.cfg.xml
sessionFactory = configuration.buildSessionFactory(); // 创建SessionFactory
} catch (Exception e) {
System.err.println("Error Creating SessionFactory ");
e.printStackTrace();
}
}
// 关闭缓存和连接池
public static void shutdown() {
getSessionFactory().close();
}
}
5.UserDAO.java,包含两个方法,一个用来数据库里添加记录,一个用来取数据库里记录。
package com.hibernate.wxh;
import java.util.*;
import org.hibernate.*;
public class UserDAO {
public static List<User>getUser(){
List<User> user=new ArrayList<User>();
Session session=HibernateUtil.getSession();
user=session.createQuery("from User").list();
HibernateUtil.closeSession();
return user;
}
public static void addUser(User u){
Session session=HibernateUtil.getSession();
Transaction ts=session.beginTransaction();
session.save(u);
ts.commit();
HibernateUtil.closeSession();
}
}
6.hibernate.cfg.xml配置文件
<?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">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">111</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/db_test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/hibernate/wxh/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
7. web.xml
<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>
8. Struts.xml
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ui.theme" value="simple"/>
<package name="default" namespace="/" extends="struts-default">
<action name="UserAction" class="com.struts2.wxh.UserAction">
<result>/index.jsp</result>
</action>
</package>
</struts>
9. UserAction
package com.struts2.wxh;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.hibernate.wxh.*;
public class UserAction extends ActionSupport implements ModelDriven<User>{
private User u=new User();
public User getModel(){
return u;
}
public User getU() {
return u;
}
public void setU(User u) {
this.u = u;
}
public String execute() throws Exception{
UserDAO.addUser(u);
return "success";
}
}
10.index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*,com.hibernate.wxh.*" %>
<!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>
<form name="form1" method="post" action="UserAction">
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="text" name="userpwd"></p>
<p>
<input type="submit" name="submit" value="添加">
<input type="reset" name="reset" value="重置">
</p>
</form>
<table width="400" border="1" cellspacing="5" >
<tr>
<td align="center">ID</td>
<td align="center">用户名</td>
<td align="center">密码</td>
</tr>
<%
List<User> user=UserDAO.getUser();
for(User u:user){
%>
<tr>
<td align="center"><%=u.getId() %></td>
<td align="center"><%=u.getUsername() %></td>
<td align="center"><%=u.getUserpwd() %></td>
</tr>
<%} %>
</table>
</body>
</html>
项目完整源码下载地址:
http://download.csdn.net/detail/hoho_12/9524142
开发工具:
Eclipse + mysql+Tomcat8