1. 程式人生 > >Spring-SpringMVC-Hibernate maven整合

Spring-SpringMVC-Hibernate maven整合

前面的一篇文章http://blog.csdn.net/wangdianyong/article/details/38842693曾經也寫過三者之間的整合,但是當時沒有用maven

導致了專案中含有大量包,看著十分不美觀!

下面就使用maven重新整合一下!新手還望不吝賜教!

maven專案的建立過程省略

看專案結構


各個配置檔案程式碼我貼一下,不一樣的地方請自行修改

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>com.iss</groupId>
	<artifactId>maven03</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>maven03</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<!-- log4j 日誌 -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<!-- servlet API -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1-b09</version>
			<scope>provided</scope>
		</dependency>
		<!-- MySQL驅動 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.24</version>
		</dependency>
		<!-- mchange C3P0 資料來源 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5-pre2</version>
		</dependency>
		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<!-- fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.29</version>
		</dependency>

		<!-- struts2 -->
		<!-- <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> 
			<version>2.3.14</version> <exclusions> <exclusion> <groupId>javassist</groupId> 
			<artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> 
			<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> 
			<version>2.3.14</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> 
			<artifactId> struts2-convention-plugin</artifactId> <version>2.3.14</version> 
			</dependency> -->


		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<!-- aspectjweaver -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.2</version>
		</dependency>
		<!-- hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.2.0.Final</version>
		</dependency>

	</dependencies>
	<build>
		<!-- Maven外掛 -->
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
			</plugin>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-javadoc-plugin</artifactId>
				<configuration>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.7.2</version>
				<configuration>
					<forkMode>once</forkMode>
					<argLine>-Dfile.encoding=UTF-8</argLine>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>8.1.14.v20131031</version>

				<configuration>
					<webApp>
						<contextPath>/maven03</contextPath>
					</webApp>
				</configuration>
			</plugin>
		</plugins>

	</build>
</project>


database.properties

hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true

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-3.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	">
	<!-- 使用C3P0資料來源,MySQL資料庫 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<!-- MySQL5 -->
		<property name="driverClass" value="${driverClassName}"></property>
		<property name="jdbcUrl" value="${url}"></property>
		<property name="user" value="${username}"></property>
		<property name="password" value="${password}"></property>
		<property name="maxPoolSize" value="40"></property>
		<property name="minPoolSize" value="1"></property>
		<property name="initialPoolSize" value="1"></property>
		<property name="maxIdleTime" value="20"></property>
	</bean>


	<!-- session工廠 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<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>
			</props>
		</property>

		<!-- 註解方式配置 -->
		<property name="packagesToScan">
			<list>
				<value>com.iss.model</value>
			</list>
		</property>


	</bean>

	<!-- 配置事務 -->
	<bean name="txManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="txManager" />


</beans>
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-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- 自動掃描controller包下的所有類,使其認為spring mvc的控制器 -->
	<context:component-scan base-package="com.iss.controller" />

	<!-- 避免IE執行AJAX時,返回JSON出現下載檔案 -->
	<!-- <bean id="mappingJacksonHttpMessageConverter" -->
	<!-- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> -->
	<!-- <property name="supportedMediaTypes"> -->
	<!-- <list> -->
	<!-- <value>text/html;charset=UTF-8</value> -->
	<!-- </list> -->
	<!-- </property> -->
	<!-- </bean> -->

	<!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 -->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
		<property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" 
		/>json轉換器 </list> </property> </bean> -->
	<mvc:annotation-driven />
	<!-- 對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

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-3.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	">
	<!--啟用註解 -->
	<context:annotation-config />

	<context:component-scan
		base-package="com.iss.action,com.iss.dao.impl,com.iss.service"></context:component-scan>

	<!-- 引入屬性檔案Hibernate屬性配置 -->
	<context:property-placeholder location="classpath:database.properties" />

	<!-- 自動掃描dao和service包(自動注入) -->
	<!-- <context:component-scan base-package="com.iss*" /> -->

</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name></display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/classes/spring.xml,/WEB-INF/classes/spring-hibernate.xml,</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<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>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--Hibernate的session丟失解決方法 -->
	<filter>
		<filter-name>openSessionInView</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>openSessionInView</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- struts2配置 -->
	<!-- <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 
		</filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> 
		</filter-mapping> -->
	<!-- springMVC 配置 -->
	<servlet>
		<description>spring mvc servlet</description>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<description>spring mvc 配置檔案</description>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/classes/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>




	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

src/main/java中各個包的內容

com.iss.controller.UserController

package com.iss.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.iss.model.User;
import com.iss.service.UserService;

@Controller("userController")
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("/reg")
	public String saveUser(User user) {
		System.out.println(userService);
		userService.save(user);
		return "success";
	}

}

com.iss.dao.UserDao
package com.iss.dao;

import com.iss.model.User;

public interface UserDao<T> {
	public User save(T o);

}

com.iss.dao.impl.UserDaoImpl
package com.iss.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.iss.dao.UserDao;
import com.iss.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao<User> {

	@Autowired
	private SessionFactory sessionFactory;

	//
	// public void setSessionFactory(SessionFactory sessionFactory) {
	// this.sessionFactory = sessionFactory;
	// }
	//
	// public SessionFactory getSessionFactory() {
	// return sessionFactory;
	// }

	@Override
	public User save(User o) {
		Session session = sessionFactory.getCurrentSession();
		session.save(o);
		return o;
	}

}

com.iss.model.User
package com.iss.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User implements Serializable {
	private int id;
	private String name;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

com.iss.service.UserService
package com.iss.service;

import com.iss.model.User;

public interface UserService {

	public User save(User user);
}

com.iss.service.impl.UserServiceImpl
package com.iss.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.iss.dao.UserDao;
import com.iss.model.User;
import com.iss.service.UserService;


@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao<User> userDao;


	@Override
	public User save(User user) {
		// TODO Auto-generated method stub
		return userDao.save(user);
	}


}

index,jsp
<body>
	<form action="userAction" method="post">
		<table width="207" border="0" align="center">
			<tr>
				<td colspan="2" align="center" nowrap="nowrap">使用者註冊</td>
			</tr>
			<tr>
				<td width="68" nowrap="nowrap">使用者名稱</td>
				<td width="127" nowrap="nowrap"><label> <input
						name="name" type="text" id="username" size="20" /> </label></td>
			</tr>
			<tr>
				<td colspan="2" align="center" nowrap="nowrap"><label>
						<input type="submit" value="註冊" /> <input type="reset" value="重填" />
				</label></td>
			</tr>
		</table>
	</form>
</body>

success.jsp
<body>${user.name }
</body>
完成之後mvn install 部署到tomcat伺服器即可!