Spring3.1+SpringMVC3.1+JPA2.0

来源:互联网 发布:php好书推荐 编辑:程序博客网 时间:2024/06/09 22:47

SpringMVC是越来越火,自己也弄一个Spring+SpringMVC+JPA的简单框架。

1、搭建环境。

1)下载Spring3.1.2的发布包;Hibernate4.1.7的发布包(没有使用hibernate的API,只是使用了它对JPA的实现);下载 BoneCP 连接池框架及其依赖的jar,下载缓存框架ehcache,全部所用到的jar包如下:

?
antlr-2.7.7.jar
bonecp-0.7.1.RELEASE.jar
bonecp-provider-0.7.1-rc2.jar
bonecp-spring-0.7.1-rc1.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.aspectj.weaver-1.6.12.RELEASE.jar
dom4j-1.6.1.jar
ehcache-core-2.5.2.jar
guava-12.0.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.7.Final.jar
hibernate-entitymanager-4.1.7.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.6-bin.jar
org.springframework.aop-3.1.2.RELEASE.jar
org.springframework.asm-3.1.2.RELEASE.jar
org.springframework.aspects-3.1.2.RELEASE.jar
org.springframework.beans-3.1.2.RELEASE.jar
org.springframework.context-3.1.2.RELEASE.jar
org.springframework.context.support-3.1.2.RELEASE.jar
org.springframework.core-3.1.2.RELEASE.jar
org.springframework.expression-3.1.2.RELEASE.jar
org.springframework.instrument-3.1.2.RELEASE.jar
org.springframework.instrument.tomcat-3.1.2.RELEASE.jar
org.springframework.jdbc-3.1.2.RELEASE.jar
org.springframework.jms-3.1.2.RELEASE.jar
org.springframework.orm-3.1.2.RELEASE.jar
org.springframework.oxm-3.1.2.RELEASE.jar
org.springframework.test-3.1.2.RELEASE.jar
org.springframework.transaction-3.1.2.RELEASE.jar
org.springframework.web-3.1.2.RELEASE.jar
org.springframework.web.portlet-3.1.2.RELEASE.jar
org.springframework.web.servlet-3.1.2.RELEASE.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.1.jar

2)建立一个Web Project,引入上述jar包

2.1)web.xml配置如下:

