(可以跑通的,有数据库的,mchange+ aop )springmvc+jdbctemplate+mchange+multidatasource

 基于 上篇文章  mybatis +springmvc+ mchange+multidatasource 没有跑通 , 一直没有找到 问题所在,现在 用 jdbctemplate 是可以跑通的 ,,,,

(可以跑通的,有数据库的,mchange+ aop )springmvc+jdbctemplate+mchange+multidatasource 

下载:  http://download.csdn.net/download/knight_black_bob/9245103

扫描二维码关注公众号,回复: 738190 查看本文章



 applicationcontext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd    
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd    
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd    
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd    
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd    
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd    
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd    
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd    
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">

	<context:annotation-config />
	<aop:aspectj-autoproxy proxy-target-class="true" />
  
    <context:component-scan base-package="com.baoy"  >
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:db-config.properties" />
	</bean>


	<bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"   destroy-method="close">  
	   <property name="driverClass" value="${one.jdbc.driverClass}" />
		<property name="jdbcUrl" value="${one.jdbc.url}"/>
		<property name="user" value="${one.jdbc.user}"/>
		<property name="password" value="${one.jdbc.password}"/>
		<property name="initialPoolSize" value="${one.jdbc.initialPoolSize}"/>
		<property name="minPoolSize" value="${one.jdbc.minPoolSize}"/>
		<property name="maxPoolSize" value="${one.jdbc.maxPoolSize}"/>
		<property name="checkoutTimeout" value="${one.jdbc.checkoutTimeout}" />
		<property name="idleConnectionTestPeriod" value="${one.jdbc.idleConnectionTestPeriod}"/>
		<property name="maxIdleTime" value="${one.jdbc.maxIdleTime}"/>
		<property name="maxStatements" value="${one.jdbc.maxStatements}"/>
		<property name="testConnectionOnCheckout" value="${one.jdbc.testConnectionOnCheckout}"/>
	</bean>

	 

	<bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"   destroy-method="close">  
	    <property name="driverClass" value="${two.jdbc.driverClass}" />
		<property name="jdbcUrl" value="${two.jdbc.url}"/>
		<property name="user" value="${two.jdbc.user}"/>
		<property name="password" value="${two.jdbc.password}" />
		<property name="initialPoolSize" value="${two.jdbc.initialPoolSize}"/>
		<property name="minPoolSize" value="${two.jdbc.minPoolSize}"/>
		<property name="maxPoolSize" value="${two.jdbc.maxPoolSize}"/>
		<property name="checkoutTimeout" value="${two.jdbc.checkoutTimeout}" />
		<property name="idleConnectionTestPeriod" value="${two.jdbc.idleConnectionTestPeriod}"/>
		<property name="maxIdleTime" value="${two.jdbc.maxIdleTime}"/>
		<property name="maxStatements" value="${two.jdbc.maxStatements}"/>
		<property name="testConnectionOnCheckout" value="${two.jdbc.testConnectionOnCheckout}"/>
	</bean>
    
     <bean id="dataSource" class="com.baoy.dynamic.DynamicDataSource">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry key="dataSourceOne" value-ref="dataSourceOne" />
				<entry key="dataSourceTwo" value-ref="dataSourceTwo" />
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="dataSourceOne" />
	  </bean>

	 <bean id="dataSourceInterceptor" class="com.baoy.dynamic.DataSourceInterceptor" />

	<aop:config>
		<aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
			<aop:pointcut id="dsone" expression="execution(* com.baoy.oneweb.dao.*.*(..))" />
			<aop:pointcut id="dstwo" expression="execution(* com.baoy.twoweb.dao.*.*(..))" />
			<aop:before method="setDataSourceOne" pointcut-ref="dsone"/>
			<aop:before method="setDataSourceTwo" pointcut-ref="dstwo"/>
		</aop:aspect>
	</aop:config>


    <bean id="jdbcTemplate"   class="org.springframework.jdbc.core.JdbcTemplate">  
        <property name="dataSource">  
            <ref bean="dataSource" />  
        </property>  
    </bean> 
</beans>   

springMvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:oxm="http://www.springframework.org/schema/oxm"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
				http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
				http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
				http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
	<!-- 激活Spring注解方式:自动扫描,并注入bean -->
	<context:component-scan base-package="com.baoy.oneweb.action" /> 
	<context:component-scan base-package="com.baoy.twoweb.action" /> 

	
	<!-- 配置视图解析 -->
     <bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="" p:suffix=".jsp">  
        <property name="order" value="0" />  
    </bean> 
	 <!-- 默认的注解映射的支持 -->
	<mvc:annotation-driven/>
	
	
	 
	
</beans>

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" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name></display-name>

	<!-- welcome page -->
	<welcome-file-list>
		<welcome-file>/back/jsp/main.jsp</welcome-file>
	</welcome-file-list>


	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>




	<!-- springmvc -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springMVC-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>



</web-app>

DatabaseContextHolder。java

package com.baoy.dynamic;

public class DatabaseContextHolder {

	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
	  
    public static void setCustomerType(String customerType) { 
        contextHolder.set(customerType);  
    }  
  
    public static String getCustomerType() {  
        return contextHolder.get();  
    }  
  
    public static void clearCustomerType() {  
        contextHolder.remove();  
    }  
	    
}

DataSourceInterceptor.java

package com.baoy.dynamic;
 
   
public class DataSourceInterceptor {   
    public void setDataSourceOne() {  
        DatabaseContextHolder.setCustomerType("dataSourceOne");  
    }  
       
