码迷,mamicode.com
首页 > 其他好文 > 详细

SSH2整合--配置+详解

时间:2015-08-27 00:30:34      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

      

        最近的项目做完了,整理整理用到的技术,也顺便系统地回顾一下框架基础,防止学而不思则罔,思而不学则殆.

 

       先说说框架整合.最初的架构是最简单的Struts2+Spring3+Hibernate3,数据库使用的是MySQL.分别列出整合需要的jar.

Struts:

		commons-fileupload.jar
		Commons-io.jar
		Freemarker.jar
		Ognl.jar
		Struts2-core.jar
		Xwork-core.jar
		servlet-api.jar

Hibernate:

		Hibernate3.jar
		Required:
			antlr.jar
			Commons-collections.jar
			Dom4j.jar
			Javassist.jar
			Jta.jar
			Slf4j-api.jar
			Slf4j-log4j.jar
			mysql-connector-java-bin.jar
		Optional:
			c3p0.jar
		Jpa:
			Hibernate-jpa.jar

Spring:

		spring.jar
		commons-logging.jar,
		log4j.jar
		aspectJjrt.jar,
		aspectJweaver.jar,
		cglib-nodep.jar
		struts2-spring-plugin.jar


       各部分的配置及文件分别是

       struts.xml;

      Hibernate.cfg.xml,*.hbm.xml,jdbc.properties,Log4j.properties;

      applicationContext.xml;

      因为Spring集成了Hibernate,所有Hibernate.cfg.xml中的配置就可以直接配置到applicationContext.xml中了.这样一来对于我们这样的Spring爱好者来说就方便多了.有了这些,后面在web.xml中再进行一些配置就可以了.一般我们总是先整合Spring和Hibernate,再整合Struts,不为别的,方便调错.

 

 

         applicationContext.xml内容如下:
 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
	http://www.springframework.org/schema/tx  
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<!-- 自动扫描与装配bean -->
<context:component-scan base-package="com.tgb.oa"></context:component-scan>

<!-- 导入外部的properties文件 -->
   <context:property-placeholder location="classpath:jdbc.properties"/>
	
<!-- 配置sessionFactory,将Hibernate中的事务交给spring管理 -->
   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	     
	      <!-- 配置数据库连接池,指定sessionFactory中的数据源 -->
	      <property name="dataSource">
		    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
		 	<!-- 数据库连接信息 -->
		 	<property name="jdbcUrl" value="${jdbcUrl}"></property>
		 	<property name="driverClass" value="${driverClass}"></property>
		 	<property name="user" value="${user}"></property>
		 	<property name="password" value="${password}"></property>
		 		
		 	<!-- 其他配置 -->		 		
		 	<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
			<property name="initialPoolSize" value="3"></property>
			<!--连接池中保留的最小连接数。Default: 3 -->
			<property name="minPoolSize" value="3"></property>
			<!--连接池中保留的最大连接数。Default: 15 -->
			<property name="maxPoolSize" value="5"></property>
			<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
			<property name="acquireIncrement" value="3"></property>
			<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
			<property name="maxStatements" value="8"></property>
			<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
			<property name="maxStatementsPerConnection" value="5"></property>
			<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
			<property name="maxIdleTime" value="1800"></property>
		 		 		
		    </bean>
	     </property>
	     <!-- 指定hibernate的属性  -->  
   	     <property name="hibernateProperties">  
       	        <value>  
            	    <!-- hibernate使用的 方言 -->  
	            hibernate.dialect=org.hibernate.dialect.Oracle10gDialect  
	            <!-- 根据实体的映射文件生成表结构 -->  
	            hibernate.hbm2ddl.auto=update	              
	            <!-- 是否打印出sql语句 -->  
	            hibernate.show_sql=false  
	         </value>  
	     </property>
	     <!-- Hibernate的映射文件 -->
	     <property name="mappingResources">
		 <list>
		 	<value>com/tgb/oa/domain/User.hbm.xml</value>
		 	<value>com/tgb/oa/domain/Role.hbm.xml</value>
		 </list>
	     </property>
   </bean>	 
   <!-- 配置使用基于Hibernate的事务管理器 -->
   <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
   	 <!-- 通过sessionfactory开启事务 -->
   	 <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
   <!--声明式事务管理(采用注解的方式) -->
   <tx:annotation-driven transaction-manager="txManager"/>
</beans>


      这里读到的一个文件是jdbc.properties,当我们要修改连接信息时,只要修改该文件即可.

jdbcUrl=jdbc:mysql:///projectoa
driverClass=com.mysql.jdbc.Driver
user=root
password=root

 

        然后是映射部分Role.java

 

package com.tgb.oa.domain;

/**
 * 岗位
 * 
 * @author ghy version 3.0.0 , 2015年8月14日 下午10:22:59
 */