view sourceprint?
01.<?xmlversion="1.0"encoding="UTF-8"?>
02.<web-appversion="2.5"
03.xmlns="http://java.sun.com/xml/ns/javaee"
04.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05.xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
06.http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
07. 
08.<!-- 配置Log4j -->
09.<context-param>
10.<param-name>webAppRootKey</param-name>
11.<param-value>spring_springmvc_jpa.root</param-value>
12.</context-param>
13.<context-param>
14.<param-name>log4jConfigLocation</param-name>
15.<param-value>classpath:log4j.properties</param-value>
16.</context-param>
17.<listener>
18.<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
19.</listener>
20. 
21.<!-- 配置编码过滤器 -->
22.<filter>
23.<filter-name>characterEncodingFilter</filter-name>
24.<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
25.<init-param>
26.<param-name>encoding</param-name>
27.<param-value>UTF-8</param-value>
28.</init-param>
29.</filter>
30.<filter-mapping>
31.<filter-name>characterEncodingFilter</filter-name>
32.<url-pattern>/*</url-pattern>
33.</filter-mapping>
34. 
35.<!-- 配置Spring监听器 -->
36.<listener>
37.<listener-class>
38.org.springframework.web.context.ContextLoaderListener
39.</listener-class>
40.</listener>
41.<context-param>
42.<param-name>contextConfigLocation</param-name>
43.<param-value>/WEB-INF/applicationContext.xml</param-value>
44.</context-param>
45. 
46.<!-- Spring 刷新Introspector防止内存泄露 -->
47.<listener>
48.<listener-class>
49.org.springframework.web.util.IntrospectorCleanupListener
50.</listener-class>
51.</listener>
52. 
53. 
54.<!-- SpringMVC核心分发器 -->
55.<servlet>
56.<servlet-name>dispatcherServlet</servlet-name>
57.<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
58.<init-param>
59.<param-name>contextConfigLocation</param-name>
60.<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
61.</init-param>
62.<load-on-startup>1</load-on-startup>
63.</servlet>
64.<!-- 映射*.do的请求 -->
65.<servlet-mapping>
66.<servlet-name>dispatcherServlet</servlet-name>
67.<url-pattern>*.do</url-pattern>
68.</servlet-mapping>
69. 
70. 
71.<welcome-file-list>
72.<welcome-file>index.jsp</welcome-file>
73.</welcome-file-list>
74.</web-app>
2.2)在src目录下建立log4j.properties日志配置文件,内容如下:
view sourceprint?
01.log4j.rootLogger=INFO,stdout,file
02. 
03.#应用于控制台
04.log4j.appender.stdout=org.apache.log4j.ConsoleAppender
05.log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
06.log4j.appender.stdout.Target=System.out
07.log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss,SSS} [%c]-[%p] %m%n
08.#应用于文件
09.log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
10.log4j.appender.file.File=${spring_springmvc_jpa.root}/app.log
11.log4j.appender.file.layout=org.apache.log4j.PatternLayout
12.log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
13. 
14. 
15.log4j.logger.org.hibernate.tool.hbm2ddl=debug
2.3)在src目录下建立缓存的配置文件ehcache.xml,内容如下:
view sourceprint?
01.<?xmlversion="1.0"encoding="UTF-8"?>
02.<ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03.xsi:noNamespaceSchemaLocation="ehcache.xsd"
04.updateCheck="true"monitoring="autodetect"
05.dynamicConfig="true">
06. 
07.<!--  <diskStore path="java.io.tmpdir"/> -->
08. 
09.<!-- 配置缓存文件存放路径 -->
10.<diskStorepath="E:/CacheTmpDir"/>
11. 
12.<!--  
13..必须要有的属性:  
14. 
15.name: cache的名字,用来识别不同的cache,必须惟一。  
16. 
17.maxElementsInMemory: 内存管理的缓存元素数量最大限值。  
18. 
19.maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。  
20. 
21.eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。  
22. 
23.overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。  
24..下面是一些可选属性:  
25. 
26.timeToIdleSeconds: 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。  
27. 
28.timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。  
29. 
30.diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)。  
31. 
32.diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。  
33. 
34.diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。  
35. 
36.memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。
37.First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用 
38. 
39.-->
40. 
41.<defaultCachemaxElementsInMemory="10000"
42.eternal="false"
43.timeToIdleSeconds="120"
44.timeToLiveSeconds="120"
45.overflowToDisk="true"
46.maxElementsOnDisk="10000000"
47.diskPersistent="false"
48.diskExpiryThreadIntervalSeconds="120"
49.memoryStoreEvictionPolicy="LRU"/>
50. 
51.<!-- User cache -->
52.<cachename="userCache"
53.maxElementsInMemory="10000"
54.maxElementsOnDisk="1000"
55.eternal="false"
56.overflowToDisk="true"
57.diskSpoolBufferSizeMB="20"
58.timeToIdleSeconds="300"
59.timeToLiveSeconds="600"
60.memoryStoreEvictionPolicy="LFU"/>
61. 
62.</ehcache>
2.4)在src目录下建立数据库连接属性配置文件jdbc.properties,内容如下:
view sourceprint?
01.#mysql数据库用
02.jdbc.driverClassName=com.mysql.jdbc.Driver
03.jdbc.url=jdbc:mysql://localhost:3306/spring_springmvc_jpa?useUnicode=true&amp;characterEncoding=UTF-8
04.jdbc.username=root
05.jdbc.password=root
06. 
07. 
08.##===============BoneCP配置==============##
09. 
10.#检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0#
11.BoneCP.idleConnectionTestPeriod=60
12. 
13.#连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0#
14.BoneCP.idleMaxAge=60
15. 
16.#每个分区最大的连接数# 
17.BoneCP.maxConnectionsPerPartition=5
18. 
19.#每个分区最小的连接数# 
20.BoneCP.minConnectionsPerPartition=1
21. 
22.#分区数 ,默认值2,最小1,推荐3-4,视应用而定# 
23.BoneCP.partitionCount=3
24. 
25.#每次去拿数据库连接的时候一次性要拿几个,默认值:2
26.BoneCP.acquireIncrement=2 
27. 
28.#缓存prepared statements的大小,默认值:0
29.BoneCP.statementsCacheSize=0
30. 
31.#每个分区释放链接助理进程的数量,默认值:3,除非你的一个数据库连接的时间内做了很多工作,不然过多的助理进程会影响你的性能# 
32.BoneCP.releaseHelperThreads=3
2.5)在WEB-INF目录下建立Spring的配置文件applicationContext.xml,内容如下:
view sourceprint?
001.<?xmlversion="1.0"encoding="UTF-8"?>
002.<beansxmlns="http://www.springframework.org/schema/beans"
003.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
004.xmlns:aop="http://www.springframework.org/schema/aop"
005.xmlns:tx="http://www.springframework.org/schema/tx"
006.xmlns:context="http://www.springframework.org/schema/context"
007.xmlns:p="http://www.springframework.org/schema/p" 
008.xmlns:cache="http://www.springframework.org/schema/cache" 
009.xsi:schemaLocation="
010.http://www.springframework.org/schema/beans
011.http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
012.http://www.springframework.org/schema/tx
013.http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
014.http://www.springframework.org/schema/aop
015.http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
016.http://www.springframework.org/schema/context     
017.http://www.springframework.org/schema/context/spring-context-3.1.xsd
018.http://www.springframework.org/schema/cache
019.http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">   
020. 
021. 
022.<!-- 注解支持 -->
023.<context:annotation-config/>
024. 
025.<!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
026.<context:component-scanbase-package="cn.luxh.app">
027.<context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Controller"/> 
028.</context:component-scan>
029. 
030.<!-- 属性文件位置 -->
031.<context:property-placeholderlocation="classpath:jdbc.properties"/>
032. 
033.<!-- 数据源 -->
034.<beanid="dataSource"class="com.jolbox.bonecp.BoneCPDataSource"destroy-method="close">
035.<!-- 数据库驱动 -->
036.<propertyname="driverClass"value="${jdbc.driverClassName}"/>
037.<!-- 相应驱动的jdbcUrl-->
038.<propertyname="jdbcUrl"value="${jdbc.url}"/>
039.<!-- 数据库的用户名 -->
040.<propertyname="username"value="${jdbc.username}"/>
041.<!-- 数据库的密码 -->
042.<propertyname="password"value="${jdbc.password}"/>
043.<!-- 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 -->
044.<propertyname="idleConnectionTestPeriod"value="${BoneCP.idleConnectionTestPeriod}"/>
045.<!-- 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 -->
046.<propertyname="idleMaxAge"value="${BoneCP.idleMaxAge}"/>
047.<!-- 每个分区最大的连接数 -->
048.<propertyname="maxConnectionsPerPartition"value="${BoneCP.maxConnectionsPerPartition}"/>
049.<!-- 每个分区最小的连接数 -->
050.<propertyname="minConnectionsPerPartition"value="${BoneCP.minConnectionsPerPartition}"/>
051.<!-- 分区数 ,默认值2,最小1,推荐3-4,视应用而定 -->
052.<propertyname="partitionCount"value="${BoneCP.partitionCount}"/>
053.<!-- 每次去拿数据库连接的时候一次性要拿几个,默认值:2 -->
054.<propertyname="acquireIncrement"value="${BoneCP.acquireIncrement}"/>
055.<!-- 缓存prepared statements的大小,默认值:0 -->
056.<propertyname="statementsCacheSize"value="${BoneCP.statementsCacheSize}"/>
057.<!-- 每个分区释放链接助理进程的数量,默认值:3,除非你的一个数据库连接的时间内做了很多工作,不然过多的助理进程会影响你的性能 -->
058.<propertyname="releaseHelperThreads"value="${BoneCP.releaseHelperThreads}"/>
059.</bean>
060. 
061.<!-- JPA实体管理器工厂 -->
062.<beanid="entityManagerFactory"class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
063.<propertyname="dataSource"ref="dataSource"/>
064.<propertyname="persistenceProvider"ref="persistenceProvider"/>
065.<propertyname="jpaVendorAdapter"ref="jpaVendorAdapter"/> 
066.<propertyname="jpaDialect"ref="jpaDialect"/> 
067. 
068.<propertyname="packagesToScan"value="cn.luxh.app.entity"/>
069. 
070.<propertyname="jpaProperties">
071.<props>
072.<propkey="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
073.<propkey="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
074.<propkey="hibernate.max_fetch_depth">3</prop>
075.<propkey="hibernate.jdbc.fetch_size">18</prop>
076.<propkey="hibernate.jdbc.batch_size">10</prop>
077.<propkey="hibernate.hbm2ddl.auto">update</prop>
078.<propkey="hibernate.show_sql">true</prop>
079.<propkey="hibernate.format_sql">true</prop>
080.<propkey="javax.persistence.validation.mode">none</prop>
081.</props>
082.</property>
083.</bean>
084.<!-- 用于指定持久化实现厂商类 -->
085.<beanid="persistenceProvider"class="org.hibernate.ejb.HibernatePersistence"/>
086.<!-- 用于设置JPA实现厂商的特定属性 -->
087.<beanid="jpaVendorAdapter"class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
088.<propertyname="database"value="MYSQL"/> 
089.</bean
090.<!-- 用于指定一些高级特性 -->
091.<beanid="jpaDialect"class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/> 
092. 
093.<!-- 事务管理器 --> 
094.<beanid="txManager"class="org.springframework.orm.jpa.JpaTransactionManager"
095.<propertyname="entityManagerFactory"ref="entityManagerFactory"/> 
096.</bean>
097. 
098.<!-- 注解式事务 -->
099.<tx:annotation-driventransaction-manager="txManager"/>
100. 
101.<!-- 启用缓存注解功能 -->
102.<cache:annotation-drivencache-manager="cacheManager"/>
103. 
104.<!-- 声明cacheManager -->  
105.<beanid="cacheManager"class="org.springframework.cache.ehcache.EhCacheCacheManager"   
106.p:cacheManager-ref="ehcache"/>
107. 
108.<!-- cacheManager工厂类,指定ehcache.xml的位置 -->   
109.<beanid="ehcache"class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
110.p:configLocation="classpath:/ehcache.xml"/>
111. 
112.</beans>
2.6)在WEB-INF目录下建立SpringMVC的配置文件dispatcher-servlet.xml,内容如下:
view sourceprint?
01.<?xmlversion="1.0"encoding="UTF-8"?>
02.<beansxmlns="http://www.springframework.org/schema/beans"
03.xmlns:mvc="http://www.springframework.org/schema/mvc"
04.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05.xmlns:context="http://www.springframework.org/schema/context"
06.xsi:schemaLocation="
07.http://www.springframework.org/schema/beans
08.http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
09.http://www.springframework.org/schema/context
10.http://www.springframework.org/schema/context/spring-context-3.1.xsd
11.http://www.springframework.org/schema/mvc
12.http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
13. 
14. 
15. 
16. 
17.<mvc:annotation-driven/>
18.<context:component-scanbase-package="cn.luxh.app.controller"/>
19. 
20. 
21.<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
22.<propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/>
23.<propertyname="prefix"value="/WEB-INF/jsp/"/>
24.<propertyname="suffix"value=".jsp"/>
25.</bean>
26. 
27.</beans>

2、编写代码

1)在WEB-INF目录下建立名叫jsp的文件夹,用于放置jsp页面,和SpringMVC配置文件中的<property name="prefix" value="/WEB-INF/jsp/"/>相对应。

2)创建一个实体。

view sourceprint?
01.packagecn.luxh.app.entity.privilege;
02. 
03.importjava.io.Serializable;
04. 
05.importjavax.persistence.Column;
06.importjavax.persistence.Entity;
07.importjavax.persistence.GeneratedValue;
08.importjavax.persistence.Id;
09.importjavax.persistence.Table;
10. 
11. 
12./**
13.* 用户信息
14.* @author Luxh
15.*/
16. 
17.@Entity
18.@Table(name="t_user_info")
19.publicclassUserInfoimplementsSerializable{
20. 
21.privatestaticfinallong serialVersionUID = -3838732995856086555L;
22. 
23.@Id
24.@GeneratedValue
25.privateLong id;
26. 
27.//账号
28.@Column(length=20,nullable=false)
29.privateString account;
30.//密码
31.@Column(length=20,nullable=false)
32.privateString password;
33.//姓名
34.@Column(length=32,nullable=false)
35.privateString name;
36. 
37.//getter、setter
38.//......
39. 
40. 
41.}

3)通用DAO,用于其他DAO继承,

3.1)接口

view sourceprint?
01.packagecn.luxh.app.dao.base;
02. 
03./**
04.* 通用的DAO
05.* @author Luxh
06.*/
07.publicinterfaceBaseDao {
08. 
09./**
10.* 持久化实体
11.* @param entity
12.*/
13.voidsave(Object entity);
14. 
15./**
16.* 根据主键查询实体
17.* @param <T>
18.* @param clazz  实体类
19.* @param id     主键
20.* @return
21.*/
22.<T> T getById(Class<T> clazz,Object id);
23.}
3.2)实现
view sourceprint?
01.packagecn.luxh.app.dao.base;
02. 
03.importjavax.persistence.EntityManager;
04.importjavax.persistence.PersistenceContext;
05. 
06.importorg.springframework.stereotype.Repository;
07. 
08./**
09.* 通用DAO实现
10.* @author Luxh
11.*/
12. 
13.@Repository
14.publicclassBaseDaoImplimplementsBaseDao{
15. 
16.//注入实体管理器
17.@PersistenceContext
18.protectedEntityManager em;
19. 
20.public<T> T getById(Class<T> clazz, Object id) {
21.returnem.find(clazz, id);
22.}
23. 
24.publicvoidsave(Object entity) {
25.em.persist(entity);
26.}
27. 
28.}

4)UserDao,继承于通用DAO

4.1)接口

view sourceprint?
01.packagecn.luxh.app.dao.privilege;
02. 
03.importcn.luxh.app.dao.base.BaseDao;
04. 
05./**
06.* User Dao Interface
07.* @author Luxh
08.*/
09.publicinterfaceUserDaoextendsBaseDao{
10. 
11.}
4.2)实现
view sourceprint?
01.packagecn.luxh.app.dao.privilege;
02. 
03.importorg.springframework.stereotype.Repository;
04. 
05.importcn.luxh.app.dao.base.BaseDaoImpl;
06. 
07./**
08.* User DAO Implement
09.* @author Luxh
10.*/
11. 
12.@Repository
13.publicclassUserDaoImplextendsBaseDaoImplimplementsUserDao{
14. 
15.}

5)通用的业务接口

这里只写一个接口,留给其他Service实现。

view sourceprint?
01.packagecn.luxh.app.service.base;
02. 
03./**
04.* 通用业务接口
05.* @author Luxh
06.*/
07.publicinterfaceBaseService {
08. 
09./**
10.* 保存实体
11.* @param entity
12.*/
13.voidsave(Object entity);
14. 
15./**
16.* 根据主键获取对象
17.* @param <T>
18.* @param clazz 实体类
19.* @param id    主键
20.* @return
21.*/
22.<T> T getById(Class<T> clazz,Object id);
23.}

