struts2+spring3+hibernate3.5简单配置

这段时间因为工作需要,自己自学ssh框架,关于这个框架,网上的论文数不胜数,我也是在众多论文里不断的过滤,筛选成属于自己的,在学习的过程中,将很多复杂的,不必要的全都删掉了,现在说说我自己找到的最最简单的demo,这个是参考网上,然后自己写出来的。

这个demo是单纯的struts2、spring3、hibernate,没有使用任何注解的。加入注解和没加注解的写法、文件配置各方面都是不一样的,这里我会分开两篇文章记载。

第一、准备好开发环境:

myeclipse7.5、jdk1.6、tomcat6


第一、导入项目需要的包(jar包导到项目的lib文件夹下):


spring3.5的jar包从官网下载,解压后导入如下jar包:


第三、建一个空的java web项目


第四、需要做好配置

1、在WEB-INF里面web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<!-- spring配置 -->
	<context-param>
	<param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    
    <!-- 监听spring配置文件加载到容器 -->
    <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- spring提供的防止内存泄露的监听器 -->
    <listener>
       <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    
    <!-- spring的编码过滤器,请求的编码格式若不是encoding定义的,则会过滤掉 -->
    <!-- forceEncoding为true作用:不管请求的编码格式是什么,都会强制采用encoding里面的编码格式,响应同样也是 -->
    <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
	
	<!-- 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>
  
  
  <!-- 系统访问首页 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>


2、在WEB-INF里面applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
	<!-- 指定Spring配置文件的Schema信息 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 项目公共配置 -易受环境影响的配置环境-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
    <list>
    <!-- 本地服务器开发配置 -->
    <value>/WEB-INF/application.properties</value>
    <!-- 生产服务器开发配置 -->
    </list>
    </property>
    </bean>

   <!-- 公共配置也可使用这种方式:  <context:component-scan base-package="/WEB-INF/application.properties"></context:component-scan>-->
	
	<!-- 设置连接数据库的驱动、URL、用户名、密码 连接池最大连接数、最小连接数、初始连接数等参数 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<!-- Connection Info -->
	<property name="driverClassName" value="${jdbc.driver}"></property>
	<property name="url" value="${jdbc.url}"></property>
	<property name="username" value="${jdbc.username}"></property>
	<property name="password" value="${jdbc.password}"></property>	
	<!-- Connection Pooling Info -->	
	</bean>

	<!-- 定义Hibernate的SessionFactory -->
	<!-- 依赖注入数据源,注入正是上面定义的dataSource -->

        <bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
		p:dataSource-ref="dataSource">

		<!-- mappingResouces属性用来列出全部映射文件 -->
		<property name="mappingResources">
			<list>
				 以下用来列出Hibernate映射文件 
				<value>com/main/entity/User.hbm.xml
				</value>
			</list>
		</property>
		
		<!-- 定义Hibernate的SessionFactory的属性 -->
		<property name="hibernateProperties">
			<!-- 指定数据库方言、是否自动建表 是否生成SQL语句等 -->
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
			</props>
		</property>
	</bean>

	<!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->
	<!-- 该类实现PlatformTransactionManager接口,是针对Hibernate的特定实现 -->
	<!-- 并注入SessionFactory的引用 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager"
		p:sessionFactory-ref="sessionFactory" />

	<!-- 配置事务增强处理Bean,指定事务管理器 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 用于配置详细的事务语义 -->
		<tx:attributes>
			<!-- 所有以'get'开头的方法是read-only的 -->
			<tx:method name="get*" read-only="true" />
			<tx:method name="find*" read-only="true"/>
			<tx:method name="query*" read-only="true"/>
			<!-- 其他方法使用默认的事务设置 -->
			<tx:method name="*" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<!-- 配置一个切入点,匹配empManager和mgrManager 两个Bean的所有方法的执行 -->
		<aop:pointcut id="leePointcut" expression="execution(* com.main.service.*.*(..))" />
		<!-- 指定在leePointcut切入点应用txAdvice事务增强处理 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="leePointcut" />
	</aop:config>

	<bean id="userDao" class="com.main.dao.impl.UserDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<bean id="userService" class="com.main.service.UserServiceImpl">
		<property name="userDao" ref="userDao"></property>
	</bean>

	<bean id="loginAction" class="com.main.action.LoginAction">
		<property name="userService" ref="userService"></property>
	</bean>
	
