Maven 搭建SpringMVC+Hibernate项目详解
前言
今天复习一下springmvc+hibernate的搭建,本来想着将spring-security权限控制框架也映入其中的,但是发现内容太多了,spring-security的就留在下一篇吧,这篇主要搭建springmvc4.1.4和hibernate4.3.8,之前也打了好多springmvc的,这部分已经非常的熟悉了,毕竟业开发过一年多springmvc的,这次持久层采用hibernate,数据源采用c3p0,数据库暂采用mysql,主要是想复习一下hibernate。搭建springmvc+hibernate的框架的思路如下:
1、设计数据库:设计好表结构,最好符合3nf,采用hibernate tools将设计好的表自动生成对应的实体entity。
1、创建maven项目,按需映入maven包依赖。
2、搭建spring:配置spring对控件层bean的注入。
3、搭建hibernate:配置数据源,配置sessionfactory,配置事务,以及二级缓存ehcache的配置。
4、测试spring+hibernate的框架搭建,写单元测试junit,测试事务配置等。
5、映入springmvc:配置springmvc配置信息。
6、配置web.xml容器
7、测试三个框架的整合:maven编译打包部署服务器,测试。
1、数据库设计
设计一个权限、角色、用户的表。自然如果一个用户可以有多个角色,一个角色多个用户所拥有;一个角色拥有多个权限,一个权限对应多个角色。所以按照数据库表结构设计,符合3nf的话我们需要5张表进行存在。表的具体信息就不列出了(可以下在源码,里面还有数据库),表关系如下:
这里面id才用到是java的uuid(36位)
2、创建maven项目,编写pom.xml文件
创建一个maven的webapp项目,编写pom.xml文件,引入所需的包依赖,我这里就将所需的全部的映入了。
pom.xml文件内容如下:
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelversion>4.0.0</modelversion> <groupid>org.andy.sh</groupid> <artifactid>springmvc_hibernate_demo</artifactid> <packaging>war</packaging> <version>0.0.1-snapshot</version> <name>springmvc_hibernate_demo maven webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <spring.version>4.1.4.release</spring.version> <hibernate.version>4.3.8.final</hibernate.version> <jackson.version>2.5.0</jackson.version> </properties> <dependencies> <!-- junit --> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.12</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-core</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-beans</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-tx</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-web</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-test</artifactid> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- 使用springmvc需配置 --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>${spring.version}</version> </dependency> <!-- 关系型数据库整合时需配置 如hibernate jpa等 --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-orm</artifactid> <version>${spring.version}</version> </dependency> <!-- hibernate --> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-core</artifactid> <version>${hibernate.version}</version> </dependency> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-ehcache</artifactid> <version>${hibernate.version}</version> </dependency> <!-- 二级缓存ehcache --> <dependency> <groupid>net.sf.ehcache</groupid> <artifactid>ehcache</artifactid> <version>2.9.0</version> </dependency> <!-- log4j --> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>1.2.17</version> </dependency> <!-- mysql连接 --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.34</version> </dependency> <!-- c3p0数据源 --> <dependency> <groupid>com.mchange</groupid> <artifactid>c3p0</artifactid> <version>0.9.5-pre10</version> </dependency> <!-- json --> <dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.3</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.core</groupid> <artifactid>jackson-annotations</artifactid> <version>${jackson.version}</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.core</groupid> <artifactid>jackson-core</artifactid> <version>${jackson.version}</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.core</groupid> <artifactid>jackson-databind</artifactid> <version>${jackson.version}</version> </dependency> <!-- aop --> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjweaver</artifactid> <version>1.8.4</version> </dependency> <!-- servlet --> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>jstl</artifactid> <version>1.2</version> </dependency> </dependencies> <build> <finalname>springmvc_hibernate_demo</finalname> <plugins> <!-- run the junit unit tests in an isolated classloader --> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-surefire-plugin</artifactid> <version>2.4.2</version> <configuration> <skiptests>true</skiptests> </configuration> </plugin> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-war-plugin</artifactid> <version>2.3</version> <configuration> <webxml>src/main/webapp/web-inf/web.xml</webxml> </configuration> </plugin> <!-- generate java doc --> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-javadoc-plugin</artifactid> <version>2.9.1</version> <configuration> <javadocdirectory>target/javadoc</javadocdirectory> <reportoutputdirectory>target/javadoc</reportoutputdirectory> <charset>utf-8</charset> <encoding>utf-8</encoding> <docencoding>utf-8</docencoding> <show>private</show> </configuration> </plugin> <!-- 部署至本机 --> <plugin> <groupid>org.codehaus.cargo</groupid> <artifactid>cargo-maven2-plugin</artifactid> <version>1.0</version> <configuration> <container> <containerid>tomcat6x</containerid> <home>d:\webserver\apache-tomcat-6.0.39</home> </container> <configuration> <type>existing</type> <home>d:\webserver\apache-tomcat-6.0.39</home> </configuration> </configuration> </plugin> </plugins> </build> </project>
3、引入spring配置
编写配置文件,配置文件放在src/main/resources资源目录下(下同)。
项目所需的配置信息config.properties
#application configs #jdbc c3p0 config jdbc.driver = com.mysql.jdbc.driver jdbc.url = jdbc:mysql://localhost:3306/work?useunicode=true&characterencoding=utf-8 jdbc.username = root jdbc.password = 12345 #hibernate config hibernate.dialect = org.hibernate.dialect.mysqldialect hibernate.show_sql = true hibernate.format_sql = false hibernate.hbm2ddl.auto = update hibernate.cache.use_second_level_cache = true hibernate.cache.use_query_cache = true hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.ehcacheregionfactory hibernate.cache.provider_configuration_file_resource_path = ehcache.xml
3.1、spring配置
spring.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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:config.properties"/> <!-- 扫描service自动注入为bean --> <context:component-scan base-package="org.andy.work.service.impl,org.andy.work.dao.impl" /> </beans>
上面spring配置了对应包下组件bean自动注入管理,我们需要将dao,service的实现类交由spring管理,如(@repository,@service)。
3.2、引入日志文件配置log4j
log4j.properties的配置文件如下: ### set log levels ### log4j.rootlogger = info , c , d , e ### console ### log4j.appender.c = org.apache.log4j.consoleappender log4j.appender.c.target = system.out log4j.appender.c.layout = org.apache.log4j.patternlayout log4j.appender.c.layout.conversionpattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-mm-dd hh:mm:ss}] %c.%m(%l) | %m%n ### log file ### log4j.appender.d = org.apache.log4j.dailyrollingfileappender log4j.appender.d.file = ../logs/springmvc_hibernate_demo.log log4j.appender.d.append = true log4j.appender.d.threshold = info log4j.appender.d.layout = org.apache.log4j.patternlayout log4j.appender.d.layout.conversionpattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-mm-dd hh:mm:ss}] %c.%m(%l) | %m%n ### exception ### log4j.appender.e = org.apache.log4j.dailyrollingfileappender log4j.appender.e.file = ../logs/springmvc_hibernate_demo_error.log log4j.appender.e.append = true log4j.appender.e.threshold = error log4j.appender.e.layout = org.apache.log4j.patternlayout log4j.appender.e.layout.conversionpattern = [sspringmvc_hibernate_demo][%p] [%-d{yyyy-mm-dd hh:mm:ss}] %c.%m(%l) | %m%n
4、hibernate配置
hibernate的配置主要包括:配置数据源c3p0,配置sessionfactory,配置事务管理器,配置事务管理,其spring-hibernate.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"> <!-- 配置数据源 c3p0 --> <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource" destroy-method="close"> <property name="driverclass" value="${jdbc.driver}" /> <property name="jdbcurl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 请求超时时间 --> <property name="checkouttimeout" value="30000" /> <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 --> <property name="idleconnectiontestperiod" value="30" /> <!-- 连接数据库连接池最大空闲时间 --> <property name="maxidletime" value="30" /> <!-- 连接池初始化连接数 --> <property name="initialpoolsize" value="5" /> <property name="minpoolsize" value="5" /> <property name="maxpoolsize" value="20" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 --> <property name="acquireincrement" value="5" /> </bean> <!-- 配置hibernate的sessionfactory --> <bean id="sessionfactory" class="org.springframework.orm.hibernate4.localsessionfactorybean"> <!-- 注入数据源 相关信息看源码 --> <property name="datasource" ref="datasource" /> <!-- hibernate配置信息 --> <property name="hibernateproperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!-- 开启二级缓存 ehcache --> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path} </prop> </props> </property> <!-- 扫描hibernate注解配置的entity --> <property name="packagestoscan" value="org.andy.work.entity" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionmanager" class="org.springframework.orm.hibernate4.hibernatetransactionmanager"> <property name="sessionfactory" ref="sessionfactory" /> </bean> <!-- 配置事务增强处理bean,指定事务管理器 --> <tx:advice id="transactionadvice" transaction-manager="transactionmanager"> <!-- 配置详细事务处理语义 --> <tx:attributes> <tx:method name="insert*" propagation="required" /> <tx:method name="update*" propagation="required" /> <tx:method name="delete*" propagation="required" /> <tx:method name="get*" propagation="supports" read-only="true" /> <tx:method name="find*" propagation="supports" read-only="true" /> <tx:method name="select*" propagation="supports" read-only="true" /> <tx:method name="load*" propagation="supports" read-only="true" /> <!-- 其他采用默认事务方式 --> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- spring aop事务管理 --> <aop:config> <!-- 配置切入点 --> <aop:pointcut id="transactionpointcut" expression="execution(* org.andy.work.service..*impl.*(..))" /> <!-- 指定在txadvice切入点应用txadvice事务增强处理 --> <aop:advisor pointcut-ref="transactionpointcut" advice-ref="transactionadvice" /> </aop:config> </beans>
上面配置了二级缓存,ehcache,相关的具体信息查看上一篇hibernate二级缓存以及ehcache的搭建配置,下面是二级缓存的配置。
4.1、ehcache.xml的配置
<?xml version="1.0" encoding="utf-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:nonamespaceschemalocation="../config/ehcache.xsd"> <diskstore path="d:/ehcache" /> <!-- defaultcache setting. --> <defaultcache maxelementsinmemory="1000" eternal="false" timetoidleseconds="120" timetoliveseconds="120" maxelementsondisk="1000000" overflowtodisk="true" memorystoreevictionpolicy="lru"> </defaultcache> <!-- special objects setting. --> <cache name="org.andy.work.entity.acctuser" maxelementsinmemory="2" memorystoreevictionpolicy="lru" eternal="true" diskpersistent="false" overflowtodisk="false" maxelementsondisk="1000000" /> </ehcache>
上面hibernate二级缓存ehcache存放磁盘是d:/ehcache
5、生成业务entity实体
设计好数据表后,hibernate的实体有工具hibernate tools自动生成,eclipse需要安装hibernate tools插件(我在线安装过几次都不成功,推荐使用links离线安装,附录将介绍),所以不需要手工的书写,下面就贴一个用户信息的实体,acctuser.java
package org.andy.work.entity; // generated 2015-2-3 10:43:00 by hibernate tools 4.0.0 import java.util.date; import java.util.hashset; import java.util.set; import javax.persistence.column; import javax.persistence.entity; import javax.persistence.fetchtype; import javax.persistence.id; import javax.persistence.joincolumn; import javax.persistence.jointable; import javax.persistence.manytomany; import javax.persistence.table; import javax.persistence.temporal; import javax.persistence.temporaltype; import org.hibernate.annotations.cache; import org.hibernate.annotations.cacheconcurrencystrategy; import com.fasterxml.jackson.annotation.jsonignoreproperties; /** * acctuser generated by hbm2java */ @entity @table(name = "acct_user", catalog = "work") @cache(usage = cacheconcurrencystrategy.read_write) public class acctuser implements java.io.serializable { /** * */ private static final long serialversionuid = 6980093847795726310l; private string id; private string nickname; private string telephone; private date registertime; private set<acctrole> acctroles = new hashset<acctrole>(0); public acctuser() { } public acctuser(string id, string nickname) { this.id = id; this.nickname = nickname; } public acctuser(string id, string nickname, string telephone, date registertime, set<acctrole> acctroles) { this.id = id; this.nickname = nickname; this.telephone = telephone; this.registertime = registertime; this.acctroles = acctroles; } @id @column(name = "id", unique = true, nullable = false, length = 36) public string getid() { return this.id; } public void setid(string id) { this.id = id; } @column(name = "nick_name", nullable = false) public string getnickname() { return this.nickname; } public void setnickname(string nickname) { this.nickname = nickname; } @column(name = "telephone") public string gettelephone() { return this.telephone; } public void settelephone(string telephone) { this.telephone = telephone; } @temporal(temporaltype.timestamp) @column(name = "register_time", length = 19) public date getregistertime() { return this.registertime; } public void setregistertime(date registertime) { this.registertime = registertime; } @jsonignoreproperties(value={"acctusers", "acctauthorities"}) @manytomany(fetch = fetchtype.lazy) @cache(usage = cacheconcurrencystrategy.read_write) @jointable(name = "acct_user_role", catalog = "work", joincolumns = { @joincolumn(name = "user_id", nullable = false, updatable = false) }, inversejoincolumns = { @joincolumn(name = "role_id", nullable = false, updatable = false) }) public set<acctrole> getacctroles() { return this.acctroles; } public void setacctroles(set<acctrole> acctroles) { this.acctroles = acctroles; } }
上面有几个需要注意的:
上面大多数都是hibernate tools自动生成的,但是有几个需要手动添加:
1、如果这个实体使用二级缓存的话,需要添加@cache注解;
2、如果该实体里面还有集合元素(set, map,list),如果实体要采用二级缓存,那么这些集合元素必须也添加@cache注解。
3、@jsonignoreproperties注解是为了防止springmvc在json返回时产生循环输出使用,如果不配置的话就会出现json死循环(还有多对多,一对多的属性时)。
4、@jsonignore这个是在转换成json是忽略该属性,而@jsonignoreproperties(value={"acctusers", "acctauthorities"})则是忽略acctroles里面的acctusers和acctauthorites属性。
6、创建dao层
6.1dao接口
dao层和service层我们肯定采用的是面相接口编程的思想,所以,我们先定义一个通用的dao接口,genericdao.java
package org.andy.work.dao; import java.io.serializable; import java.util.list; /** * 创建时间:2015-2-6 下午2:26:42 * * @author andy * @version 2.2 * * dao通用接口 */ interface genericdao<t, pk extends serializable> { t load(pk id); t get(pk id); list<t> findall(); void persist(t entity); pk save(t entity); void saveorupdate(t entity); void delete(pk id); void flush(); }
在定义具体的userdao.java接口
package org.andy.work.dao; import org.andy.work.entity.acctuser; /** * 创建时间:2015-2-6 下午2:43:50 * * @author andy * @version 2.2 * * 用户dao接口 */ public interface userdao extends genericdao<acctuser, string> { }
6.2、dao层实现类
我们需要将dao层的实现类注入为bean,所以需要添加@repository注解,userdaoimpl如下:
package org.andy.work.dao.impl; import java.util.list; import org.andy.work.dao.userdao; import org.andy.work.entity.acctuser; import org.hibernate.session; import org.hibernate.sessionfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.repository; /** * 创建时间:2015-2-6 下午2:45:14 * * @author andy * @version 2.2 */ @repository("userdao") public class userdaoimpl implements userdao { @autowired private sessionfactory sessionfactory; private session getcurrentsession() { return this.sessionfactory.getcurrentsession(); } @override public acctuser load(string id) { return (acctuser) this.getcurrentsession().load(acctuser.class, id); } @override public acctuser get(string id) { return (acctuser) this.getcurrentsession().get(acctuser.class, id); } @suppresswarnings("unchecked") @override public list<acctuser> findall() { list<acctuser> acctusers = this.getcurrentsession().createquery("from acctuser").setcacheable(true).list(); return acctusers; } @override public void persist(acctuser entity) { this.getcurrentsession().persist(entity); } @override public string save(acctuser entity) { return (string) this.getcurrentsession().save(entity); } @override public void saveorupdate(acctuser entity) { this.getcurrentsession().saveorupdate(entity); } @override public void delete(string id) { acctuser entity = this.load(id); this.getcurrentsession().delete(entity); } @override public void flush() { this.getcurrentsession().flush(); } }
7、创建service层
7.1、service层接口
package org.andy.work.service; import java.util.list; import org.andy.work.entity.acctuser; /** * 创建时间:2015-2-6 下午3:18:57 * * @author andy * @version 2.2 * userservice接口 */ public interface userservice { acctuser load(string id); acctuser get(string id); list<acctuser> findall(); void persist(acctuser entity); string save(acctuser entity); void saveorupdate(acctuser entity); void delete(string id); void flush(); }
7.2、service层实现类
userserviceimpl就需要注入上面定义的dao层bean。
package org.andy.work.service.impl; import java.util.list; import org.andy.work.dao.userdao; import org.andy.work.entity.acctuser; import org.andy.work.service.userservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; /** * 创建时间:2015-2-6 下午3:24:16 * * @author andy * @version 2.2 userservice 的实现 */ @service("userservice") public class userserviceimpl implements userservice { @autowired private userdao userdao; @override public acctuser load(string id) { return userdao.load(id); } @override public acctuser get(string id) { return userdao.get(id); } @override public list<acctuser> findall() { return userdao.findall(); } @override public void persist(acctuser entity) { userdao.persist(entity); } @override public string save(acctuser entity) { return userdao.save(entity); } @override public void saveorupdate(acctuser entity) { userdao.saveorupdate(entity); } @override public void delete(string id) { userdao.delete(id); } @override public void flush() { userdao.flush(); } }
8、测试spring和hibernate的整合
我们可以在src/test/java编写测试类,测试上面的配置,如果测试成功已经基本大功告成。
package org.andy.work.service; import java.util.date; import java.util.list; import java.util.uuid; import org.andy.work.entity.acctuser; import org.apache.log4j.logger; 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.alibaba.fastjson.json; /** * 创建时间:2015-2-6 下午3:31:07 * * @author andy * @version 2.2 */ @runwith(springjunit4classrunner.class) @contextconfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" }) public class testuserservice { private static final logger logger = logger .getlogger(testuserservice.class); @autowired private userservice userservice; @test public void save() { acctuser acctuser = new acctuser(); acctuser.setid(uuid.randomuuid().tostring()); acctuser.setnickname("andy"); acctuser.setregistertime(new date()); acctuser.settelephone("13022221111"); string id = userservice.save(acctuser); logger.info(json.tojsonstring(id)); } }
9、引入springmvc
添加spring-mvc.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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 自动扫描@controller注入为bean --> <context:component-scan base-package="org.andy.work.controller" /> <!-- 以下为springmvc配置 --> <mvc:annotation-driven> <!-- 返回json数据,@response使用 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.mappingjackson2httpmessageconverter"> <property name="supportedmediatypes"> <list> <value>text/html;charset=utf-8</value> <value>application/json;charset=utf-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="viewclass" value="org.springframework.web.servlet.view.jstlview" /> <property name="prefix" value="/web-inf/views" /> <property name="suffix" value=".jsp" /> </bean> </beans>
上面配置了包扫描controller,[email protected]��,和视图层的配置。
10、配置web.xml容器
web容器是web项目的大脑,所以web容器,首先需要引入spring,让spring管理各个框架,并将其注入为bean。然后配置控制层的filter信息。并且配置了springmvc拦截的url为以.hmls结尾的请求。
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: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_2_5.xsd" id="webapp_id" version="2.5"> <display-name>springmvc_demo</display-name> <context-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value> </context-param> <filter> <filter-name>encodingfilter</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> <init-param> <param-name>forceencoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- opensessioninview配置 作用是延迟session关闭到view层 --> <filter> <filter-name>opensessioninviewfilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.opensessioninviewfilter</filter-class> <init-param> <param-name>singlesession</param-name> <param-value>true</param-value> </init-param> </filter> <!-- 监听servletcontext,启动contextconfiglocation中的spring配置信息 --> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.introspectorcleanuplistener</listener-class> </listener> <servlet> <description>spring mvc servlet</description> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextconfiglocation</param-name> <!-- 此处配置的是springmvc的配置文件 --> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>*.htmls</url-pattern> </servlet-mapping> <filter-mapping> <filter-name>opensessioninviewfilter</filter-name> <url-pattern>*.htmls</url-pattern> </filter-mapping> <!-- 配置session超时时间,单位分钟 --> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
11、创建控制层controller
控制层usercontroller
package org.andy.work.controller; import java.util.list; import org.andy.work.entity.acctuser; import org.andy.work.service.userservice; import org.apache.log4j.logger; 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.responsebody; /** * 创建时间:2015-2-7 上午11:49:00 * @author andy * @version 2.2 * 描述: 用户controller */ @controller @requestmapping("/user") public class usercontroller { private static final logger logger = logger.getlogger(usercontroller.class); @autowired private userservice userservice; @requestmapping("/showinfo/{userid}") public string showuserinfo(modelmap modelmap, @pathvariable string userid){ logger.info("查询用户:" + userid); acctuser userinfo = userservice.load(userid); modelmap.addattribute("userinfo", userinfo); return "/user/showinfo"; } @requestmapping("/showinfos") public @responsebody list<acctuser> showuserinfos(){ logger.info("查询用户全部用户"); list<acctuser> userinfos = userservice.findall(); return userinfos; } }
12、创建视图层
在src/main/webapp/web-inf/views下 创建user/showinfo.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <% string path = request.getcontextpath(); string basepath = request.getscheme() + "://" + request.getservername() + ":" + request.getserverport() + path + "/"; %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <base href="<%=basepath%>" /> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <title>userinfo</title> </head> <body> 用户信息 昵称: ${userinfo.nickname} 用户id:${userinfo.id} 用户电话:${userinfo.telephone } 注册时间: <fmt:formatdate value="${userinfo.registertime }" pattern="yyyy-mm-dd hh:mm:ss" /> 角色:[ <c:foreach items="${ userinfo.acctroles}" var="role"> ${role.name } 权限[ <c:foreach items="${ role.acctauthorities}" var="authority"> ${authority.name } </c:foreach> ] </c:foreach> ] <br /> ajax显示全部用户信息: <div id="show_all_user"></div> </body> <script type="text/javascript"> $.ajax({ type : "get", url : "user/showinfos.htmls", datatype : "json", success : function(data) { $(data).each( function(i, user) { var p = "<p>昵称:" + user.nickname + " 电话:" + user.telephone + " 注册时间:" + user.registertime + " id:" + user.id + "</p>"; $("#show_all_user").append(p); }); }, async : true }); </script> </html>
13、部署服务器测试
使用maven打包部署:clean compile package
部署到tomcat,测试
主要测试上面的 http://localhost:8080/springmvc_hibernate_demo/user/showinfo/6e5afb1d-50e1-45fe-b6fe-b9e399415387.htmls
和http://localhost:8080/springmvc_hibernate_demo/user/showinfos.htmls (json数据返回)
上面视图层就包含了这两条url请求的测试:
ok,到此spring+springmvc+hibernate搭建完毕。
博客来源:http://blog.csdn.net/fengshizty?viewmode=list
项目源码:http://download.csdn.net/detail/fengshizty/8432647
希望能帮助有需要的朋友,后续继续补充相关资料,谢谢大家对本站的支持!
下一篇: Java 面试题和答案 -(上)