博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于Hibernate和Struts2的用户管理系统小案例
阅读量:4009 次
发布时间:2019-05-24

本文共 7835 字,大约阅读时间需要 26 分钟。

一、

用户管理系统,使用Hibernate向数据库表中添加一个用户,将所有的用户信息查出来并显示在页面上。

所需工具:MyEclipse、MySql数据库

二、

1.数据库建表

新建一个数据库javaweb,并在该数据库下创建一个表USER并存入几条数据

DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(20) DEFAULT NULL,  `password` varchar(20) DEFAULT NULL,  `realname` varchar(50) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  `sex` varchar(2) DEFAULT NULL,  `address` varchar(50) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;INSERT INTO `user` VALUES ('1', '张三', '1111', '张三', '18', '男', '山东省');INSERT INTO `user` VALUES ('2', 'anna', '2017', 'anna', '19', '女', '美国');

2.环境配置

①直接向lib下导入所需的jar包②用myeclipse自带的jar包

在这里我使用了第二种方法:

配置Hibernate:在项目上点击右键-->MyEclipse-->Add Hibernate Capabilities...默认到最后一步配置MySql.配置好Hibernate,会自动生成hibernate.cfg.xml和HibernateSessionFactory文件,在src下新建common包将HibernateSessionFactory文件放到里面。

配置Struts2:在项目上点击右键-->MyEclipse-->Add Struts Capabilities..-->选择Struts2最高版本,URL Pattern选择/*-->Finish

3.将mysql驱动jar包放到lib文件夹下

4.实体类User(对应数据表的USER)

在src目录下新建entity包,并创建Hibernate的POJO类User(普通的Java类作为持久化对象)

public class User {	// 用户编号.	private int id;	// 用户名.	private String username;	// 密码.	private String password;	// 真实姓名.	private String realname;	// 年龄.	private int age;	// 性别.	private String sex;	// 地址.	private String address;	//属性的getter和setter方法省略。。。}

5.编写User类的Hibernate映射文件,将对象与数据库中的表建立联系

Hibernate映射文件是要告诉Hibernate持久化类和数据库表的映射信息。

在entity中创建User.hbm.xml文件

6.编写Hibernate配置文件

Hibernate配置文件是告诉Hibernate连接的数据库的相关信息,数据库配置内容定义在hibernate.cfg.xml中。

hibernate.cfg.xml
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/javaweb
root
123456
org.hibernate.dialect.MySQLDialect

7.HibernateSessionFactory类可以由MyEclipse自动生成

在该类中读取hibernae.cfg.xml配置文件。

代码如下

import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution.  Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */public class HibernateSessionFactory {    /**      * Location of hibernate.cfg.xml file.     * Location should be on the classpath as Hibernate uses       * #resourceAsStream style lookup for its configuration file.      * The default classpath location of the hibernate config file is      * in the default package. Use #setConfigFile() to update      * the location of the configuration file for the current session.        */	private static final ThreadLocal
threadLocal = new ThreadLocal
(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the
SessionFactory if needed. * * @return Session * @throws HibernateException */ 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; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; }}

8.编写数据库操作Dao类

在src目录下新建一个包dao,创建UserDao类

import java.util.ArrayList;import java.util.List;import org.hibernate.Session;import com.zrx.common.HibernateSessionFactory;import com.zrx.entity.User;public class UserDao {		//保存用户.	public int saveUser(User user) {		int num = 0;		Session session = null;				//由于Hibernate版本的差异,不能直接写Transaction transaction = null;要指定为org.hibernate.Transaction.		org.hibernate.Transaction transaction = null;				try {			session = HibernateSessionFactory.getSession();//获取session对象.			transaction = session.beginTransaction();//开启事务.			num = Integer.parseInt(session.save(user).toString());//保存数据.			transaction.commit();//提交事务.		} catch (Exception e) {			num = 0;			e.printStackTrace();		} finally {			HibernateSessionFactory.closeSession();//关闭session.		}		return num;	}		//查询全部的用户信息.	@SuppressWarnings("unchecked")	public List
getUsers() { List
users = new ArrayList
(); try { Session session = HibernateSessionFactory.getSession();//获得session对象. //创建查询语句,字符串中的User必须与entity中的User实体类名称相同. users = session.createQuery("from User order by id").list(); } catch (Exception e) { e.printStackTrace(); } finally { HibernateSessionFactory.closeSession(); } return users; }}

9.业务控制Action类

在src下新建包action,在包下创建类UserAction

import java.util.List;import com.opensymphony.xwork2.ActionSupport;import com.zrx.dao.UserDao;import com.zrx.entity.User;public class UserAction extends ActionSupport {	private static final long serialVersionUID = 1L;	private User user;	UserDao userDao = new UserDao();	private List
userList; //保存用户. public String execute() { userDao.saveUser(user); return SUCCESS; } //获取用户. public String getUsers() { userList = userDao.getUsers(); return "list"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List
getUserList() { return userList; }}

10.struts.xml中配置Action

/
user
getUsers
/index.jsp

11.用户添加界面register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>			
用户添加

12.用户显示界面index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>			
用户显示
 用户列表 
用户名 密码 真实姓名 年龄 性别 通讯地址

转载地址:http://wndfi.baihongyu.com/

你可能感兴趣的文章
输入设备节点自动生成
查看>>
opencv test code-1
查看>>
eclipse 导入先前存在的项目
查看>>
GNU hello代码分析
查看>>
Qt继电器控制板代码
查看>>
busybox passwd修改密码
查看>>
wpa_supplicant控制脚本
查看>>
rfkill: WLAN hard blocked
查看>>
gstreamer相关工具集合
查看>>
arm 自动升级脚本
查看>>
RS232 四入四出模块控制代码
查看>>
gstreamer插件之 videotestsrc
查看>>
autoupdate script
查看>>
linux 驱动开发 头文件
查看>>
/etc/resolv.conf
查看>>
container_of()传入结构体中的成员,返回该结构体的首地址
查看>>
linux sfdisk partition
查看>>
ipconfig,ifconfig,iwconfig
查看>>
opensuse12.2 PL2303 minicom
查看>>
电平触发方式和边沿触发的区别
查看>>