</beans>

3、在WEB-INF里面application.properties

#JDBC Settings
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sshlearn?useUnicode=true&characterEncoding=utf-8
jdbc.username=
jdbc.password=

jdbc.initialPoolSize=1
jdbc.maxPoolSize=40
jdbc.minPoolSize=1

#Hibernate Settings
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

4、在项目的src里面struts.xml

<?xml version="1.0" encoding="UTF-8"?>
	<!-- 指定Struts2配置文件的DTD信息 -->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
	<constant name="struts.custom.i18n.resources" value="resource" />
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.objectFactory" value="spring" />
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="userLogin" class="com.main.action.LoginAction"
			method="execute">
			<result name="success">/success.jsp</result>
			<result name="error">/error.jsp</result>
		</action>
		
	</package>
	
</struts>


五、编写java代码----实现业务逻辑


1、UserDao和UserService是接口,而UserDaoImpl和UserServiceImpl分别是其两者的实现类

2、LoginAction代码:

package com.main.action;

import java.sql.Timestamp;

import com.main.entity.User;
import com.main.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private UserService userService;
	private String uName;
	private String pwd;

        public UserService getUserService() {
        return userService;
        }
        public void setUserService(UserService userService) {
            this.userService = userService;
        }
        public String getUName() {
		return uName;
	}
	public void setUName(String name) {
		uName = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public String execute(){
		if(null == uName || null == pwd){
			return "error";
		}
		try {
			User user = new User();
			user.setUName(uName);
			user.setPwd(pwd);
			user.setCreateTime(new Timestamp(System.currentTimeMillis()));
			userService.addUser(user);
			return "success";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
	}

}

3、UserService代码:

package com.main.service;

import com.main.entity.User;

public interface UserService {
public User getUser(String arg_Username);
public void addUser(User arg_User);
}

4、UserServiceImpl代码:

package com.main.service.impl;

import com.main.dao.UserDao;
import com.main.entity.User;
import com.main.service.UserService;

public class UserServiceImpl implements UserService {
	
	private UserDao userDao;
	

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void addUser(User arg_User) {
		// TODO Auto-generated method stub
		userDao.addUser(arg_User);
	}

	public User getUser(String arg_Username) {
		// TODO Auto-generated method stub
		return userDao.getUser(arg_Username);
	}

}

5、UserDao代码:

package com.main.dao;

import com.main.entity.User;

public interface UserDao {

   public User getUser(String arg_Username);
   
   public void addUser(User arg_User);
}

6、UserDaoImpl代码:


package com.main.dao.impl;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.main.dao.UserDao;
import com.main.entity.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	
	public User getUser(String arg_Username) {
		// TODO Auto-generated method stub
		User user = (User) getHibernateTemplate().find("from User u where u.UName="+arg_Username);		
		return user;
	}

	public void addUser(User arg_User) {
		// TODO Auto-generated method stub
		if(null != arg_User)
		{
			getHibernateTemplate().getSessionFactory().getCurrentSession().save(arg_User);
		}
	}

}

7、index.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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <form action="userLogin" method="post">
       用户名:<input name="uName" type="text"><br/>
       密码:<input name="pwd" type="password"><br/>
   <input type="submit" value="提交"> <input type="reset" value="重置"> 
</form>
  </body>
</html>

总结:以上就是没有使用注解单纯使用xml里面的bean将hibernate的SessionFactory和spring的Dao类结合在一起使用,通过struts.xml将jsp的请求映射到对应的java Action类里。虽然在功能上是满足了从jsp发送数据到action再从action通过一连串的数据逻辑处理存储到数据库里去,但是其关系配置需要写很多代码,我们每定义一个dao类就需要在applicationContext.xml里定义一堆bean来映射dao类和hibernate之间的关系。如果项目过大,那么就不知道要写多少个xml文件了,这样很不方便管理,整个项目的开发架构看起来也显得冗余。

以上只代表我的个人想法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值