struts2与hibernate整合实例

程序功能为注册用户,显示用户信息。分四层:jsp,action,service,DAO
1、在lib目录加入struts2与hibernate的包。我是用
2、在web.xml增加struts2的过滤器
3、注册表单,register.jsp:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


  
    struts2与hibernate整合实例 | 应用开发笔记
  
  
	
用户名:
密码:
年龄:

4、建Model:建包com.model,类Person


package com.model;

import java.sql.Date;

public class Person {
	private Integer id;
	//最好用Integer而不是用int,后面查询需要Integer
	private String username;
	private String password;
	private Integer age;
	private Date registerDate;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public Date getRegisterDate() {
		return registerDate;
	}
	public void setRegisterDate(Date registerDate) {
		this.registerDate = registerDate;
	}
}

5、配置Model与数据库字段的映射,在src目录下添加Person.hbm.xml(不是严格要求的):


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- name类名,table表名 -->
	<class name="com.model.Person" table="person">
		<!-- id标签表示主键 -->
		<id name="id" column="id" type="int">
			<!-- 自动增长 -->
			<generator class="increment"></generator>
		</id>
		<!-- 下面是字段映射 name属性,column是字段 type数据库类型 -->
		<property name="username" column="username" type="string"></property>
		<property name="password" column="password" type="string"></property>
		<property name="age" column="age" type="int"></property>
		<property name="registerDate" column="registerDate" type="date"></property>
	</class>
</hibernate-mapping>

6、配置Hibernate数据库连接,src目录下建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="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    	<property name="connection.username">root</property>
    	<property name="connection.password"></property>
    	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    	<!-- 设置dialect属性可以使用该类型数据库特性 -->
    	<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    	<!-- 在命令行输出SQL语句 -->
    	<property name="show_sql">true</property>
    	<!-- Model属性与数据库字段的映射文件 -->
    	<mapping resource="Person.hbm.xml" />
    </session-factory>
</hibernate-configuration>

注意,需要导入mysql jdbc驱动jar包.

7、数据库连接与关闭:包com.util类HibernateUtil


package com.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
	private static SessionFactory sessionFactory;
	//因为sessionFactory一旦生成就不需要关闭,即使配置文件修改也不会影响,所以放在静态代码片段中,类加载时就生成
	static{
		sessionFactory=new Configuration().configure().buildSessionFactory();
	}
	public static Session openSession()
	{
		Session session=sessionFactory.openSession();
		return session;
	}
	public static void close(Session session)
	{
		if(session!=null)
		{
			session.close();
		}
	}
}

8、写DAO层(调用Hibernate API与数据库交互),建包com.dao,接口PersonDAO,内容如下:


package com.dao;
import com.model.Person;
public interface PersonDAO {
	public void savePerson(Person person);
	public Person showPerson(Integer id);
}

一个保存用户(注册),一个返回指定ID的用户。
实现:包com.dao.impl,类PersonDAOImpl:


package com.dao.impl;

import org.hibernate.Transaction;

import com.dao.PersonDAO;
import com.model.Person;
import com.util.HibernateUtil;

public class PersonDAOImpl implements PersonDAO {

	@Override
	public void savePerson(Person person) {
		//开启session,与HttpSession完全没有任何关系,相当于一个数据库连接对象
		org.hibernate.Session session = HibernateUtil.openSession();
		Transaction tx = session.beginTransaction();
		//开启事务
		try {
			//插入
			session.save(person);
			tx.commit();
		} catch (Exception ex) {
			if (null != tx) {
				tx.rollback();
				//失败回滚
			}

		} finally {
			//关闭session
			HibernateUtil.close(session);
		}

	}

	@Override
	public Person showPerson(Integer id) {
		// TODO Auto-generated method stub
		org.hibernate.Session session = HibernateUtil.openSession();
		//get方法取出对象
		Person person = (Person) session.get(Person.class, id);
		return person;
	}
}

9、Service层,主要功能是逻辑处理,这里是与DAO层交互,即调用DAO层方法取出数据:
建com.service包,类PersonService:


package com.service;

import com.model.Person;

public interface PersonService {
	public void savePerson(Person person);
	public Person showPerson(Integer id);
}

实现类PersonServiceImpl,包com.service.impl中


package com.service.impl;

import com.dao.PersonDAO;
import com.dao.impl.PersonDAOImpl;
import com.model.Person;
import com.service.PersonService;

public class PersonServiceImpl implements PersonService {
	@Override
	public void savePerson(Person person) {
		// TODO Auto-generated method stub
		PersonDAO personDAO=new PersonDAOImpl();
		personDAO.savePerson(person);
	}
	@Override
	public Person showPerson(Integer id) {
		// TODO Auto-generated method stub
		PersonDAO personDAO=new PersonDAOImpl();
		Person person=personDAO.showPerson(id);
		return person;
	}
}

10、建Action(接收用户请求,作简单的包装),包com.action,类PersonAction,这里把查询和注册的方法写在同一个action中。


package com.action;

import org.apache.struts2.ServletActionContext;

import com.model.Person;
import com.opensymphony.xwork2.ActionSupport;
import com.service.PersonService;
import com.service.impl.PersonServiceImpl;

public class PersonAction extends ActionSupport {
	private String username;
	private String password;
	private Integer age;
	private Integer id;
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * 保存用户
	 * @return
	 * @throws Exception
	 */
	public String savePerson() throws Exception {
		// TODO Auto-generated method stub
		Person person=new Person();
		person.setAge(age);
		person.setPassword(password);
		person.setUsername(username);
		
		java.sql.Date registerDate=new java.sql.Date(new java.util.Date().getTime());
		person.setRegisterDate(registerDate);
		
		PersonService personService=new PersonServiceImpl();
		personService.savePerson(person);
		
		return SUCCESS;
	}
	/**
	 * 取用户
	 * @return
	 * @throws Exception
	 */
	public String showPerson() throws Exception{
		PersonService personService=new PersonServiceImpl();
		Person person=personService.showPerson(id);
		ServletActionContext.getRequest().setAttribute("person", person);
		return SUCCESS;
	}
}

struts.xml中配置Action:


	<package name="struts2_hibernate" extends="struts-default">
		<action name="savePerson" class="com.action.PersonAction" method="savePerson">
		</action>
		<action name="showPerson" class="com.action.PersonAction" method="showPerson">
			<result name="success">/showPerson.jsp</result>
		</action>
	</package>

savePerson没有写result,所以添加成功后返回404.
显示用户信息的jsp,showPerson.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


  
    struts2与hibernate整合实例 | 应用开发笔记
  
  
    ${person.username }
${person.password }
${person.age }

启动服务器测试前,先在数据库中建好相应的表
注册用户:http://localhost:8080/hibernate/register.jsp
查看用户:http://localhost:8080/hibernate/showPerson.action?id=用户id

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记