6)用户业务接口UserService,实现通用业务接口的方法,并加上缓存


6.1)接口

view sourceprint?
01.packagecn.luxh.app.service.privilege;
02. 
03.importcn.luxh.app.service.base.BaseService;
04. 
05./**
06.* User Service
07.* @author Luxh
08.*/
09.publicinterfaceUserServiceextendsBaseService {
10. 
11.}
6.2)实现
view sourceprint?
01.packagecn.luxh.app.service.privilege;
02. 
03.importorg.springframework.beans.factory.annotation.Autowired;
04.importorg.springframework.cache.annotation.CacheEvict;
05.importorg.springframework.cache.annotation.Cacheable;
06.importorg.springframework.stereotype.Service;
07.importorg.springframework.transaction.annotation.Propagation;
08.importorg.springframework.transaction.annotation.Transactional;
09. 
10.importcn.luxh.app.dao.privilege.UserDao;
11. 
12./**
13.* User Service Implement
14.* @author Luxh
15.*/
16. 
17.@Service
18.publicclassUserServiceImplimplementsUserService{
19. 
20.@Autowired
21.privateUserDao userDao;
22. 
23.@Cacheable(value="userCache")//缓存数据
24.public<T> T getById(Class<T> clazz, Object id) {
25.returnuserDao.getById(clazz, id);
26.}
27. 
28.@Transactional(propagation=Propagation.REQUIRED)
29.@CacheEvict(value="userCache",allEntries=true)//清除缓存
30.publicvoidsave(Object entity) {
31.userDao.save(entity);
32.}
33. 
34.}
7)控制层,暂时还没有写一个公共的Controller用于被继承,就直接写UserController吧
view sourceprint?
01.packagecn.luxh.app.controller.privilege;
02. 
03.importorg.apache.commons.logging.Log;
04.importorg.apache.commons.logging.LogFactory;
05.importorg.springframework.beans.factory.annotation.Autowired;
06.importorg.springframework.stereotype.Controller;
07.importorg.springframework.ui.ModelMap;
08.importorg.springframework.web.bind.annotation.RequestMapping;
09.importorg.springframework.web.bind.annotation.RequestParam;
10.importorg.springframework.web.servlet.mvc.support.RedirectAttributes;
11. 
12.importcn.luxh.app.entity.privilege.UserInfo;
13.importcn.luxh.app.service.privilege.UserService;
14. 
15. 
16./**
17.* User Controller
18.* @author Luxh
19.*/
20. 
21.@Controller
22.@RequestMapping(value="/user")
23.publicclassUserController {
24. 
25.privatestaticfinalLog LOG = LogFactory.getLog(UserController.class);
26. 
27. 
28.@Autowired
29.privateUserService userService;//注入业务接口
30. 
31./**
32.* 用户列表
33.*/
34.@RequestMapping(value="/userList.do")
35.publicString userList(ModelMap modelMap) {
36.LOG.info("访问用户列表");
37.//打印一句话测试,不查数据库了
38.return"user/userList";//根据SpringMVC配置文件配好的前缀和后缀,自动转为:/WEB-INF/jsp/user/userList.jsp
39.}
40. 
41./**
42.* 根据主键查找用户
43.*/
44.@RequestMapping(value="/getUserById.do")
45.publicString getUserById(@RequestParamlongid) {
46.LOG.info("id is :"+id);
47.UserInfo userInfo = userService.getById(UserInfo.class,id);
48.LOG.info("user's name is :"+userInfo.getName());
49.return"user/userList";
50.}
51. 
52./**
53.* 保存用户
54.*/
55.@RequestMapping(value="/saveUser.do")
56.publicString saveUser(UserInfo userInfo,RedirectAttributes redirectAttributes) {
57.LOG.info("保存用户");
58.userService.save(userInfo);
59.//重定向后的提示信息,使用RedirectAttributes传递,在JSP页面可以用${message}获取
60.//提示信息只出现一次,刷新也不会重复提示,
61.redirectAttributes.addFlashAttribute("message","操作成功");
62. 
63.//重定向,防止表单重复提交
64.return"redirect:userList.do";//相对于当前路径 
65.//return "redirect:/user/userList.do";//相对于当前项目根路径
66.}
67. 
68. 
69.}

访问用户列表就是http://localhost:8080/APP/user/userList.do

根据主键查找用户:http://localhost:8080/APP/user/getUserById.do?id=1

保存用户:http://localhost:8080/APP/user/saveUser.do

APP是我的应用名称。