Spring3+Struts2+Hibernate4+Mybatis整合的一个maven例子

说明:

1.用了maven去搞这个demo,懒得去导jar包。。。

2.这个demo用了spring去做Ioc,事务的aop;用了struts2去做“MVC”(没有用到任何UI技术,有点对不起这个MVC,就单单一个后台。。。);用了hibernate和Mybatis两个持久层,用上MyBatis是用来应对复杂的SQL查询逻辑,结果集映射也灵活。

3.此demo目的只是一个笔记,搞java web 开发的都懂的,要学的太多,很多东西过段时间不接触就忘了,也用作一个测试环境同时也是给自己的一个小礼物以自勉之,下周鄙人就要跳去搞外包了。。。只因实力不济啊,吾为索道不辞路远,希望未来有所长进。。。

4.很遗憾,Junit test 用不了。。。

 

demo的整合大致示意图:Spring3+Struts2+Hibernate4+Mybatis整合的一个maven例子_第1张图片

demo的目录结构:

Spring3+Struts2+Hibernate4+Mybatis整合的一个maven例子_第2张图片
 

 

给出demo用到的依赖包,pom.xml:


	4.0.0
	org.oham.ssh
	ssh
	war
	0.0.1-SNAPSHOT
	ssh Maven Webapp
	http://maven.apache.org


	
	
		UTF-8
		3.1.0.RELEASE
		2.3.15.1
		4.1.4.Final
		3.1.1
	

	
	
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				2.3.2
				
					1.6
					1.6
				
			
		
	 

	
	

		
		
			org.springframework
			spring-core
			${spring.version}
		
		
		
			org.springframework
			spring-beans
			${spring.version}
		
            
           
	        org.springframework  
	        spring-context  
			${spring.version}
    	  
      
	      
	        org.springframework  
	        spring-web  
			${spring.version}
	        
	    
	      
	        org.springframework  
	        spring-orm  
	        3.1.1.RELEASE  
	      
	    
	    
			org.springframework
			spring-tx
			3.1.1.RELEASE
		
		
		
		
		
        
			org.apache.struts
			struts2-core
			${struts2.version}
		

		
			org.apache.struts
			struts2-spring-plugin
			${struts2.version}
		
            
           
	      
	        org.apache.struts  
	        struts2-convention-plugin  
	        ${struts2.version}  
	      
	    
           
	    
			org.apache.struts
			struts2-config-browser-plugin
			${struts2.version}
		
		
           
		
			org.apache.struts
			struts2-json-plugin
			${struts2.version}
		
		
		
		
		
			com.mchange.c3p0
			com.springsource.com.mchange.v2.c3p0
			0.9.1.2
		
		
		
		
		
			mysql
			mysql-connector-java
			5.1.15
		
		
		
		
		
			org.hibernate
			hibernate-core
			${hibernate.version}
		
		
		
			org.hibernate
			hibernate-ehcache
			${hibernate.version}
		
		
		
			org.slf4j
			slf4j-log4j12
			1.6.1
		
		
		
		
		
			org.mybatis
			mybatis
			${mybatis.version}
		

		
			org.mybatis
			mybatis-spring
			1.1.1
		
		
		
		
		
			junit
			junit
			4.8.2
			test
		
		
		
		
		
			org.apache.openejb
			javaee-api
			5.0-1
			provided
		
		
			javax.faces
			jsf-api
			1.2_04
			provided
		
		
			javax.servlet
			jstl
			1.2
			provided
		
		
			javax.servlet.jsp
			jsp-api
			2.1
			provided
		
		
	
	

 

demo是web项目,web.xml:




	
	
		contextConfigLocation
		classpath:spring/applicationContext.xml,classpath:spring/**/applicationContext*.xml
	


	
	
		org.springframework.web.util.Log4jConfigListener
	
	
	
	
		struts2
		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
		
			config
			platform-web.xml,struts-default.xml,struts-plugin.xml,struts/struts.xml
		
	
	
		struts2
		*.action
	

	
	
		org.springframework.web.context.ContextLoaderListener
	


 

先看spring的配置,有两个,

