Springmvc+Spring+Hibernate+maven 搭建开发项目
在做的一个项目并不是由我来搭建,所以就练习一下Springmvc+Spring+Hibernate的搭建,这是本人第一次写博客,如有错误或建议请在评论提出。
博客的编写参考于:http://blog.csdn.net/shin7914/article/details/51892469
IDE:myeclipse JDK:1.7 tomcat:7.0.77
项目目录图:
一、maven安装与配置
使用的maven是3.0.4版本,安装就不多说了直接百度下载就行了,在myeclipse中的配置如下图

使用的仓库是阿里云仓库和中央仓库,在maven目录下conf中的setting.xml中进行配置
<!-- 阿里云仓库 --> <mirror> <id>alimaven</id> <mirrorOf>central</mirrorOf> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/repositories/central/</url> </mirror> <!-- 中央仓库1 --> <mirror> <id>repo1</id> <mirrorOf>central</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://repo1.maven.org/maven2/</url> </mirror> <!-- 中央仓库2 --> <mirror> <id>repo2</id> <mirrorOf>central</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://repo2.maven.org/maven2/</url> </mirror>
二、新建maven项目并添加配置文件
1、新建项目



不选择filter会导致项目没有web.xml和WEB-INF文件夹,当然也可以自己创建。

2、编写配置文件
以下为配置文件的名字:pom.xml,web.xml,spring-mvc.xml,spring-context.xml,spring-transaction.xml,spring-dao.xml,log4j2.xml和jdbc.properties。
其中通过spring-context.xml对spring-transaction.xml和spring-dao.xml进行关联。
pom.xml的代码:
<properties> <!-- 参数配置 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <downloadJavadocs>true</downloadJavadocs> <downloadSources>true</downloadSources> <jdk.version>1.7</jdk.version> <!-- ************ 依赖版本号 **************************** --> <spring.version>4.3.6.RELEASE</spring.version> <hibernate.version>4.3.6.Final</hibernate.version> <mysql.version>5.1.6</mysql.version> <druid.version>1.0.27</druid.version> <!-- 测试 --> <junit.version>4.12</junit.version> <!-- 日志 --> <log4j2.version>2.7</log4j2.version> <slf4j.version>1.7.21</slf4j.version> <!-- servlet --> <servlet.version>3.1.0</servlet.version> <jsp-api.version>2.0</jsp-api.version> <!-- apache公共包 --> <commons-beanutils.version>1.7.0</commons-beanutils.version> <commons-logging.version>1.1.1</commons-logging.version> <commons-logging-api.version>1.1</commons-logging-api.version> <commons-codec.version>1.9</commons-codec.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <commons-io.version>2.4</commons-io.version> <commons-lang.version>2.6</commons-lang.version> <commons-lang3.version>3.1</commons-lang3.version> </properties> <dependencies> <!-- `spring start` --> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <!-- spring aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- spring aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- spring test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- spring orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- spring web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>${spring.version}</version> </dependency> <!-- `spring end` --> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <!-- jdbc driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- connection pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- junit test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- logs --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- `apache commons start` --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>${commons-logging.version}</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>${commons-logging-api.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${commons-lang.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <!-- `apache commons end` --> </dependencies> <build> <finalName>ssh</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.hbm.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources> </build>
spring、hibernate等等的版本都在里面,数据库链接池用的是druid。
web.xml的代码:
!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置spring ioc容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring-context.xml</param-value> </context-param> <!-- 配置springmvc 的DispatcherServlet 前置控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 配置 Druid 监控信息显示页面 --> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> <init-param> <!-- 允许清空统计数据 --> <param-name>resetEnable</param-name> <param-value>true</param-value> </init-param> <init-param> <!-- 用户名 --> <param-name>loginUsername</param-name> <param-value>druid</param-value> </init-param> <init-param> <!-- 密码 --> <param-name>loginPassword</param-name> <param-value>druid</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- 字符集过滤器 --> <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> <!-- session延时过滤器 --> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class> org.springframework.orm.hibernate4.support.OpenSessionInViewFilter </filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>flushMode</param-name> <param-value>AUTO</param-value> </init-param> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/> </bean> <!-- 自动扫描并装配bean(多个使用;隔开) --> <context:component-scan base-package="com.test.controller" /> <!-- 启用注解驱动 --> <mvc:annotation-driven> <!-- 配置消息转换器 --> <mvc:message-converters register-defaults="true"> <ref bean="stringHttpMessageConverter" /> </mvc:message-converters> </mvc:annotation-driven> <!-- 创建请求参数转换器 --> <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" index="0"></constructor-arg> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </beans>
spring-context.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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-- 导入springDao配置文件 --> <import resource="classpath*:spring/spring-dao.xml" /> <!-- 导入spring事务配置文件 --> <import resource="classpath*:spring/spring-transaction.xml" /> <!-- 导入spring定时任务配置文件 --> <import resource="classpath*:spring/spring-task.xml" /> <!-- 配置扫描注解,不扫描@Controller注解 --> <context:component-scan base-package="com.newyali"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 开启AOP注解扫描 --> <aop:aspectj-autoproxy /> </beans>
spring-transaction.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 创建事务管理器--> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置事务传播特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="*" read-only="false" /> </tx:attributes> </tx:advice> <!-- 开启AOP注解扫描 --> <aop:aspectj-autoproxy /> <!-- AOP配置 --> <aop:config expose-proxy="true"> <aop:pointcut id="txPointcut" expression="execution(* com.test.*..service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> </beans>
spring-dao.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:property-placeholder location="classpath:config/jdbc.properties"/> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testOnReturn" value="${jdbc.testOnReturn}" /> <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> <property name="logAbandoned" value="${jdbc.logAbandoned}" /> <property name="filters" value="${jdbc.filters}" /> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">false</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:com/test/entities/**/*.hbm.xml</value> </list> </property> </bean> </beans>
log4j2.xml的代码:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="off"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n" /> </Console> </Appenders> <Loggers> <!-- hibernate log configure --> <logger name="org.hibernate" level="WARN"/> <logger name="org.hibernate.SQL" level="DEBUG"/> <logger name="org.hibernate.tool.hbm2ddl" level="WARN"/> <!-- <logger name="log4j.logger.org.hibernate.type" level="DEBUG"/> --> <!-- <logger name="log4j.logger.org.hibernate.cache" level="DEBUG"/> --> <!-- <logger name="log4j.logger.org.hibernate.jdbc" level="DEBUG"/> --> <!-- 减少部分debug日志 --> <logger name="druid.sql" level="INFO"/> <logger name="org.ehcache" level="INFO"/> <logger name="org.springframework" level="INFO"/> <logger name="org.apache" level="INFO"/> <!-- 业务debug日志 --> <logger name="com.newyali" level="DEBUG"/> <Root level="debug"> <AppenderRef ref="Console" /> </Root> </Loggers> </Configuration>
jdbc.properties的代码:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\:///test?useUnicode\=true&characterEncoding\=UTF-8 jdbc.username=root jdbc.password=root jdbc.initialSize=3 jdbc.minIdle=2 jdbc.maxActive=60 jdbc.maxWait=60000 jdbc.minEvictableIdleTimeMillis=300000 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.validationQuery=SELECT 1 jdbc.testWhileIdle=true jdbc.testOnBorrow=false jdbc.testOnReturn=false jdbc.poolPreparedStatements=false jdbc.maxPoolPreparedStatementPerConnectionSize=20 jdbc.removeAbandoned=true jdbc.removeAbandonedTimeout=120 jdbc.logAbandoned=false jdbc.filters=mergeStat
三、编写实体类,dao层,dao层接口实现类,service层,service层接口实现类和实体类的controller
User.java的代码:
package com.test.entities; public class User { private Integer id; private String name; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
User.hbm.xml的代码:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.test.entities.User" table="USER"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" /> </property> </class> </hibernate-mapping>
UserDao.java的代码:
package com.test.dao; import com.test.entities.User; public interface UserDao { public void addUser(User user); }
UserDaoImpl.java的代码:
package com.test.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.test.dao.UserDao; import com.test.entities.User; @Repository("userDao") public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void addUser(User user) { sessionFactory.getCurrentSession().save(user); } }
UserService.java的代码:
package com.test.service; import com.test.entities.User; public interface UserService { public void addUser(User user); }
UserServiceImpl.java的代码:
package com.test.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.dao.UserDao; import com.test.entities.User; import com.test.service.UserService; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void addUser(User user) { // TODO Auto-generated method stub userDao.addUser(user); } }
UserController的代码:
package com.test.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.test.entities.User; import com.test.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="sucess.do") public String add(HttpServletRequest request){ String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username+" "+password); User user = new User(); user.setName(username); user.setPassword(password); userService.addUser(user); return "sucess"; } }
运行:填写用户 密码,添加成功。完成~

浙公网安备 33010602011771号