struts2+spring+hibernate的简单实例
需求: 查询用户列表
技术: struts2+spring+hibernate, oracle, myeclipse
一、工程结构
jar包: 【有些包没用到】
antlr-2.7.7.jar
aspectjrt.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar
common-annotations.jar
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-dbcp.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
commons-pool.jar
commons-validator-1.3.1.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
ejb3-persistence.jar
freemarker-2.3.15.jar
hibernate-annotations.jar
hibernate-cglib-repack-2.1_3.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-entitymanager.jar
hibernate3.jar
javassist-3.9.0.GA.jar
jstl-1.0.2.jar
jta-1.1.jar
log4j-api-2.7.jar
log4j.jar
ognl-2.7.3.jar
ojdbc14.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.6.1.jar
spring-webmvc-struts.jar
spring.jar
struts2-core-2.1.8.1.jar
struts2-spring-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar
二、正式开发
(1)配置文件
** web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 5 id="WebApp_ID" version="3.1"> 6 <display-name>ssh</display-name> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 <welcome-file>index.html</welcome-file> 10 <welcome-file>index.htm</welcome-file> 11 <welcome-file>default.html</welcome-file> 12 <welcome-file>default.htm</welcome-file> 13 <welcome-file>default.jsp</welcome-file> 14 </welcome-file-list> 15 16 <!-- Spring配置和监听start --> 17 <context-param> 18 <param-name>contextConfigLocation</param-name> 19 <param-value>classpath:applicationContext.xml</param-value> 20 </context-param> 21 <listener> 22 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 23 </listener> 24 25 <!-- 拦截请求 --> 26 <filter> 27 <filter-name>struts2</filter-name> 28 <filter-class> 29 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 30 </filter-class> 31 </filter> 32 <filter-mapping> 33 <filter-name>struts2</filter-name> 34 <url-pattern>*.action</url-pattern> 35 </filter-mapping> 36 </web-app>
** struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 3 4 <struts> 5 <constant name="struts.objectFactory" value="spring" /> 6 7 <package name="ssh" extends="struts-default"> 8 <global-results> 9 <result name="error">/WEB-INF/jsp/error.jsp</result> 10 <result name="success">/WEB-INF/jsp/success.jsp</result> 11 </global-results> 12 13 <action name="query" class="com.jg.ssh.action.UserAction" method="queryUsers" /> 14 </package> 15 </struts>
** applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 5 6 <!-- 数据库配置 --> 7 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 8 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"> 9 </property> 10 <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"> 11 </property> 12 <property name="username" value="Peter"></property> 13 <property name="password" value="123"></property> 14 </bean> 15 16 <!-- 配置会话工厂SessionFactory --> 17 <bean id="sessionFactory" 18 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 19 <property name="dataSource"> 20 <ref bean="dataSource" /> 21 </property> 22 <property name="hibernateProperties"> 23 <props> 24 <prop key="hibernate.dialect"> 25 org.hibernate.dialect.Oracle10gDialect 26 </prop> 27 <prop key="hibernate.hbm2ddl.auto">update</prop> 28 </props> 29 </property> 30 <!-- 配置实体描述文件 --> 31 <property name="mappingResources"> 32 <list> 33 <value>com/jg/ssh/pojo/User.hbm.xml</value> 34 </list> 35 </property> 36 </bean> 37 38 <bean id="userAction" class="com.jg.ssh.action.UserAction" scope="prototype"> 39 <property name="userService" ref="userService"></property> 40 </bean> 41 42 <bean id="userService" class="com.jg.ssh.service.UserService"> 43 <property name="baseDao" ref="baseDao"></property> 44 </bean> 45 46 <bean id="baseDao" class="com.jg.ssh.dao.BaseDao"> 47 <property name="sessionFactory" ref="sessionFactory" /> 48 </bean> 49 </beans>
** log4j.properties
1 log4j.rootLogger = DEBUG, stdout 2 log4j.appender.stdout = org.apache.log4j.ConsoleAppender 3 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout 4 log4j.appender.stdout.layout.ConversionPattern =%d{ISO8601} %-5p [%F\:%L] \: %m%n
(2)各层
** com.jg.ssh.pojo
User.java
private Integer id; private String username; private String sex; private String password; private String telephone; private String address;
User.hbm.xml
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 5 <hibernate-mapping> 6 <class name="com.jg.ssh.pojo.User" table="TB_USER"> 7 <id name="id" type="java.lang.Integer"> 8 <column name="ID" /> 9 <generator class="native" /> 10 </id> 11 <property name="username" type="java.lang.String"> 12 <column name="USERNAME" /> 13 </property> 14 <property name="sex" type="java.lang.String"> 15 <column name="SEX" /> 16 </property> 17 <property name="password" type="java.lang.String"> 18 <column name="PASSWORD" /> 19 </property> 20 <property name="telephone" type="java.lang.String"> 21 <column name="TELEPHONE" /> 22 </property> 23 <property name="address" type="java.lang.String"> 24 <column name="ADDRESS" /> 25 </property> 26 </class> 27 </hibernate-mapping>
** com.jg.ssh.dao
BaseDao.java
1 package com.jg.ssh.dao; 2 3 import java.util.List; 4 5 import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 6 7 /** 8 * 基础DAO 9 */ 10 public class BaseDao extends HibernateDaoSupport { 11 /** 12 * 根据hql语句查询用户列表 13 * @param hql 14 * @return 用户列表 15 */ 16 @SuppressWarnings("unchecked") 17 public <T>List<T> getObjects(String hql) { 18 List<T> userList = this.getHibernateTemplate().find(hql); 19 return userList; 20 } 21 22 @SuppressWarnings({ "unchecked", "rawtypes" }) 23 public <T>List<T> getAllObjects(Class clazz) { 24 return this.getHibernateTemplate().loadAll(clazz); 25 } 26 }
** com.jg.ssh.service
UserService.java
1 package com.jg.ssh.service; 2 3 import java.util.List; 4 5 import com.jg.ssh.dao.BaseDao; 6 import com.jg.ssh.pojo.User; 7 8 /** 9 * 用户Service 10 */ 11 public class UserService { 12 private BaseDao baseDao; 13 14 /** 15 * 获取用户列表 16 * @param username 17 * @param clazz 18 * @return 用户列表 19 */ 20 @SuppressWarnings("rawtypes") 21 public List<User> getUsers(String queryText, Class clazz) { 22 if (queryText == null || "".equals(queryText)) { 23 return baseDao.getAllObjects(clazz); 24 } 25 26 String hql = "FROM User WHERE username = '" + queryText + "'"; 27 // String hql = "FROM User WHERE username = '" + queryText + "'"; 28 return baseDao.getObjects(hql); 29 } 30 31 public BaseDao getBaseDao() { 32 return baseDao; 33 } 34 35 public void setBaseDao(BaseDao baseDao) { 36 this.baseDao = baseDao; 37 } 38 }
** com.jg.ssh.action
UserAction.java
1 package com.jg.ssh.action; 2 3 import java.util.List; 4 5 import com.jg.ssh.pojo.User; 6 import com.jg.ssh.service.UserService; 7 import com.jg.ssh.util.ServletContextUtil; 8 import com.opensymphony.xwork2.ActionSupport; 9 10 /** 11 * 用户控制器 12 */ 13 @SuppressWarnings("serial") 14 public class UserAction extends ActionSupport { 15 private UserService userService; 16 17 /** 18 * 根据条件查询用户列表 19 * @return 用户列表 20 */ 21 public String queryUsers() { 22 String param = ServletContextUtil.getRequest().getParameter("queryText"); 23 List<User> users = userService.getUsers(param, User.class); 24 ServletContextUtil.getRequest().setAttribute("users", users); 25 return SUCCESS; 26 } 27 28 public UserService getUserService() { 29 return this.userService; 30 } 31 32 public void setUserService(UserService userService) { 33 this.userService = userService; 34 } 35 }
** com.jg.ssh.util
ServletContextUtil.java
1 package com.jg.ssh.util; 2 3 import javax.servlet.http.HttpServletRequest; 4 5 import org.apache.struts2.ServletActionContext; 6 7 import com.opensymphony.xwork2.ActionSupport; 8 9 @SuppressWarnings("serial") 10 public class ServletContextUtil extends ActionSupport { 11 public static HttpServletRequest getRequest() { 12 return ServletActionContext.getRequest(); 13 } 14 }
(3) 页面
index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme() + "://" 5 + request.getServerName() + ":" + request.getServerPort() 6 + path + "/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 <title>首页</title> 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 </head> 20 21 <body> 22 <form action="${pageContext.request.contextPath}/query.action" method="post"> 23 用户名:<input type="text" name="queryText"/> 24 <input type="submit" value="查询"/> 25 </form> 26 </body> 27 </html>
success.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme() + "://" 6 + request.getServerName() + ":" + request.getServerPort() 7 + path + "/"; 8 %> 9 10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 11 <html> 12 <head> 13 <base href="<%=basePath%>"> 14 <title>成功页面</title> 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="This is my page"> 20 21 </head> 22 23 <body> 24 <center> 25 <c:if test="${empty users}"> 26 <h3>无任何员工信息!</h3> 27 </c:if> 28 <c:if test="${not empty users}"> 29 <table border="1px" cellpadding="5" cellspacing="0" style="width: 40%;margin-top: 50px;"> 30 <tr> 31 <td>用户ID</td> 32 <td>用户名</td> 33 <td>性别</td> 34 <td>密码</td> 35 <td>手机</td> 36 <td>地址</td> 37 </tr> 38 <c:forEach items="${users }" var="user"> 39 <tr> 40 <td><c:out value="${user.id }" /></td> 41 <td><c:out value="${user.username }" /></td> 42 <td><c:out value="${user.sex }" /></td> 43 <td><c:out value="${user.password }" /></td> 44 <td><c:out value="${user.telephone }" /></td> 45 <td><c:out value="${user.address }" /></td> 46 </tr> 47 </c:forEach> 48 </table> 49 </c:if> 50 </center> 51 </body> 52 </html>
error.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme() + "://" 5 + request.getServerName() + ":" + request.getServerPort() 6 + path + "/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 <title>错误页面</title> 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 20 </head> 21 22 <body> 23 <h1>访问出错!</h1> 24 </body> 25 </html>
Oracle数据库
-- Create table create table TB_USER ( ID NUMBER not null, USERNAME VARCHAR2(32) not null, SEX VARCHAR2(5), PASSWORD VARCHAR2(32) not null, TELEPHONE VARCHAR2(32), ADDRESS VARCHAR2(255) ) tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64 next 1 minextents 1 maxextents unlimited ); -- Add comments to the columns comment on column TB_USER.ID is '用户ID'; comment on column TB_USER.USERNAME is '用户名'; comment on column TB_USER.SEX is '性别'; comment on column TB_USER.PASSWORD is '密码'; comment on column TB_USER.TELEPHONE is '电话'; comment on column TB_USER.ADDRESS is '地址'; -- Create/Recreate primary, unique and foreign key constraints alter table TB_USER add constraint ID primary key (ID) using index tablespace USERS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited );
测试结果: