实验目的:利用Struts 1.x和Hibernate框架,实现注册功能。即在Web界面上输入学号,用户名和密码,存入MySQL数据库中。
注:此实验是基于struts1.x框架下(含有Action,ActionForm和jsp)
使用软件:MySQL 8.0及以上版本,Navicat 12,MyEclipse2017
相关参数
- 数据库名:login_database
- 表名:people
- 字段名:id,stdnumber,name,password
具体流程
1、新建Web Project项目,并在该项目新建Struts1.x和Hibernate
2、添加Hibernate相关jar包和MySQL连接jar包
3、编写Hibernate工具包函数HibernateSessionFactory.java和hibernateUtils.java
HibernateSessionFactory.java:
package hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
public HibernateSessionFactory() {
}
static {
try {
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return ses