1. 程式人生 > >SSH實現動態資料來源切換

SSH實現動態資料來源切換

目錄:

SSH的整合:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>dynamicDBsource</display-name>
  <welcome-file-list>
 
    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>
 
  
  
    <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>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  
</web-app>

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.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
    
       <action name="student_*" class="com.xh.dataSource.action.StuAction" method="{1}">
       		<result name="addUI">/WEB-INF/view/addUI.jsp</result>
   			<result name="list">/WEB-INF/view/list.jsp</result>
   			<result name="add">/WEB-INF/view/list.jsp</result>
   			<result name="#">index.jsp</result>
       		
   
       </action>
       
      
    </package>

</struts>

applicatonContext.xml

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

	<!--自動掃描和裝配 -->
	<context:component-scan base-package="com.xh.dataSource"></context:component-scan>
	
	<!-- 匯入外部的properties檔案 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	
		<!-- 指定hibernate的配置檔案位置 -->
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
		<!-- c3p0資料庫連線資訊 -->
		<property name="dataSource" ref="MYdataSource"></property>
			

	</bean>
	
	
	
	<bean id="MYdataSource" class="com.xh.dataSource.ds.MyDataSource">
		<property name="targetDataSources"> 
	     	<map key-type="java.lang.String">  
	        		<entry key="dataSource0" value-ref="dataSource0"/>  
	         		<entry key="dataSource1" value-ref="dataSource1"/>  
	      	</map>  
   		</property>  
  		<property name="defaultTargetDataSource" ref="dataSource1"/>  
	</bean>
	
	
	
	<bean id="dataSource0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql:///db0"></property>
		<property name="driverClass" value="com.jdbc.mysql.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
				
	</bean>
	
	
	
	<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql:///db1"></property>
		<property name="driverClass" value="com.jdbc.mysql.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
				
	</bean>
	
	
	
	<!-- 配置宣告式事務管理(採用註解的方式) -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="txManager"/>
	
	</beans>

hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    
    	<!-- 1,資料庫連線資訊 -->
	<property name="dialect">
		org.hibernate.dialect.MySQL5InnoDBDialect
	</property>


	<!-- 2,其他配置 -->
	<property name="show_sql">true</property>
	<property name="hbm2ddl.auto">update</property>

	<!-- 3,匯入對映檔案 -->
	<mapping resource="com/xh/dataSource/entity/Student.hbm.xml" />
	
    	
    </session-factory>
</hibernate-configuration>

action

package com.xh.dataSource.action;

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

import javax.annotation.Resource;


import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.xh.dataSource.ds.DataSourceContextHolder;
import com.xh.dataSource.ds.MyDataSource;
import com.xh.dataSource.entity.Student;
import com.xh.dataSource.service.StuService;


public class StuAction extends ActionSupport implements ModelDriven<Student> ,RequestAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource
	StuService stuService;

	
	Map<String, Object> request=new HashMap<>();
	
	List<Student> stus;
	public List<Student> getStus() {
		return stus;
	}



	public void setStus(List<Student> stus) {
		this.stus = stus;
	}




	@Resource
	Student stu;

	public String list()
	{
		stus=stuService.lsit();
		System.out.println("stus:>>"+stus.size());
		ActionContext.getContext().put("stusList", stus);
		return "list";
	}
	
	
	
	public String add()
	{	
		System.out.println("ID>>>"+stu.getId()+"NAME>>>"+stu.getName());
		stuService.add(stu);
		return "add";
	}
	
	
	
	
	public String addUI()
	{
		return "addUI";
	}


	
	
	
	public String dataSource0() {
		DataSourceContextHolder.setDataSourceType("dataSource0");
		return "#";
	}

	public String dataSource1() {
		DataSourceContextHolder.setDataSourceType("dataSource1");
		return "#";
	}
	

	@Override
	public Student getModel() {
		// TODO Auto-generated method stub
		stu=new Student();
		return stu;
	}



	@Override
	public void setRequest(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		request=arg0;
	}
	
	
	
	
}

service

package com.xh.dataSource.service;