    public void setDataSourceTwo() {  
        DatabaseContextHolder.setCustomerType("dataSourceTwo");  
    }   
}  

DynamicDataSource.java

package com.baoy.dynamic;
 
 

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 

public class DynamicDataSource  extends AbstractRoutingDataSource{  
  
	  
    @Override  
    protected Object determineCurrentLookupKey() {   
        return DatabaseContextHolder.getCustomerType();   
    }
 
    
}  

UserDaoImpl.java

package com.baoy.oneweb.daoimpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; 
import org.springframework.stereotype.Repository;

import com.baoy.common.bean.User;
import com.baoy.oneweb.dao.UserDao; 

@Repository
public class UserDaoImpl   implements UserDao {
	

	 @Autowired 
	 private JdbcTemplate jdbcTemplate;
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	
	@SuppressWarnings("rawtypes")
	private class UserRowMapper implements RowMapper {

//		userId,userName,password,tel,sex,description
		@Override
		public User mapRow(ResultSet rs, int i) throws SQLException {
			User user = new User(); 
			user.setUserId(rs.getInt("userId"));
			user.setUserName(rs.getString("userName"));
			user.setPassword(rs.getString("password"));
			user.setTel(rs.getString("tel"));
			user.setSex(rs.getString("sex"));
			user.setDescription(rs.getString("description"));
			return user;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> allUser() {
		String sql = "select * from t_user ";
		return   this.getJdbcTemplate().query(sql, new UserRowMapper());
	}

	@Override
	public void delUser(int userId) {
		String sql = "delete from t_user where userId ='"+userId+"'"; 
	    this.getJdbcTemplate().update(sql );
		
	}

	@Override
	public User user(int userId) {
		String sql = "select * from t_user where  userId ='"+userId+"'"; 
		List<User> userList = this.getJdbcTemplate().query(sql, new UserRowMapper());
		if (userList !=null && userList.size() > 0 ) {
			return userList.get(0);
		}else{
			return null;	
		}
	}

	@Override
	public void updateUser(User user) {
		String sql = "update t_user set userName=?,password=?,tel=?,sex=?,description=?";
		  this.getJdbcTemplate().update(sql, new Object[] {
					 user.getUserName(),
					 user.getPassword(),
					 user.getTel(),
					 user.getSex(),
					 user.getDescription()
			 });
	}

	@Override
	public void addUser(User user) {
		String sql = "insert into t_user(userName,password,tel,sex,description) values (?,?,?,?,?)";
		 this.getJdbcTemplate().update(sql, new Object[] {
				 user.getUserName(),
				 user.getPassword(),
				 user.getTel(),
				 user.getSex(),
				 user.getDescription()
		 });
	}


}

 service

package com.baoy.oneweb.service;

import java.util.List; 

import com.baoy.common.bean.User; 
 public interface UserService {
 
   public List<User> allUser();

   public void delUser(int userId);
   public User user(int userId);

   public void updateUser(User user);

   public void addUser(User user);

}

action

package com.baoy.oneweb.action;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.baoy.common.bean.User;
import com.baoy.oneweb.service.UserService;
 

@Controller
public class UserController {

       
      @Autowired
      UserService userService;

      @RequestMapping(value = "/userView.do")
      public String userView(ModelMap modelMap,String pageNo, String choice, HttpSession session){
            List<User> userList = userService.allUser();  
           modelMap.put("userList", userList);
           return "back/jsp/user/userView";
     }

      @RequestMapping(value = "/userDel{userId}.do")
      public String userDel(@PathVariable("userId")int userId ,ModelMap modelMap,String pageNo, String choice, HttpSession session){
             userService.delUser(userId);
             String message1="删除成功";
             String message2="请返回……";
             String  url="userView.do";
             modelMap.put("message1", message1);
             modelMap.put("message2", message2);
             modelMap.put("url", url);
            return "infomationShow";
      }

      @RequestMapping(value ="/userGoAdd.do")
             public String userGoAdd(ModelMap modelMap,String pageNo, String choice, HttpSession session){
             return "back/jsp/user/userAdd";
      }

      @RequestMapping(value = "/userAdd.do",method=RequestMethod.POST)
      public String userAdd(User form,ModelMap modelMap,String pageNo, String choice, HttpSession session){
             userService.addUser(form);
             String message1="添加成功";
             String message2="请返回……";
             String  url="userView.do";
             modelMap.put("message1", message1);
             modelMap.put("message2", message2);
            modelMap.put("url", url);
             return "infomationShow";
      }

      @RequestMapping(value = "/userGoUpdate{userId}.do")
      public String userGoUpdate(@PathVariable("userId")int userId ,ModelMap modelMap,String pageNo, String choice, HttpSession session){
            User user = userService.user(userId);
           modelMap.put("user", user);
           return "back/jsp/user/userUpdate";
      }

      @RequestMapping(value = "/userUpdate.do",method=RequestMethod.POST)
      public String userUpdate(User form,ModelMap modelMap,String pageNo, String choice, HttpSession session){
             userService.updateUser(form);
             String message1="修改成功";
             String message2="请返回……";
             String  url="userView.do";
             modelMap.put("message1", message1);
             modelMap.put("message2", message2);
             modelMap.put("url", url);
             return "infomationShow";
      }

}

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

猜你喜欢

转载自knight-black-bob.iteye.com/blog/2254761
AOP