Struts2和Hibernate的整合

本文主要讲Struts2和Hibernate两种框架的整合,以模仿用户登录为例

第一步:写三个页面(分别为index.jsp,success.jsp,fail.jsp)

index.jsp的主要代码:

<!-- 表单不要写错了,否则就会出现不跳转的现象 -->
  <body>
    <form action="login" method="post">
    <!-- 必须是实体对象的名称 -->
    用户名:<input type="text" name="user.username"><br/>
     密     码:<input type="password" name="user.password"/><br/>
    <input type="submit" value="提交"/>
    <input type="reset" value="重置"/>   
    
    </form>

success.jsp的主要代码

 <body>
  <!-- 已经位于值栈之中,就不需要写# -->
    <h1>登录成功,欢迎<s:property value="user.username"/>登录!!!!</h1>
  </body>
fail.jsp的主要代码

 <body>
    <h1>登录失败,点击<a href="<%=path %>/index.jsp">这里</a>重新登录</h1>
  </body>

第二步:导入开发所需要的架包



第三步:.在src文件夹下建立两个包(分别为com.easyteam.action,com.easyteam.model)

在com.easyteam.action包下建立一个LoginAction类,代码如下:

package com.easyteam.action;

import java.util.List;

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

import com.easyteam.model.User;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>title LoginAction
 * <p>Description: <P>
 * <P>Company:com.easyteam.cn
 * @author yc
 * @date 2016-6-28 下午09:02:49
 *
 */
public class LoginAction extends ActionSupport  {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private User user;
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public String login(){
		
		Configuration cfg=new Configuration();
		SessionFactory sf=cfg.configure().buildSessionFactory();
		Session session=sf.openSession();
		Query query=session.createQuery("from User");//在HQL语句中表名应该是ORM映射的类名,而不是你在数据库中的表名
		List list=query.list();
		System.out.println(list.size());
		for (int i = 0; i < list.size(); i++) {
			
			if(user.getUsername().equals(((User)list.get(i)).getUsername())&&user.getPassword().equals(((User)list.get(i)).getPassword())){
				return "suc";
			}
			
		}
		return "err";
	}

}

在com.easyteam.model包下分别建立(HibernateSessionFactory,User,User.hbm.xml,TestDemo)

HibernateSessionFactory类的代码如下(它是自动生成的):

package com.easyteam.model;

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

/**
 * 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 String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> 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(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} 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 session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}
User类的代码如下:

package com.easyteam.model;

/**
 * <p>title User
 * <p>Description: <P>
 * <P>Company:com.easyteam.cn
 * @author yc
 * @date 2016-6-28 下午09:04:00
 *
 */
public class User {
	
	private int id;
	private String username;
	private String password;
	
	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;
	}
	
	

}
User.hbm.xml的配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.easyteam.model">
	<class name="User" table="user">
		<id name="id"  >
		<generator class="increment"></generator>
		</id>
		<property name="username"  />
		<property name="password" />
</class>
	
</hibernate-mapping>
TestDemo类的代码如下(这个类仅仅是为了测试使用):

package com.easyteam.model;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

/**
 * <p>title Test
 * <p>Description: <P>
 * <P>Company:com.easyteam.cn
 * @author yc
 * @date 2016-6-29 下午03:44:36
 *
 */
public class TestDemo {


	@Test
	public void fun(){
		User user=new User();
		user.setId(2);
		user.setUsername("lisi");
		user.setPassword("123");
		Configuration cfg=new Configuration();
		SessionFactory sf=cfg.configure().buildSessionFactory();
		Session session=sf.openSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		
	}
	@Test
	public void fun2(){
		
		Configuration cfg=new Configuration();
		SessionFactory sf=cfg.configure().buildSessionFactory();
		Session session=sf.openSession();
		Query query=session.createQuery("from User");
		List list=query.list();
		User user=(User) list.get(0);
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		
		
	}
	
}

第四部:在src文件夹下写hibernate.cfg.cml和struts.xml配置文件

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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/users</property>
        <property name="connection.username">root</property>
        <property name="connection.password">1</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!--<property name="connection.pool_size">1</property>

        --><!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

      
        <mapping resource="com/easyteam/model/User.hbm.xml"/>
	
    </session-factory>

</hibernate-configuration>
struts.xml的配置如下:

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

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
    <!-- 写类的时候要注意写类名字,光写包名是错误的,这种错误很容易干 -->
        <action name="login" class="com.easyteam.action.LoginAction" method="login">
            <result name="suc">
               success.jsp
            </result>
             <result name="err">
               fail.jsp
            </result>
        </action>
    </package>

</struts>

第五步:更改web.xml文件的配置如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>

    <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>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
附件:数据库的创建如下:
create database users;
create table user(
id int primary key auto_increment,
username varchar(20),
password varchar(20));






  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Struts2Hibernate 是两个非常流行的 Java Web 开发框架,它们可以很好地协同工作。下面是 Struts2Hibernate 整合的基本步骤: 1. 引入相关依赖 在项目的 pom.xml 文件中添加 Struts2Hibernate 相关依赖。例如: ``` <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts.version}</version> </dependency> ``` 2. 配置数据库连接 在项目的配置文件中配置数据库连接。例如,在 Hibernate 中,可以在 hibernate.cfg.xml 文件中指定数据库连接信息。同时,还需要在该文件中定义 Hibernate 的实体类映射信息。 3. 配置 Hibernate 的 SessionFactory 在 Spring 中,可以使用 LocalSessionFactoryBean 配置 Hibernate 的 SessionFactory。在配置文件中定义该 bean,并将数据库连接和实体类映射信息注入到该 bean 中。 4. 配置事务管理器 在 Spring 中,可以使用 HibernateTransactionManager 来管理 Hibernate 的事务。在配置文件中定义该 bean,并将 SessionFactory 注入到该 bean 中。 5. 配置 Struts2 的 Action 在 Struts2 中,可以使用 Hibernate 的 SessionFactory 来进行数据库操作。在 Action 中,通过注入 SessionFactory 来获得 Hibernate 的 Session 对象,从而进行数据库操作。 以上是 Struts2Hibernate 整合的基本步骤,具体实现还需要根据项目的实际情况进行调整和完善。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值