Preface
Today I will review the construction of SpringMVC+Hibernate. I originally thought that the Spring-Security permission control framework will also be included in it, but I found that there is too much content. Let's leave it to the next article. This article mainly builds SpringMVC4.1.4 and Hibernate4.3.8. I have also used a lot of SpringMVC before. This part is very familiar with it. After all, SpringMVC has been developed for more than a year. This time, the persistence layer uses Hibernate, the data source uses c3p0, and the database uses MySQL temporarily. I mainly want to review Hibernate. The idea of building the framework of SpringMVC+Hibernate is as follows:
1. Design database: Design the table structure, it is best to meet 3NF, and use Hibernate tools to automatically generate the corresponding entity entity.
1. Create a Maven project and enter the Maven package dependencies as needed.
2. Build Spring: Configure Spring injection of control layer beans.
3. Build Hibernate: configure data sources, configure SessionFactory, configure transactions, and configure secondary cache ehcache.
4. Test the framework construction of Spring+Hibernate, write unit test JUnit, test transaction configuration, etc.
5. Input SpringMVC: Configure SpringMVC configuration information.
6. Configure web.xml container
7. Test the integration of three frameworks: Maven compiles, packages and deploys servers, and tests.
1. Database design
Design a table of permissions, roles, and users. Of course, if a user can have multiple roles, one role owns multiple users; one role has multiple permissions, and one permission corresponds to multiple roles. Therefore, according to the database table structure design, if it meets 3NF, we need 5 tables to exist. The specific information of the table is not listed (you can download it in the source code, and there is also a database in it), and the table relationship is as follows:
Only in this ID is used is the UUID (36-bit)
2. Create a Maven project and write a pom.xml file
Create a Maven webapp project, write a pom.xml file, and introduce the required package dependencies. I will map all the required ones here.
The content of the pom.xml file is as follows:
<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> <!-- Configuring with SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- When integrating a relational database, you need to configure such as 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> <!-- Secondary cache 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 connection--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- c3p0 data source--> <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> <!-- Deploy to native --> <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. Introduce Spring Configuration
Write a configuration file, and place the configuration file in the src/main/resources resource directory (same below).
Configuration information required by the project config.properties
#application configs#jdbc c3p0 configjdbc.driver = com.mysql.jdbc.Driverjdbc.url = jdbc:mysql://localhost:3306/work?useUnicode=true&characterEncoding=utf-8jdbc.username = rootjdbc.password = 12345#hibernate confighibernate.dialect = org.hibernate.dialect.MySQLDialecthibernate.show_sql = truehibernate.format_sql = falsehibernate.hbm2ddl.auto = updatehibernate.cache.use_second_level_cache = truehibernate.cache.use_query_cache = truehibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactoryhibernate.cache.provider_configuration_file_resource_path = ehcache.xml
3.1. Spring configuration
The configuration file of spring.xml is as follows:
<?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"> <!-- Loading configuration file --> <context:property-placeholder location="classpath:config.properties"/> <!-- Scan service automatically injected as bean --> <context:component-scan base-package="org.andy.work.service.impl,org.andy.work.dao.impl" /></beans>
The above spring configures automatic bean injection management of the corresponding component beans under the package. We need to hand over the implementation class of dao and service to spring to manage, such as (@Repository, @Service).
3.2. Introduce log file configuration Log4j
The configuration file of log4j.properties is as follows: ### set log levels ###log4j.rootLogger = INFO , C , D , E ### console ###log4j.appender.C = org.apache.log4j.ConsoleAppenderlog4j.appender.C.Target = System.outlog4j.appender.C.layout = org.apache.log4j.PatternLayoutlog4j.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.DailyRollingFileAppenderlog4j.appender.D.File = ../logs/springmvc_hibernate_demo.loglog4j.appender.D.Append = truelog4j.appender.D.Threshold = INFO log4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.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.DailyRollingFileAppenderlog4j.appender.E.File = ../logs/springmvc_hibernate_demo_error.loglog4j.appender.E.Append = truelog4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayoutlog4j.appender.E.layout.ConversionPattern = [sspringmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n 4. Hibernate configuration
The configuration of Hibernate mainly includes: configuring the data source c3p0, configuring SessionFactory, configuring transaction manager, and configuring transaction management. The spring-hibernate.xml file is as follows:
<?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 http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"> <!-- Configure Data Source c3p0 --> <bean id="dataSource" 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}" /> <!-- Request timeout--> <property name="checkoutTimeout" value="30000" /> <!-- Check all idle connections in the connection pool every 60 seconds. Default value: 0, not check --> <property name="idleConnectionTestPeriod" value="30" /> <!-- Maximum idle time for connection database connection pool--> <property name="maxIdleTime" value="30" /> <!-- Number of connections initialized connections in connection pool--> <property name="initialPoolSize" value="5" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <!-- Number of connections obtained by c3p0 at the same time at one time when the connection in the connection pool is exhausted. Default value: 3 --> <property name="acquireIncrement" value="5" /> </bean> <!-- Configure hibernate SessionFactory --> <bean id="sessionFactory"> <!-- See the source code for injecting data source--> <property name="dataSource" ref="dataSource" /> <!-- hibernate configuration information--> <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> <!-- Turn on Level 2 cache 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> <!-- Scan the entity of the hibernate annotation configuration --> <property name="packagesToScan" value="org.andy.work.entity" /> </bean> <!-- Configure transaction manager --> <bean id="transactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Configure transaction enhancement processing beans and specify transaction manager --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <!-- Configure detailed transaction processing semantics --> <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="find*" propagation="SUPPORTS" read-only="true" /> <!-- Others use default transaction methods --> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- Spring aop transaction management-> <aop:config> <!-- Configure pointcut--> <aop:pointcut id="transactionPointcut" expression="execution(* org.andy.work.service..*Impl.*(..))" /> <!-- Specify to apply txAdvice transaction enhancement processing at txAdvice pointcut--> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config></beans> The above is configured with the secondary cache and ehcache. For the relevant specific information, please see the previous article Hibernate secondary cache and ehcache construction configuration. The following is the configuration of the secondary cache.
4.1. Ehcache.xml configuration
<?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>
The above Hibernate secondary cache ehcache is D:/ehcache
5. Generate business entity
After designing the data table, Hibernate entities have the tool Hibernate tools automatically generated. Eclipse requires the installation of Hibernate tools plug-in (I have installed it online several times but it is not successful. It is recommended to use links to install offline, and the appendix will introduce it). Therefore, there is no need to write manually. Here is an entity with user information, AcctUser.java
package org.andy.work.entity;// Generated 2015-2-3 10:43:00 by Hibernate Tools 4.0.0import 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, updateable = 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; }} There are a few things to note above:
Most of the above are automatically generated by Hibernate tools, but there are several that need to be added manually:
1. If this entity uses Level 2 cache, you need to add the @cache annotation;
2. If there are set elements (set, map, list) in the entity, and if the entity wants to use a secondary cache, then these set elements must also be added with @cache annotation.
3. @JsonIgnoreProperties annotation is to prevent SpringMVC from producing loop output when json returns. If it is not configured, json dead loop will occur (and many-to-many, one-to-many properties).
4. @JsonIgnore is converting to json to ignore this property, while @JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"}) ignores the acctUsers and acctAuthorities properties in acctRoles.
6. Create a Dao layer
6.1Dao interface
We must adopt the idea of facial interface programming in the Dao layer and the Service layer, so we first define a general Dao interface, GenericDao.java
package org.andy.work.dao;import java.io.Serializable;import java.util.List;/** * Created time: 2015-2-6 2:26:42 pm * * @author andy * @version 2.2 * * Dao General Interface*/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();}Define the specific UserDao.java interface
package org.andy.work.dao;import org.andy.work.entity.AcctUser;/** * Creation time: 2015-2-6 2:43:50 pm * * @author andy * @version 2.2 * * User Dao interface*/public interface UserDao extends GenericDao<AcctUser, String> {}6.2. Dao layer implementation class
We need to inject the implementation class of the Dao layer into beans, so we need to add the @Repository annotation, UserDaoImpl is as follows:
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;/** * Creation time: 2015-2-6 2:45:14 pm * * @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. Create a Service Layer
7.1. Service layer interface
package org.andy.work.service;import java.util.List;import org.andy.work.entity.AcctUser;/** * Creation time: 2015-2-6 3:18:57 pm * * @author andy * @version 2.2 * userService interface*/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 layer implementation class
UserServiceImpl needs to inject the Dao layer bean defined above.
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;/** * Creation time: 2015-2-6 3:24:16 pm * * @author andy * @version 2.2 UserService Implementation*/@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. Test the integration of Spring and Hibernate
We can write a test class in src/test/java to test the above configuration. If the test is successful, it will basically be completed.
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;/** * Creation time: 2015-2-6 3:31:07 pm * * @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. Introduce SpringMVC
Add spring-mvc.xml file
<?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"> <!-- Automatic scan @Controller injection as bean --> <context:component-scan base-package="org.andy.work.controller" /> <!-- The following is SpringMVC configuration --> <mvc:annotation-driven> <!-- Return json data, @response-used-> <mvc:message-converters register-defaults="true"> <bean> <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> <!-- Parse the model view name, that is, add pre- and suffixes to the model view name--> <bean> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views" /> <property name="suffix" value=".jsp" /> </bean></beans>
The package scanning controller, [email protected]��, and view layer configurations are configured above.
10. Configure the web.xml container
Web containers are the brain of web projects, so web containers first need to introduce spring, let spring manage various frameworks, and inject them into beans. Then configure the filter information of the control layer. And the url intercepted by springmvc is configured to requests ending in .hmls.
The web.xml file is as follows:
<?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" 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> <!-- The openSessionInView configuration is to delay the session closing to the view layer --> <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> <!-- Listen to servletContext and start spring configuration information in contextConfigLocation--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Prevent spring memory overflow listener --> <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> <!-- Here is the SpringMVC configuration file --> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <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> <!-- Configure session timeout, in minutes--> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list></web-app>
11. Create a control layer controller
Control layer 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;/** * Creation time: 2015-2-7 11:49:00 am * @author andy * @version 2.2 * Description: User 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("Query user: " + userId); AcctUser userInfo = userService.load(userId); modelMap.addAttribute("userInfo", userInfo); return "/user/showInfo"; } @RequestMapping("/showInfos") public @ResponseBody List<AcctUser> showUserInfos(){ LOGGER.info("Query all users of the user"); List<AcctUser> userInfos = userService.findAll(); return userInfos; }}12. Create a view layer
Create user/showInfo.jsp under src/main/webapp/WEB-INF/views
<%@ 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> User information nickname: ${userInfo.nickName} User id: ${userInfo.id} User phone: ${userInfo.telephone } Registration time: <fmt:formatDate value="${userInfo.registerTime }" pattern="yyyy-MM-dd HH:mm:ss" /> Role: [ <c:forEach items="${ userInfo.acctRoles}" var="role"> ${role.name } Permissions[ <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
希望能帮助有需要的朋友,后续继续补充相关资料,谢谢大家对本站的支持!