applicationContext.xml:




	
	

	
	


	
	
	
	
	
	

 applicationContext-persistence.xml:




	
		
		
		
		
		
		
		
		
		
	
	
	
	
		
		
			
				#{dbProp.hibernate_dialect}
				#{dbProp.hibernate_showSql}
				#{dbProp.hibernate_formatSql}
				#{dbProp.hibernate_useSqlComments}
				#{dbProp.hibernate_hbm2ddlAuto}
				
				
				#{dbProp.hibernate_cacheProviderClass}
				#{dbProp.hibernate_cacheUseQueryCache}
				#{dbProp.hibernate_cacheUseSecondLevelCache}
			
		
		
		
		
		
			
				org/oham/learn/ssh/beans/TPerson.hbm.xml
			
		
	

	
	
	
		
		
	

	
	
		
		
	

	
	
	
	
	
	    
	 
	 	  
	 	
	 	  
	 	  
          
      
    
    
	
    

 

struts.xml:


  
  

 	  
    
    
  	  
    
      
      

   
      
    
      
      
    
     
     




	
	
		
			
		
		
			
		
	
	
	
  	  
          
            /WEB-INF/jsp/Main.jsp  
              
          
          
            /WEB-INF/jsp/Main.jsp  
          
      

  
   

 

基本配置写完了,现在挑选一个action试试,TestStrutsAction.java:

package org.oham.learn.ssh.controllers;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.oham.learn.ssh.beans.TGroup;
import org.oham.learn.ssh.beans.TPerson;
import org.oham.learn.ssh.beans.TUser;
import org.oham.learn.ssh.services.TestHibernateService;
import org.oham.learn.ssh.sqlmapper.TUserMapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.opensymphony.xwork2.ActionSupport;


/**
 * 此处的action由spring去负责实例化,默认是单例的,
 * 为迎合struts的action,现设置器scope为protoype
 */
@Service(value="testStrutsAction")
@Scope("prototype")
public class TestStrutsAction extends ActionSupport {
	private static final long serialVersionUID = 3362122496775495186L;
	
	@Resource(name="TestHibernate")
	private TestHibernateService testHibernateService;
	
	@Resource
	private TUserMapper tUserMapper;
	
	private Map jsonMap;
	
	/**
	 * 该action为xml方式配置的,此处测试其方法的调用,
	 * 用Hibernate执行了查询,此处的映射配置基于xml 
	 */
	public String testCall() {
		List list = testHibernateService.getTpersonList();
		for(TPerson p : list) {
			System.out.println(p.getName());
		}
		
		return "success";
	}
	
	/**
	 * 用Hibernate执行了查询,此处的映射配置基于annotation 
	 */
	public String testAnnotationCall() {
		List list = testHibernateService.getTGroupList();
		
		for(TGroup g : list) {
			System.out.println(g.getName());
		}
		
		return "success";
	}
	
	
	/**
	 * 测试json interceptor是否起作用
	 */
	public String testJsonCall() {
		jsonMap = new HashMap();
		jsonMap.put("a", "aa");
		jsonMap.put("b", "b");
		return "json";
	}
	
	/**
	 * 测试MyBatis 整合
	 */
	public String testMybatisCall() {
		TUser user = new TUser();
		user.setId(1);
		user.setName("oham");
		List list = tUserMapper.selectTUserByExample(user);
		for(TUser t : list) {
			System.out.println(t.getName());
		}
		return SUCCESS;
	}

	public Map getJsonMap() {
		return jsonMap;
	}
}

看其testCall方法, 用到一个注入的testHibernateService,进入看看,TestHibernateServiceImpl.java:

package org.oham.learn.ssh.services.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.oham.learn.ssh.beans.TGroup;
import org.oham.learn.ssh.beans.TPerson;
import org.oham.learn.ssh.services.TestHibernateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service(value="TestHibernate")
public class TestHibernateServiceImpl implements TestHibernateService {

	@Resource(name="sessionFactory")
	private SessionFactory factory;
	
	
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public List getTpersonList() {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(TPerson.class);
		List list = criteria.list(); 
		return list;
	}
	
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public List getTGroupList() {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(TGroup.class);
		List list = criteria.list();
		return list;
	}

}

  factory.getCurrentSession();这句,若当前没有事务,抛session closed异常的,可以注释@Transactional试试,方法调用结束,随着事务关闭,session也关闭。可以自己写个方法测试,形如:

@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public Session testSession() {
		Session session = factory.getCurrentSession();
		return session;
	}

 然后action里如此调用:

Session session = testHibernateService.testSession();
		Criteria criteria = session.createCriteria(TPerson.class);
		List list = criteria.list(); 

 

给出hibernate的映射相关,

 TPerson.java:

 

package org.oham.learn.ssh.beans;

import java.io.Serializable;


public class TPerson implements Serializable{
	private static final long serialVersionUID = 4135349486988951197L;
	
	private int id;
	private String name;
	private String address;
	private String tel;
	private String zipCode;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getZipCode() {
		return zipCode;
	}
	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}
}

 TPerson.hbm.xml:

 



  

	
		
			
		
		
		
			
			
			
	
	

 

TGroup.java,这个是基于hibernate的注解来做映射的:

 

package org.oham.learn.ssh.beans;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_group")
public class TGroup implements Serializable {
	private static final long serialVersionUID = 2177231731375781687L;

	@Id
	@Column(name="id")
	private int id;
	
	@Column(name="name", nullable= true)
	private String name;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

然后试着调用:http://你的IP加端口/ssh/struts/testCall.action,看看可否。也可调用本action的其他方法,诸如:http://你的IP加端口/ssh/struts/testCall!testJsonCall.action,再看看。

再给出基于struts注解形式注册的另一个action,TestStrutsAnnotationAction.java:

package org.oham.learn.ssh.controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.oham.learn.ssh.beans.TGroup;
import org.oham.learn.ssh.beans.TPerson;
import org.oham.learn.ssh.beans.TUser;
import org.oham.learn.ssh.services.TestHibernateService;
import org.oham.learn.ssh.sqlmapper.TUserMapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("ssh-default")
@Namespace("/sa")
@Scope(value="prototype")
@Component("saAction")
public class TestStrutsAnnotationAction extends ActionSupport{
	private static final long serialVersionUID = -2793512785203051741L;
	
	private Map jsonMap;
	
	@Resource(name="TestHibernate")
	private TestHibernateService testHibernateService;
	
	@Resource
	private TUserMapper tUserMapper;
	
	@Action(value="testSACall",
			results={
				@Result(name="success", location="/WEB-INF/jsp/Main.jsp")
	})
	public String testAnnotaionCall() {
		List list = testHibernateService.getTpersonList();
		for(TPerson p : list) {
			System.out.println(p.getName());
		}
		
		List list2 = testHibernateService.getTGroupList();
		for(TGroup g : list2) {
			System.out.println(g.getName());
		}
		return "success";
	}
	
	
	@Action(value="testSAMyBatis",
			results={
				@Result(name="success", location="/WEB-INF/jsp/Main.jsp")
	})
	public String testMyBatisCall() {
		List list = tUserMapper.selectTUserByExample(null);
		for(TUser t : list) {
			System.out.println(t.getName());
		}
		return SUCCESS;
	}
	
	@Action(value="testJ",
			results={@Result(name="json", type="json")})
	public String testJ() {
		
		jsonMap = new HashMap();
		jsonMap.put("a", "aa");
		jsonMap.put("b", "b");
		return "json";
		
	}

	public Map getJsonMap() {
		return jsonMap;
	}
}

 调用:诸如,http://你的IP加端口/ssh/sa/testSACall.action试试可否。

 

本demo用到了struts2-config-browser-plugin这个插件,主要用来看看注册的action有哪些,因为鄙人为了搞基于注解的struts action搞半天没成,起初不知原因为何,后来struts.xml中加上:就行了,但看别人的一些demo他们没加,所以至今也不太敢确定是否就是这个原因了。

 

调用http://你的IP加端口/ssh/config-browser/actionNames.action就可以看到成功注册的action。

 

完了,希望对诸君有所助。

 

附上项目源码ssh.zip,解压——>导入Existing Maven Project。

 

 

 

你可能感兴趣的:(系统架构)