Struts2 Hibernate集成示例教程
Struts2和Hibernate都是各自领域中广泛使用的框架。
今天,我们将学习如何将Struts2 Web应用程序框架与Hibernate ORM框架集成在一起。
Struts2 Hibernate
与Spring Hibernate Integration不同,Struts2框架没有提供可使用的插件。
因此,我们将需要使用Servlet侦听器来管理Hibernate SessionFactory。
让我们看看如何通过一个简单的Web应用程序示例将Struts2与Hibernate集成。
我们最终的项目结构将如下图所示,我们将逐一研究每个组件。
首先在Eclipse中创建"动态Web项目",然后将其转换为maven项目,以为我们的Web应用程序准备好基本框架。
Struts2 Hibernate示例数据库设置
在身份验证用户出现在欢迎页面之后,我们将创建一个登录应用程序,其中将显示他的所有信息。
下面的SQL脚本将创建所需的表并插入将用于身份验证的数据。
setup.sql
CREATE TABLE `User` ( `user_id` varchar(10) NOT NULL DEFAULT '', `password` varchar(40) NOT NULL DEFAULT '', `name` varchar(40) NOT NULL DEFAULT '', `email` varchar(40) NOT NULL DEFAULT '', PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `User` (`user_id`, `password`, `name`, `email`) VALUES ('hyman', 'hyman123', 'hyman Kumar', '[email protected]');
Struts2,Hibernate和MySQL Maven依赖关系
我们需要在pom.xml文件中添加Struts2,Hibernate和MySQL maven依赖项,最终的pom.xml文件如下所示。
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Struts2Hibernate</groupId> <artifactId>Struts2Hibernate</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.15.1</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> <finalName>${project.artifactId}</finalName> </build> </project>
我们在示例中使用的是Hibernate 4,但是相同的代码也可以在Hibernate 3中使用。
尽管您可能需要进行一些配置,但休眠3的特定更改。
Struts2 Hibernate示例部署描述符
我们需要通过在部署描述符中应用StrutsPrepareAndExecuteFilter
在我们的Web应用程序中插入Struts2框架。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts2Hibernate</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> <listener> <listener-class>com.theitroad.struts2hibernate.listener.HibernateServletContextListener</listener-class> </listener> </web-app>
注意,HibernateServletContextListener
将用于管理Hibernate SessionFactory,稍后我们将看它的代码。
Entity Bean
我们的实体Bean还将用作struts2动作类模型Bean,如下所示。
User.java
package com.theitroad.struts2hibernate.model; public class User { private String id; private String name; private String pwd; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString(){ return "Name= "+name+", Email= "+email; } }
我正在使用基于XML的映射,但是我们也可以为我们的实体bean使用基于JPA注释的映射。
Hibernate DAO实现类
我们的UserDAO接口声明了将为User实体bean公开的方法。
UserDAO.java
package com.theitroad.struts2hibernate.dao; import com.theitroad.struts2hibernate.model.User; public interface UserDAO { User getUserByCredentials(String userId, String password); }
休眠特定的DAO实现如下所示。
UserDAOImpl.java
package com.theitroad.struts2hibernate.dao; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.theitroad.struts2hibernate.model.User; public class UserDAOImpl implements UserDAO { private SessionFactory sf; public UserDAOImpl(SessionFactory sf){ this.sf = sf; } @Override public User getUserByCredentials(String userId, String password) { Session session = sf.openSession(); Transaction tx = session.beginTransaction(); Query query = session.createQuery("from User where id=:id and pwd=:pwd"); query.setString("id", userId); query.setString("pwd", password); User user = (User) query.uniqueResult(); if(user != null){ System.out.println("User Retrieved from DB::"+user); } tx.commit();session.close(); return user; } }
Servlet上下文侦听器
我们将在ServletContextListener实现中初始化Hibernate SessionFactory,当应用程序停止时,我们将销毁SessionFactory。
HibernateServletContextListener.java
package com.theitroad.struts2hibernate.listener; import java.net.URL; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateServletContextListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { SessionFactory sf = (SessionFactory) sce.getServletContext().getAttribute("SessionFactory"); sf.close(); } @Override public void contextInitialized(ServletContextEvent sce) { URL url = HibernateServletContextListener.class.getResource("/hibernate.cfg.xml"); Configuration config = new Configuration(); config.configure(url); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(config.getProperties()).build(); SessionFactory sf = config.buildSessionFactory(serviceRegistry); sce.getServletContext().setAttribute("SessionFactory", sf); } }
Struts2动作类
我们已经准备好了休眠专用的设置,让我们继续Struts2动作类。
LoginAction.java
package com.theitroad.struts2hibernate.action; import javax.servlet.ServletContext; import org.apache.struts2.util.ServletContextAware; import org.hibernate.SessionFactory; import com.theitroad.struts2hibernate.dao.UserDAO; import com.theitroad.struts2hibernate.dao.UserDAOImpl; import com.theitroad.struts2hibernate.model.User; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ModelDriven; public class LoginAction implements Action, ModelDriven<User>, ServletContextAware { @Override public String execute() throws Exception { SessionFactory sf = (SessionFactory) ctx.getAttribute("SessionFactory"); UserDAO userDAO = new UserDAOImpl(sf); User userDB = userDAO.getUserByCredentials(user.getId(), user.getPwd()); if(userDB == null) return ERROR; else { user.setEmail(userDB.getEmail()); user.setName(userDB.getName()); return SUCCESS; } } @Override public User getModel() { return user; } private User user = new User(); private ServletContext ctx; @Override public void setServletContext(ServletContext sc) { this.ctx = sc; } }
Struts2,Hibernate配置和Hibernate映射XML
我们在Struts2配置文件中具有以下URI配置。
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "https://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.devMode" value="true"></constant> <constant name="struts.convention.result.path" value="/"></constant> <package name="user" namespace="/User" extends="struts-default"> <action name="home"> <result>/login.jsp</result> </action> <action name="login" class="com.theitroad.struts2hibernate.action.LoginAction"> <result name="success">/welcome.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
休眠配置文件如下所示。
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection properties - Driver, URL, user, password --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property> <property name="hibernate.connection.username">hyman</property> <property name="hibernate.connection.password">hyman123</property> <!-- Connection Pool Size --> <property name="hibernate.connection.pool_size">1</property> <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! --> <property name="hibernate.current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Outputs the SQL queries, should be disabled in Production --> <property name="hibernate.show_sql">true</property> <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc Hibernate 4 automatically figure out Dialect from Database Connection Metadata --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- mapping file, we can use Bean annotations too --> <mapping resource="User.hbm.xml" </session-factory> </hibernate-configuration>
Hibernate Mapping XML文件如下所示。
User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.theitroad.struts2hibernate.model.User" table="USER"> <id name="id" type="java.lang.String"> <column name="USER_ID" <generator class="assigned" </id> <property name="name" type="java.lang.String"> <column name="NAME" </property> <property name="pwd" type="java.lang.String"> <column name="PASSWORD" </property> <property name="email" type="java.lang.String"> <column name="EMAIL" </property> </class> </hibernate-mapping>
Struts2查看页面
从struts2配置文件中可以看到,我们有三个视图页面。
它们是简单的页面,如下所示。
login.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <%-- Using Struts2 Tags in JSP --%> <%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Login Page</title> </head> <body> <h3>Welcome User, please login below</h3> <s:form action="login"> <s:textfield name="id" label="User ID"></s:textfield> <s:textfield name="pwd" label="Password" type="password"></s:textfield> <s:submit value="Login"></s:submit> </s:form> </body> </html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Welcome Page</title> </head> <body> <h3>Welcome <s:property value="name"></s:property></h3> <h3>Your id is <s:property value="id"></s:property></h3> <h3>Your password is <s:property value="pwd"></s:property></h3> <h3>Your email id is <s:property value="email"></s:property></h3> </body> </html>
error.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Error Page</title> </head> <body> <h4>User Name or Password is wrong</h4> <s:include value="login.jsp"></s:include> </body> </html>