import java.util.List;


import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.xh.dataSource.dao.StuDao;
import com.xh.dataSource.entity.Student;
@Component
public class StuService {

	@Resource
	StuDao stuDao;
	
	public List<Student> lsit() {
		return stuDao.list();
		
	}
	
	
	
	public void add(Student stu) {
		System.out.println("service---ID>>>"+stu.getId()+"NAME>>>"+stu.getName());
		stuDao.add(stu);
		
	}
}


dao

package com.xh.dataSource.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.xh.dataSource.entity.Student;
@Component
public class StuDao {
	@Resource
	SessionFactory sessionFactory;
	
	
	@SuppressWarnings("unchecked")
	public List<Student> list() {
		List<Student> stus=new ArrayList<>();
		stus=sessionFactory.openSession().createQuery("FROM Student").list();
		return stus;
		
	}
	
	
	@Transactional
	public void add(Student stu) {
		System.out.println("dao----ID>>>"+stu.getId()+"NAME>>>"+stu.getName());
		sessionFactory.openSession().save(stu);
		
	}
}

entity

package com.xh.dataSource.entity;

import org.springframework.stereotype.Component;

@Component
public class Student {

	private Long id;
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}

*.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-2-3 9:36:30 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.xh.dataSource.entity.Student" table="STUDENT">
        <id name="id" >
            <column name="ID" default="1" />
            <generator class="native"  />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
    </class>
</hibernate-mapping>



資料來源切換相關

ds:

package com.xh.dataSource.ds;

public class DataSourceContextHolder {
	
	@SuppressWarnings("rawtypes")
	private static final ThreadLocal contextHolder=new ThreadLocal();  
    
    @SuppressWarnings("unchecked")
	public static void setDataSourceType(String dataSourceName){  
        contextHolder.set(dataSourceName);  
    }  
       
    public static String getDataSourceName(){  
        return (String) contextHolder.get();  
    }  
       
    public static void clearDataSourceType(){  
        contextHolder.remove();  
    }  
    
    
    
    
}

package com.xh.dataSource.ds;

import java.sql.SQLFeatureNotSupportedException;
import java.util.Map;
import java.util.logging.Logger;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;
import org.springframework.stereotype.Component;



public class MyDataSource extends AbstractRoutingDataSource{


	private Map<String,String> myds;


	public Map<String,String> getMyds() {
		return myds;
	}

	public void setMyds(Map<String,String> myds) {
		this.myds = myds;
	}

	 @Override  
	    public Object determineCurrentLookupKey() {  
	        return DataSourceContextHolder.getDataSourceName();  
	    }  
	   
	    @Override  
	    public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {  
	        super.setDataSourceLookup(dataSourceLookup);  
	    }  
	   
	    @Override  
	    public void setDefaultTargetDataSource(Object defaultTargetDataSource) {  
	        super.setDefaultTargetDataSource(defaultTargetDataSource);  
	    }  
	   
	    @Override  
	    public void setTargetDataSources(Map targetDataSources) {  
	        super.setTargetDataSources(targetDataSources);  
	        //重點  
	        super.afterPropertiesSet();  
	    }

		@Override
		public Logger getParentLogger() throws SQLFeatureNotSupportedException {
			// TODO Auto-generated method stub
			return null;
		}  
	
}

前臺頁面:

index.jap

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="student_addUI">ADDstudents</a>
<br>
<br>
<a href="student_list">LISTstudents</a>
<br>
<br>
<a href="student_dataSource0">dataSource0</a>
<br>
<br>
<a href="student_dataSource1">dataSource1</a>
</body>
</html>

list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib prefix="s" uri="/struts-tags" %>         
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<s:iterator value="#stusList">
<tr>
<td>${id}</td>
<td>${name}</td>
<br>

</tr>
		

</s:iterator>

</body>
</html>

addUI.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<s:form action="student_add" method="post">
	<s:textfield name="id" label="學生ID"></s:textfield>
	<s:textfield name="name" label="學生姓名"></s:textfield>
	<input type="submit" value="提  交"/s>
</s:form>

</body>
</html>