SpringMVC +Spring+ SpringJDBC整合實例。文件結構: java
整合大體以下: mysql
1)web.xml的配置: web
<?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: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-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:*applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 編碼轉換器 --> <filter> <filter-name>setcharacter</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> </filter> <filter-mapping> <filter-name>setcharacter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2)applicationContext.xml的配置: spring
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/context http://www.springframework.org/schema/context/spring-context-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 掃描類包,將標註Spring註解的類自動轉化Bean,同時完成Bean的注入 --> <context:component-scan base-package="com.controller" /> <context:component-scan base-package="com.service" /> <context:component-scan base-package="com.dao" /> <!-- 配置數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${jdbc.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> <!--鏈接池中保留的最小鏈接數。 --> <property name="minPoolSize"> <value>5</value> </property> <!--鏈接池中保留的最大鏈接數。Default: 15 --> <property name="maxPoolSize"> <value>30</value> </property> <!--初始化時獲取的鏈接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 --> <property name="initialPoolSize"> <value>10</value> </property> <!--最大空閒時間,60秒內未使用則鏈接被丟棄。若爲0則永不丟棄。Default: 0 --> <property name="maxIdleTime"> <value>60</value> </property> <!--當鏈接池中的鏈接耗盡的時候c3p0一次同時獲取的鏈接數。Default: 3 --> <property name="acquireIncrement"> <value>5</value> </property> <!--JDBC的標準參數,用以控制數據源內加載的PreparedStatements數量。但因爲預緩存的statements 屬於單個connection而不是整個鏈接池。因此設置這個參數須要考慮到多方面的因素。 若是maxStatements與maxStatementsPerConnection均爲0,則緩存被關閉。Default: 0 --> <property name="maxStatements"> <value>0</value> </property> <!--每60秒檢查全部鏈接池中的空閒鏈接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>60</value> </property> <!--定義在從數據庫獲取新鏈接失敗後重復嘗試的次數。Default: 30 --> <property name="acquireRetryAttempts"> <value>30</value> </property> <!--獲取鏈接失敗將會引發全部等待鏈接池來獲取鏈接的線程拋出異常。可是數據源仍有效 保留,並在下次調用getConnection()的時候繼續嘗試獲取鏈接。若是設爲true,那麼在嘗試 獲取鏈接失敗後該數據源將申明已斷開並永久關閉。Default: false --> <property name="breakAfterAcquireFailure"> <value>true</value> </property> <!--因性能消耗大請只在須要的時候使用它。若是設爲true那麼在每一個connection提交的 時候都將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable 等方法來提高鏈接測試的性能。Default: false --> <property name="testConnectionOnCheckout"> <value>false</value> </property> </bean> <!-- 配置Jdbc模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!-- 經過AOP配置提供事務加強,讓service包下全部Bean的全部方法擁有事務 --> <aop:config proxy-target-class="true"> <aop:pointcut id="serviceMethod" expression=" execution(* com.service..*(..))" /> <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 配置視圖解析器,將ModelAndView及字符串解析爲具體的頁面 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans>3)jdbc.properties的配置:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test2 jdbc.username=root jdbc.password=1234564)log4j.properties的配置:
log4j.rootLogger=DEBUG,A1 # \u8f93\u51fa\u5230\u63a7\u5236\u53f0 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [\u65E5\u5FD7\u4FE1\u606F] %m%n
5)User.java sql
package com.model; import java.io.Serializable; @SuppressWarnings("serial") public class User implements Serializable { private int id; private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } }6)UserController.java
package com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.model.User; import com.service.UserService; @Controller public class UserComtroller { @Autowired private UserService userService; @RequestMapping("/user/loginView") public String loginView(){ return "login"; } @RequestMapping("/user/registerView") public String registerView(){ return "register"; } @RequestMapping("/user/login") public ModelAndView login(User user){ ModelAndView mav = new ModelAndView(); User u = userService.loginCheck(user); if(null == u){ mav.setViewName("login"); mav.addObject("errorMsg","用戶名或密碼有誤!"); return mav; } else{ mav.setViewName("success"); mav.addObject("user", u); return mav; } } @RequestMapping("/user/register") public ModelAndView register(User user){ ModelAndView mav = new ModelAndView(); if(userService.register(user)){ mav.setViewName("register_succ"); return mav; } else{ mav.setViewName("register"); mav.addObject("errorMsg","用戶名已被佔用,請更換!!"); return mav; } } }7)UserService Interface
package com.service; import com.model.User; public interface UserService { public boolean register(User user); public User loginCheck(User user); }8)UserServiceImp.java
package com.service.implement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.UserDao; import com.model.User; import com.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public User loginCheck(User user) { User u = userDao.findUserByUserName(user.getUserName()); System.out.println("id="+u.getId()+", userName="+u.getUserName()+", password="+u.getPassword()); if(user.getPassword().equals(u.getPassword())){ return u; } else{ return null; } } @Override public boolean register(User user) { User u = userDao.findUserByUserName(user.getUserName()); if(u.getId() == 0){ userDao.register(user); return true; } else{ System.out.println("id="+u.getId()+", userName="+u.getUserName()+", password="+u.getPassword()); return false; } } }9)UserDao Interface
package com.dao; import com.model.User; public interface UserDao { public void register(User user); public User findUserByUserName(final String userName); }10)UserDaoImpl.java
package com.dao.implement; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Repository; import com.dao.UserDao; import com.model.User; @Repository public class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public void register(User user) { String sqlStr = "insert into user(uname,pwd) values(?,?)"; Object[] params = new Object[]{user.getUserName(),user.getPassword()}; jdbcTemplate.update(sqlStr, params); } @Override public User findUserByUserName(String userName) { String sqlStr = "select id,uname,pwd from user where uname=?"; final User user = new User(); jdbcTemplate.query(sqlStr, new Object[]{userName}, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { user.setId(rs.getInt("id")); user.setUserName(rs.getString("uname")); user.setPassword(rs.getString("pwd")); } }); return user; } }11)測試類:test/com.service.implement
-UserServiceImplTest.java 數據庫
package com.service.implement; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.model.User; import com.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext.xml") public class UserServiceTest { @Autowired private UserService userService; @Test public void testLoginCheck(){ User user = new User(); user.setUserName("manager2"); user.setPassword("123"); if(null != userService.loginCheck(user)) System.out.println("------OK!!------"); else System.out.println("-----Sorry!!----"); } @Test public void testRegister(){ User user = new User(); user.setUserName("manager"); user.setPassword("123"); System.out.println(userService.register(user)); } }12)測試結果:
源碼:http://t.cn/zQiBoBL express