struts2整合hibernate

数据库表:Person表



框架目录:



Person.java

package com.hibernate.model;

import java.sql.Date;

public class Person {
	private Integer id;
	private String username;
	private String password;
	private int age;
	private Date registerdate;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = 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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Date getRegisterdate() {
		return registerdate;
	}
	public void setRegisterdate(Date registerdate) {
		this.registerdate = registerdate;
	}

}

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>
	<class name="com.hibernate.model.Person" table="person">
		<id name="id" column="id" type="int">
			<generator class="increment">
			</generator>
		</id>
		
		<property name="username" column="username" type="string"></property>
		<property name="password" column="password" type="string"></property>
		<property name="age" column="age" type="integer"></property>
		<property name="registerdate" column="registerdate" type="date"></property>
		
	</class>
</hibernate-mapping>

HibernateUtil.java

package com.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


	//创建session 关闭session

@SuppressWarnings("deprecation")
public class HibernateUtil { 
	private static SessionFactory sessionFactory;
	static{
		try{
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}catch(Exception ex){
			ex.printStackTrace();
			System.out.println("构造SessionFactory异常发生");
		}
	}
	
	public static Session currentSession(){
		Session session = sessionFactory.openSession();
		return session;
	}
	
	public static void closeSession(Session session){
		if(null != session){
			session.close();
		}
	}
}

DBPerson.java

package com.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hibernate.model.Person;
import com.hibernate.util.HibernateUtil;
public class DBPerson {
	/**
	 * 
	 *创建用户 
	 */
	
public static void save(Person person){
		Session session = HibernateUtil.currentSession();
		Transaction tx = session.beginTransaction();
		try{
			session.save(person); //执行数据库语句
			tx.commit();//事务提交,数据库语句产生
		}catch(Exception ex){
			System.out.println("增加用户失败");
			if(null!=session){
				tx.rollback();
			}
		}finally{
			HibernateUtil.closeSession(session);
		}
	}
	/**
	 * 查询所有用户
	 */
	@SuppressWarnings("unchecked")
	public static List<Person> listAll(){
		Session session = HibernateUtil.currentSession();
		Transaction tx = session.beginTransaction();
		List<Person> list = null;
		try{
			Query query = session.createQuery("from Person"); //这里的Person是类名,针对这个类,不针对表全称com.hibernate.model.Pseron。HQL语句,hibernate
			list = (List<Person>)query.list();
			
			tx.commit();//事务提交,数据库语句产生
		}catch(Exception ex){
			System.out.println("增加用户失败");
			ex.printStackTrace();
			if(null!=session){
				tx.rollback();
			}
		}finally{
			HibernateUtil.closeSession(session);
		}
		return list;
	}
}

PersonAction.java

package com.hibernate.action;


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hibernate.dao.DBPerson;
import com.hibernate.model.Person;
import com.opensymphony.xwork2.ActionSupport;


public class PersonAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private int id;
	private String username;
	private String password;
	private int age;

	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 getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	//完成用户增加操作
	public String save()throws Exception{ //在struts.xml里面定义一个method="save"
		Person person = new Person();
		person.setUsername(username);
		person.setPassword(password);
		person.setAge(age);
		//注册时间。服务器自己生成的时间
		java.sql.Date registerDate = new java.sql.Date(new java.util.Date().getTime());
		person.setRegisterdate(registerDate);
		
		DBPerson.save(person);//将PERSON保存到数据库进去
		
		List<Person> list = DBPerson.listAll();//这个lsit相当于数据库里面的所有数据
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("list",list);
		return SUCCESS;
		
	}
}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


<struts>
	<package name="hibernate" extends="struts-default">
		<action name="save" class="com.hibernate.action.PersonAction" method="save">
			<result name="success">/listAll.jsp</result>
		</action>
		
	</package>
</struts>

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="connection.url">jdbc:mysql://localhost:3306/test_user</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		
		<mapping resource="com/hibernate/model/Person.hbm.xml" />
	</session-factory>
</hibernate-configuration>
	


web.xml

	  <!-- 配置struts2的核心过滤器 -->
	  <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>
	  



register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="save.action">
		username:<input type="text" name="username"><br>
		password:<input type="password" name="password"><br>
		age:<input type="text" name="age"><br>
		<input type="submit" value="submit">
	</form>
</body>
</html>

listAll.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
   <%@taglib uri="/struts-tags" prefix="s"  %>
<!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>
<script type="text/javascript">
	function del(){
		if(confirm("Are you sure?")){
			return true;
		}
		return false;
	}
</script>
</head>
<body>
	<table width="80%" align="center" border="1">
		<tr>
			<td>
				username
			</td>

			<td>
				password
			</td>
		
			<td>
				registerdate
			</td>
			<td>
				age
			</td>
			<td>
				update
			</td>
			<td>
				delete
			</td>
		</tr>
		
		<s:iterator value="#request.list" id="person">
			<tr>
				<td>
				<s:a href="getPerson.action?id=%{#person.id}"/>
					<s:property value="username" />
					<s:a />
				</td>
			
				<td>
				<s:property value="password" />
				</td>
			
				<td>
					<s:property value="registerdate" />
				</td>
				<td>
					<s:property value="age" />
				</td>
				<td>
				<s:a href="updatePerson.action?id=%{#person.id}"/>
				update
				</td>
				<td>
				<s:a/>
				delete
				</td>
			</tr>
			
			
		</s:iterator>
		
		
	</table>
	
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值