SpringMVC +Spring+ SpringJDBC整合实例。文件结构:
3)jdbc.properties的配置:
4)log4j.properties的配置:
6)UserController.java
7)UserService Interface
8)UserServiceImp.java
9)UserDao Interface
10)UserDaoImpl.java
11)单元测试:test/com.service.implement
12)测试结果:
3S3(3Spring3.x)的整合大致如下:
1)web.xml的配置:
01 | <? xml
version = "1.0"
encoding = "UTF-8" ?> |
02 | < 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" > |
03 | < display-name ></ display-name > |
04 | < welcome-file-list > |
05 | < welcome-file >index.jsp</ welcome-file > |
06 | </ welcome-file-list > |
07 | < listener > |
08 | < listener-class >org.springframework.web.util.IntrospectorCleanupListener</ listener-class > |
09 | </ listener > |
10 | < servlet > |
11 | < servlet-name >spring</ servlet-name > |
12 | < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class > |
13 | < init-param > |
14 | < param-name >contextConfigLocation</ param-name > |
15 | < param-value >classpath:*applicationContext.xml</ param-value > |
16 | </ init-param > |
17 | < load-on-startup >1</ load-on-startup > |
18 | </ servlet > |
19 | < servlet-mapping > |
20 | < servlet-name >spring</ servlet-name > |
21 | < url-pattern >*.do</ url-pattern > |
22 | </ servlet-mapping > |
23 | <!-- 统一字符编码为UTF-8 --> |
24 | < filter > |
25 | < filter-name >setcharacter</ filter-name > |
26 | < filter-class >org.springframework.web.filter.CharacterEncodingFilter</ filter-class > |
27 | < init-param > |
28 | < param-name >encoding</ param-name > |
29 | < param-value >utf-8</ param-value > |
30 | </ init-param > |
31 | </ filter > |
32 | < filter-mapping > |
33 | < filter-name >setcharacter</ filter-name > |
34 | < url-pattern >/*</ url-pattern > |
35 | </ filter-mapping > |
36 | </ web-app > |
2)applicationContext.xml的配置:
001 | <? xml
version = "1.0"
encoding = "UTF-8"
?> |
002 | < beans
xmlns = "http://www.springframework.org/schema/beans" |
003 | xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:p = "http://www.springframework.org/schema/p" |
004 | xmlns:context = "http://www.springframework.org/schema/context" |
005 | xmlns:aop = "http://www.springframework.org/schema/aop"
xmlns:tx = "http://www.springframework.org/schema/tx" |
006 | xsi:schemaLocation="http://www.springframework.org/schema/beans
|
007 | http://www.springframework.org/schema/beans/spring-beans-3.0.xsd |
008 | http://www.springframework.org/schema/context
|
009 | http://www.springframework.org/schema/context/spring-context-3.0.xsd |
010 | http://www.springframework.org/schema/tx
|
011 | http://www.springframework.org/schema/tx/spring-tx-3.0.xsd |
012 | http://www.springframework.org/schema/aop |
013 | http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> |
014 |
015 | < context:property-placeholder
location = "classpath:jdbc.properties"
/> |
016 |
017 | <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 --> |
018 | < context:component-scan
base-package = "com.controller"
/> |
019 | < context:component-scan
base-package = "com.service"
/> |
020 | < context:component-scan
base-package = "com.dao"
/> |
021 |
022 | <!-- 配置数据源 --> |
023 | < bean
id = "dataSource"
class = "com.mchange.v2.c3p0.ComboPooledDataSource" |
024 | destroy-method = "close" > |
025 | < property
name = "driverClass" > |
026 | < value >${jdbc.driverClassName}</ value > |
027 | </ property > |
028 | < property
name = "jdbcUrl" > |
029 | < value >${jdbc.url}</ value > |
030 | </ property > |
031 | < property
name = "user" > |
032 | < value >${jdbc.username}</ value > |
033 | </ property > |
034 | < property
name = "password" > |
035 | < value >${jdbc.password}</ value > |
036 | </ property > |
037 | <!--连接池中保留的最小连接数。 --> |
038 | < property
name = "minPoolSize" > |
039 | < value >5</ value > |
040 | </ property > |
041 | <!--连接池中保留的最大连接数。Default: 15 --> |
042 | < property
name = "maxPoolSize" > |
043 | < value >30</ value > |
044 | </ property > |
045 | <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> |
046 | < property
name = "initialPoolSize" > |
047 | < value >10</ value > |
048 | </ property > |
049 | <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> |
050 | < property
name = "maxIdleTime" > |
051 | < value >60</ value > |
052 | </ property > |
053 | <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> |
054 | < property
name = "acquireIncrement" > |
055 | < value >5</ value > |
056 | </ property > |
057 | <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
|
058 | 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 --> |
059 | < property
name = "maxStatements" > |
060 | < value >0</ value > |
061 | </ property > |
062 | <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> |
063 | < property
name = "idleConnectionTestPeriod" > |
064 | < value >60</ value > |
065 | </ property > |
066 | <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> |
067 | < property
name = "acquireRetryAttempts" > |
068 | < value >30</ value > |
069 | </ property > |
070 | <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
|
071 | 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> |
072 | < property
name = "breakAfterAcquireFailure" > |
073 | < value >true</ value > |
074 | </ property > |
075 | <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
|
076 | 等方法来提升连接测试的性能。Default: false --> |
077 | < property
name = "testConnectionOnCheckout" > |
078 | < value >false</ value > |
079 | </ property > |
080 | </ bean > |
081 |
082 | <!-- 配置Jdbc模板 --> |
083 | < bean
id = "jdbcTemplate"
class = "org.springframework.jdbc.core.JdbcTemplate" > |
084 | < property
name = "dataSource"
ref = "dataSource" ></ property > |
085 | </ bean > |
086 |
087 | <!-- 配置事务管理器 --> |
088 | < bean
id = "transactionManager" |
089 | class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" |
090 | p:dataSource-ref = "dataSource"
/> |
091 |
092 | <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 --> |
093 | < aop:config
proxy-target-class = "true" > |
094 | < aop:pointcut
id = "serviceMethod" |
095 | expression = " execution(* com.service..*(..))"
/> |
096 | < aop:advisor
pointcut-ref = "serviceMethod"
advice-ref = "txAdvice"
/> |
097 | </ aop:config > |
098 | < tx:advice
id = "txAdvice"
transaction-manager = "transactionManager" > |
099 | < tx:attributes > |
100 | < tx:method
name = "*"
/> |
101 | </ tx:attributes > |
102 | </ tx:advice > |
103 |
104 | <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> |
105 | < bean |
106 | class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
/> |
107 | |
108 | |
109 | <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 --> |
110 | < bean |
111 | class = "org.springframework.web.servlet.view.InternalResourceViewResolver" |
112 | p:viewClass = "org.springframework.web.servlet.view.JstlView"
p:prefix = "/WEB-INF/jsp/" |
113 | p:suffix = ".jsp"
/> |
114 |
115 | </ beans > |
1 | jdbc.driverClassName=com.mysql.jdbc.Driver |
2 | jdbc.url=jdbc:mysql: //localhost:3306/test2 |
3 | jdbc.username=root |
4 | jdbc.password= 123456 |
1 | log4j.rootLogger=DEBUG,A1 |
2 | # \u8f93\u51fa\u5230\u63a7\u5236\u53f0
|
3 | log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
4 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
5 | log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [\u65E5\u5FD7\u4FE1\u606F] %m%n |
5)User.java
01 | package com.model; |
02 |
03 | import java.io.Serializable; |
04 |
05 | @SuppressWarnings ( "serial" ) |
06 | public class
User implements
Serializable { |
07 | |
08 | private
int id; |
09 | private
String userName; |
10 | private
String password; |
11 | |
12 | public
String getUserName() { |
13 | return
userName; |
14 | } |
15 | public
void setUserName(String userName) { |
16 | this .userName = userName; |
17 | } |
18 | public
String getPassword() { |
19 | return
password; |
20 | } |
21 | public
void setPassword(String password) { |
22 | this .password = password; |
23 | } |
24 | public
int getId() { |
25 | return
id; |
26 | } |
27 | public
void setId( int
id) { |
28 | this .id = id; |
29 | } |
30 | |
31 |
32 | } |
01 | package com.controller; |
02 |
03 | import org.springframework.beans.factory.annotation.Autowired; |
04 | import org.springframework.stereotype.Controller; |
05 | import org.springframework.web.bind.annotation.RequestMapping; |
06 | import org.springframework.web.servlet.ModelAndView; |
07 |
08 | import com.model.User; |
09 | import com.service.UserService; |
10 |
11 | @Controller |
12 | public class
UserComtroller { |
13 | |
14 | @Autowired |
15 | private
UserService userService; |
16 | |
17 | @RequestMapping ( "/user/loginView" ) |
18 | public
String loginView(){ |
19 | return
"login" ; |
20 | } |
21 | |
22 | @RequestMapping ( "/user/registerView" ) |
23 | public
String registerView(){ |
24 | return
"register" ; |
25 | } |
26 | |
27 | @RequestMapping ( "/user/login" ) |
28 | public
ModelAndView login(User user){ |
29 | ModelAndView mav =
new ModelAndView(); |
30 | User u = userService.loginCheck(user); |
31 | if ( null ==u){ |
32 | mav.setViewName( "login" ); |
33 | mav.addObject( "errorMsg" , "用户名或密码有误!" ); |
34 | return
mav; |
35 | } |
36 | else { |
37 | mav.setViewName( "success" ); |
38 | mav.addObject( "user" , u); |
39 | return
mav; |
40 | } |
41 | } |
42 | |
43 | @RequestMapping ( "/user/register" ) |
44 | public
ModelAndView register(User user){ |
45 | ModelAndView mav =
new ModelAndView(); |
46 | if (userService.register(user)){ |
47 | mav.setViewName( "register_succ" ); |
48 | return
mav; |
49 | } |
50 | else { |
51 | mav.setViewName( "register" ); |
52 | mav.addObject( "errorMsg" , "用户名已被占用,请更换!!" ); |
53 | return
mav; |
54 | } |
55 | } |
56 | } |
1 | package com.service; |
2 |
3 | import com.model.User; |
4 |
5 |
6 | public interface
UserService { |
7 | public
boolean register(User user); |
8 | public
User loginCheck(User user); |
9 | } |
01 | package com.service.implement; |
02 |
03 | import org.springframework.beans.factory.annotation.Autowired; |
04 | import org.springframework.stereotype.Service; |
05 |
06 | import com.dao.UserDao; |
07 | import com.model.User; |
08 | import com.service.UserService; |
09 |
10 | @Service |
11 | public class
UserServiceImpl implements
UserService { |
12 |
13 | @Autowired |
14 | private
UserDao userDao; |
15 | |
16 | @Override |
17 | public
User loginCheck(User user) { |
18 | User u = userDao.findUserByUserName(user.getUserName()); |
19 | System.out.println( "id=" +u.getId()+ ", userName=" +u.getUserName()+ ",
password=" +u.getPassword()); |
20 | if (user.getPassword().equals(u.getPassword())){ |
21 | return
u; |
22 | } |
23 | else { |
24 | return
null ; |
25 | } |
26 | } |
27 |
28 | @Override |
29 | public
boolean register(User user) { |
30 | User u = userDao.findUserByUserName(user.getUserName()); |
31 | if (u.getId()== 0 ){ |
32 | userDao.register(user); |
33 | return
true ; |
34 | } |
35 | else { |
36 | System.out.println( "id=" +u.getId()+ ", userName=" +u.getUserName()+ ",
password=" +u.getPassword()); |
37 | return
false ; |
38 | } |
39 | } |
40 |
41 | } |
1 | package com.dao; |
2 |
3 | import com.model.User; |
4 |
5 | public interface
UserDao { |
6 | public
void register(User user); |
7 | public
User findUserByUserName( final
String userName); |
8 | } |
01 | package com.dao.implement; |
02 |
03 | import java.sql.ResultSet; |
04 | import java.sql.SQLException; |
05 |
06 | import org.springframework.beans.factory.annotation.Autowired; |
07 | import org.springframework.jdbc.core.JdbcTemplate; |
08 | import org.springframework.jdbc.core.RowCallbackHandler; |
09 | import org.springframework.stereotype.Repository; |
10 |
11 | import com.dao.UserDao; |
12 | import com.model.User; |
13 |
14 | @Repository |
15 | public class
UserDaoImpl implements
UserDao { |
16 | |
17 | @Autowired |
18 | private
JdbcTemplate jdbcTemplate; |
19 |
20 | @Override |
21 | public
void register(User user) { |
22 | String sqlStr =
"insert into user(uname,pwd) values(?,?)" ; |
23 | Object[] params =
new Object[]{user.getUserName(),user.getPassword()}; |
24 | jdbcTemplate.update(sqlStr, params); |
25 | } |
26 |
27 | @Override |
28 | public
User findUserByUserName(String userName) { |
29 | String sqlStr =
"select id,uname,pwd from user where uname=?" ; |
30 | final
User user = new
User(); |
31 | jdbcTemplate.query(sqlStr,
new Object[]{userName},
new RowCallbackHandler() { |
32 | @Override |
33 | public
void processRow(ResultSet rs)
throws SQLException { |
34 | user.setId(rs.getInt( "id" )); |
35 | user.setUserName(rs.getString( "uname" )); |
36 | user.setPassword(rs.getString( "pwd" )); |
37 | } |
38 | }); |
39 | return
user; |
40 | } |
41 |
42 | } |
-UserServiceImplTest.java
01 | package com.service.implement; |
02 |
03 | import org.junit.Test; |
04 | import org.junit.runner.RunWith; |
05 | import org.springframework.beans.factory.annotation.Autowired; |
06 | import org.springframework.test.context.ContextConfiguration; |
07 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; |
08 |
09 | import com.model.User; |
10 | import com.service.UserService; |
11 |
12 |
13 | @RunWith (SpringJUnit4ClassRunner. class ) |
14 | @ContextConfiguration (locations= "/applicationContext.xml" ) |
15 | public class
UserServiceTest { |
16 | |
17 | @Autowired |
18 | private
UserService userService; |
19 | |
20 | @Test |
21 | public
void testLoginCheck(){ |
22 | User user =
new User(); |
23 | user.setUserName( "manager2" ); |
24 | user.setPassword( "123" ); |
25 | if ( null !=userService.loginCheck(user)) |
26 | System.out.println( "------OK!!-----" ); |
27 | else |
28 | System.out.println( "------Sorry!!-----" ); |
29 | } |
30 | |
31 | @Test |
32 | public
void testRegister(){ |
33 | User user =
new User(); |
34 | user.setUserName( "manager" ); |
35 | user.setPassword( "123" ); |
36 | System.out.println(userService.register(user)); |
37 | } |
38 |
39 | } |