public class Role {

	private Long id;

	private String name;

	private String description;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}

       Role.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.tgb.oa.domain">
	<class name="Role" table="projectoa_role">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name"></property>
		<property name="description"></property>
		
	</class>

</hibernate-mapping>


      接下来在web.xml中指定spring的配置文件.

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

<!-- 配置spring的监听器 -->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext*.xml</param-value>
</context-param>

<!-- 配置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.html</welcome-file>
    </welcome-file-list>

</web-app>


       现在Hibernate已经纳入Spring的管理了.看看下面的业务代码,Service层的bean也已经被Spring管理了.

        RoleServiceBeanImpl.java:

 

package com.tgb.oa.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tgb.oa.dao.RoleDao;
import com.tgb.oa.domain.Role;
import com.tgb.oa.service.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleDao roleDao;

	@Override
	public List<Role> findAll() {
		List<Role> roleList = roleDao.findAll();
		return roleList;

	}

	@Override
	public void delete(Long id) {
		roleDao.delete(id);

	}

	@Override
	public void save(Role role) {
		roleDao.save(role);
	}

	@Override
	public Role getById(Long id) {

		Role role = roleDao.getById(id);
		return role;

	}

	@Override
	public void update(Role role) {
		roleDao.update(role);
	}

}


        @Service: 该注解添加到业务层,表示这个类由spring管理.   

        @Transactional:该注解添加的类采用事务管理,类中所有的方法都有事务特性.  当某个方法不需要事务时,添加注解属性@Transactional(propagation=Propagation.NOT_SUPPORTED) .前面在web.xml中配置spring时,也顺便加上了Struts的内容.也就是说,action现在被spring管理.而action被spring管理与否的区别就是在Struts.xml中配置action时,<action name="role_*" class="roleAction">class属性是否必须写明包名,有了spring是不需要写的.

 

RoleAction.java代码如下:

 

package com.tgb.oa.view.action;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.tgb.oa.domain.Role;
import com.tgb.oa.service.RoleService;

/**
 * 岗位管理action
 * 
 * @author ghy version 3.0.0 , 2015年8月17日 下午10:07:42
 */
@Controller
@Scope("prototype")
public class RoleAction extends ActionSupport implements ModelDriven<Role> {

	@Resource
	private RoleService roleService;
	private Role model = new Role();

	@Override
	public Role getModel() {
		return model;
	}	

	// 列表
	public String list() throws Exception {
		List<Role> roleList = roleService.findAll();
		ActionContext.getContext().put("roleList", roleList);
		return "list";
	}

	// 添加页面
	public String addUI() throws Exception {
		return "saveUI";
	}

	// 添加
	public String add() throws Exception {

		roleService.save(model);
		return "toList";
	}

	// 修改页面
	public String editUI() throws Exception {
		// 准备回显的数据
		Role role = roleService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(role);
		return "saveUI";
	}

	// 修改
	public String edit() throws Exception {
		// 从数据库中取原对象
		Role role = roleService.getById(model.getId());
		// 设置要修改的属性
		role.setName(model.getName());
		role.setDescription(model.getDescription());
		// 更新到数据库
		roleService.update(role);
		return "toList";
	}

}

        配置action的注解@scope,因为Struts2是多例的,要求每一个action都是一个新的对象,但是把Action交给Spring管理后,action就是单例模式了,这就违背了Struts2的设计理念,所以我们需要将action 声明为原型@Scope("prototype").  


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>
	<!-- 配置为开发模式 -->
    <constant name="struts.devMode" value="false" />
	<!-- 把扩展名配置为action -->
	<constant name="struts.action.extension" value="action" />
	<!-- 把主题配置为simple -->
	<constant name="struts.ui.theme" value="simple" />
	
    <package name="default" namespace="/" extends="struts-default">
        <!--当struts2与spring整合后,class属性可以写bean的名称 -->
         <action name="test" class="testAction">
         	<result name="success">/test.jsp</result>         
         </action>         
   
   		<action name="role_*" class="roleAction" method="{1}">
   			<result name="list" >/WEB-INF/jsp/roleAction/list.jsp</result>
   			<result name="toList" type="redirectAction">role_list</result>
   			<result name="saveUI">/WEB-INF/jsp/roleAction/saveUI.jsp</result>			   			
   		</action>   
    </package>  
</struts>


        很多项目都是SSH做的,所以总结起来还是比较顺手的.关于框架整合这点事儿,还是要看框架设计者的意思,最好用的方法就是按着人家给设计好的去用,直接又便捷.




版权声明:本文为博主原创文章,未经博主允许不得转载。

SSH2整合--配置+详解

标签:

原文地址:http://blog.csdn.net/zhuanzhe117/article/details/48014545

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!