您的位置:首页 > 编程语言 > Java开发

java web项目搭建(spring4+springMVC+hibernate)

2016-04-16 22:47 549 查看
一、创建maven项目

1、新建项目

eclipse内“new”->”project”->Maven Project->next->”Select an Archetype”选择“….quickstart”->next->输入group id,Artifact Id,Package->finish。

2.调整项目结构

创建properties文件目录,选中项目->右键->source folder->弹出的窗口内输入“profile/dev”–本地配置文件;在profile目录下创建test和release目录,分别放置测试环境和正式环境的配置文件;

创建资源目录,选中项目->右键->source folder->弹出的窗口内输入“src/main/resources”,放置spring等的配置文件及webapp等目录;

调整各个包的顺序:选中项目->右键->build path->configure build path->在弹出的窗口内选择“order and Export”tag,通过up和down等按钮调整包的顺序。

二、添加spring4+springMVC+hibernate4依赖

在pom.xml内添加依赖,依赖包可以通过spring官网或者http://mvnrepository.com查询对应的mvn依赖。

<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>study</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.1.7.RELEASE</spring.version>
<hibernate.version>4.2.0.Final</hibernate.version>
<dao-hibernate.version>1.2.0</dao-hibernate.version>
<sitemesh.version>2.4.2</sitemesh.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysqldriver.version>5.1.20</mysqldriver.version>
<commons-lang3.version>3.1</commons-lang3.version>
<guava.version>16.0.1</guava.version>
<joda.version>2.3</joda.version>
<httpclient.version>4.3.2</httpclient.version>
<slf4j.version>1.7.5</slf4j.version>
<perf4j.version>0.9.16</perf4j.version>
<logback.version>1.0.13</logback.version>
<junit.version>4.11</junit.version>
<mockito.version>1.9.5</mockito.version>
<freemarker.version>2.3.16</freemarker.version>
<jedis.version>2.2.1</jedis.version>
<ehcache.version>2.6.8</ehcache.version>
</properties>

<dependencies>

<!-- spring start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</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-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</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-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring end -->

<!-- hibernate start -->
<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>
<dependency>
<groupId>com.googlecode.genericdao</groupId>
<artifactId>dao-hibernate</artifactId>
<version>${dao-hibernate.version}</version> <!-- use current version -->
</dependency>
<!-- hibernate end -->

<!-- AOP begin -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.3</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<!-- AOP end -->

<!-- j2ee start-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<!-- 支持写jsp时标签代码提示 -->
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- j2ee end-->

<!-- sitemesh2 -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
<version>${sitemesh.version}</version>
</dependency>

<!-- db -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysqldriver.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.9</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>

<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.15</version>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>

<!-- GENERAL UTILS begin -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- joda  -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda.version}</version>
</dependency>

<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>20030211.134440</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<!-- 加密 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpg-jdk16</artifactId>
<version>1.45</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- GENERAL UTILS end -->

<!-- xml -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.7</version>
</dependency>

<dependency>
<groupId>xmlpull</groupId>
<artifactId>xmlpull</artifactId>
<version>1.1.3.1</version>
</dependency>

<!-- http -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpclient.version}</version>
</dependency>

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0.1</version>
</dependency>

<!-- LOGGING begin -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.perf4j</groupId>
<artifactId>perf4j</artifactId>
<version>${perf4j.version}</version>
</dependency>

<!-- 代码直接调用log4j会被桥接到slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!-- 代码直接调用common-logging会被桥接到slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!-- 代码直接调用java.util.logging会被桥接到slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!-- logging end -->

<!-- 定时器 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

<!-- template engine -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>

<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>${ehcache.version}</version>
</dependency>

<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>

<!-- kaptcha -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>

<!-- 七牛 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>sdk</artifactId>
<version>6.1.0</version>
</dependency>

<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.0.8</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<excludes>
<exclude>webapp/**</exclude> <!-- 排查 webapp目录 -->
</excludes>
</resource>
</resources>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<debug>true</debug>
<showWarnings>true</showWarnings>
<encoding>UTF-8</encoding>
</configuration>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<server>tomcat</server>
<ignorePackaging>true</ignorePackaging>
<path>/</path>
<port>8888</port>
<uriEncoding>UTF-8</uriEncoding>
<warSourceDirectory>${basedir}/src/main/resources/webapp</warSourceDirectory> <!-- webapp 目录 -->
</configuration>
</plugin>

<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
<configuration>
<server>tomcat-7</server>
<ignorePackaging>true</ignorePackaging>
<protocol>org.apache.coyote.http11.Http11NioProtocol</protocol>
<path>/</path>
<port>8888</port>
<uriEncoding>UTF-8</uriEncoding>
<warSourceDirectory>${basedir}/src/main/resources/webapp</warSourceDirectory> <!-- webapp 目录 -->
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<inherited>true</inherited>
<configuration>
<includes>
<include>**/**.class</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>io.spring.repo.maven.release</id>
<url>http://repo.spring.io/release/</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>

<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<resources>
<resource>
<directory>${basedir}/profile/dev</directory>
</resource>
</resources>
</build>
</profile>

<profile>
<id>test</id>
<build>
<resources>
<resource>
<directory>${basedir}/profile/test</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<containerConfigXML>svn.info</containerConfigXML>
<warName>study</warName>
<warSourceDirectory>${basedir}/src/main/resources/webapp</warSourceDirectory>
<outputDirectory>${project.build.directory}/study</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release</id>
<build>
<resources>
<resource>
<directory>${basedir}/profile/release</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<detail>true</detail>
<containerConfigXML>svn.info</containerConfigXML>
<warName>study</warName>
<warSourceDirectory>${basedir}/src/main/resources/webapp</warSourceDirectory>
<outputDirectory>${project.build.directory}/study</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>


三、添加配置文件

1.spring配置文件

在src/main/resources目录下添加com.test.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="no" default-lazy-init="false">

<!-- 主应用 properties files -->
<bean id="main_propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath*:com.test.properties</value>
</list>
</property>
</bean>

<import resource="com.test.db.context.xml" /><!-- 数据库配置 -->
<!-- 开启扫描,把controller排除在外 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:annotation-config />
<context:component-scan base-package="com.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
</beans>


数据源、sessionFactory、事务等配置文件com.test.db.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:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
default-lazy-init="false" default-autowire="no">

<!--  c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="initialPoolSize" value="${com.test.jdbc.pool.init.size}" />
<property name="minPoolSize" value="${com.test.jdbc.pool.init.size}" />
<property name="maxPoolSize" value="${com.test.jdbc.pool.max.size}" />
<property name="maxIdleTime" value="60" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="acquireIncrement" value="2" />
<property name="acquireRetryAttempts" value="10" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="testConnectionOnCheckin" value="true" />
<property name="testConnectionOnCheckout" value="true" />
<property name="maxStatements" value="10" />
<property name="preferredTestQuery" value="SELECT 'x'" />

<property name="driverClass" value="${com.test.jdbc.driverClass}" />
<property name="jdbcUrl" value="${com.test.jdbc.url}" />
<property name="user" value="${com.test.jdbc.username}" />
<property name="password" value="${com.test.jdbc.password}" />
</bean>

<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties" value="classpath*:hibernate.properties" />
<!-- 指定namedQuery配置文件位置 -->
<property name="mappingDirectoryLocations" value="${hibernate.mappingDirectoryLocations}" />
<property name="packagesToScan" value="${hibernate.packagesToScan}" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 对于service使用annotation声明事物 -->
<tx:annotation-driven mode="proxy" proxy-target-class="true" transaction-manager="transactionManager" order="100" />

<!-- 切换数据源 -->
<bean id="dataSourceAdvice" class="com.test.common.aop.DataSourceAdvice" />
<aop:config>
<aop:advisor pointcut="execution(* com.test..*.service..*.*(..))" advice-ref="dataSourceAdvice" order="10" />
</aop:config>

<tx:advice id="dao.txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" isolation="REPEATABLE_READ" />
<tx:method name="save*" isolation="REPEATABLE_READ" />
<tx:method name="update*" isolation="REPEATABLE_READ" />
<tx:method name="del*" isolation="REPEATABLE_READ" />
<tx:method name="do*" isolation="REPEATABLE_READ" />
<tx:method name="*" isolation="REPEATABLE_READ" read-only="true" />
</tx:attributes>
</tx:advice>

<aop:config proxy-target-class="true">
<aop:advisor pointcut="execution(* com.test..*.service..*.*(..))" advice-ref="dao.txAdvice" order="200" />
</aop:config>
</beans>


配置文件com.test.properties的内容如下

##################################################
###   mysql database settings                 ####
##################################################
com.test.jdbc.driverClass=com.mysql.jdbc.Driver
com.test.jdbc.url=jdbc:mysql://127.0.0.1:3306/licensing?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull
com.test.jdbc.username=root
com.test.jdbc.password=root
com.test.jdbc.pool.init.size=1
com.test.jdbc.pool.max.size=10

##################################################
###   hibernate settings                      ####
##################################################
hibernate.mappingDirectoryLocations=classpath*:hibernate
hibernate.packagesToScan=com.test..*.model.**


配置文件hibernate.properties内容如下:

######################
### Query Language ###
######################

## define query language constants / function names
hibernate.query.substitutions yes 'Y', no 'N'

## select the classic query parser
#hibernate.query.factory_class org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

#################
### Platforms ###
#################

## JNDI Datasource
#hibernate.connection.datasource jdbc/test
#hibernate.connection.username db2
#hibernate.connection.password db2

## HypersonicSQL
#hibernate.dialect org.hibernate.dialect.HSQLDialect
#hibernate.connection.driver_class org.hsqldb.jdbcDriver
#hibernate.connection.username sa
#hibernate.connection.password
#hibernate.connection.url jdbc:hsqldb:./build/db/hsqldb/hibernate
#hibernate.connection.url jdbc:hsqldb:hsql://localhost
#hibernate.connection.url jdbc:hsqldb:test

## H2 (www.h2database.com)
#hibernate.dialect org.hibernate.dialect.H2Dialect
#hibernate.connection.driver_class org.h2.Driver
#hibernate.connection.username sa
#hibernate.connection.password
#hibernate.connection.url jdbc:h2:mem:./build/db/h2/hibernate
#hibernate.connection.url jdbc:h2:testdb/h2test
#hibernate.connection.url jdbc:h2:mem:imdb1
#hibernate.connection.url jdbc:h2:tcp://dbserv:8084/sample;
#hibernate.connection.url jdbc:h2:ssl://secureserv:8085/sample;
#hibernate.connection.url jdbc:h2:ssl://secureserv/testdb;cipher=AES

## MySQL
#hibernate.dialect org.hibernate.dialect.MySQLDialect
hibernate.dialect org.hibernate.dialect.MySQL5InnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password

## Oracle
#hibernate.dialect org.hibernate.dialect.Oracle8iDialect
#hibernate.dialect org.hibernate.dialect.Oracle9iDialect
#hibernate.dialect org.hibernate.dialect.Oracle10gDialect
#hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
#hibernate.connection.username ora
#hibernate.connection.password ora
#hibernate.connection.url jdbc:oracle:thin:@localhost:1521:orcl
#hibernate.connection.url jdbc:oracle:thin:@localhost:1522:XE

## PostgreSQL
#hibernate.dialect org.hibernate.dialect.PostgreSQLDialect
#hibernate.connection.driver_class org.postgresql.Driver
#hibernate.connection.url jdbc:postgresql:template1
#hibernate.connection.username pg
#hibernate.connection.password

## DB2
#hibernate.dialect org.hibernate.dialect.DB2Dialect
#hibernate.connection.driver_class com.ibm.db2.jcc.DB2Driver
#hibernate.connection.driver_class COM.ibm.db2.jdbc.app.DB2Driver
#hibernate.connection.url jdbc:db2://localhost:50000/somename
#hibernate.connection.url jdbc:db2:somename
#hibernate.connection.username db2
#hibernate.connection.password db2

## TimesTen
#hibernate.dialect org.hibernate.dialect.TimesTenDialect
#hibernate.connection.driver_class com.timesten.jdbc.TimesTenDriver
#hibernate.connection.url jdbc:timesten:direct:test
#hibernate.connection.username
#hibernate.connection.password

## DB2/400
#hibernate.dialect org.hibernate.dialect.DB2400Dialect
#hibernate.connection.username user
#hibernate.connection.password password

## Native driver
#hibernate.connection.driver_class COM.ibm.db2.jdbc.app.DB2Driver
#hibernate.connection.url jdbc:db2://systemname

## Toolbox driver
#hibernate.connection.driver_class com.ibm.as400.access.AS400JDBCDriver
#hibernate.connection.url jdbc:as400://systemname

## Derby (not supported!)
#hibernate.dialect org.hibernate.dialect.DerbyDialect
#hibernate.connection.driver_class org.apache.derby.jdbc.EmbeddedDriver
#hibernate.connection.username
#hibernate.connection.password
#hibernate.connection.url jdbc:derby:build/db/derby/hibernate;create=true

## Sybase
#hibernate.dialect org.hibernate.dialect.SybaseDialect
#hibernate.connection.driver_class com.sybase.jdbc2.jdbc.SybDriver
#hibernate.connection.username sa
#hibernate.connection.password sasasa
#hibernate.connection.url jdbc:sybase:Tds:co3061835-a:5000/tempdb

## Mckoi SQL
#hibernate.dialect org.hibernate.dialect.MckoiDialect
#hibernate.connection.driver_class com.mckoi.JDBCDriver
#hibernate.connection.url jdbc:mckoi:///
#hibernate.connection.url jdbc:mckoi:local://C:/mckoi1.0.3/db.conf
#hibernate.connection.username admin
#hibernate.connection.password nimda

## SAP DB
#hibernate.dialect org.hibernate.dialect.SAPDBDialect
#hibernate.connection.driver_class com.sap.dbtech.jdbc.DriverSapDB
#hibernate.connection.url jdbc:sapdb://localhost/TST
#hibernate.connection.username TEST
#hibernate.connection.password TEST
#hibernate.query.substitutions yes 'Y', no 'N'

## MS SQL Server
#hibernate.dialect org.hibernate.dialect.SQLServerDialect
#hibernate.connection.username sa
#hibernate.connection.password sa

## JSQL Driver
#hibernate.connection.driver_class com.jnetdirect.jsql.JSQLDriver
#hibernate.connection.url jdbc:JSQLConnect://1E1/test

## JTURBO Driver
#hibernate.connection.driver_class com.newatlanta.jturbo.driver.Driver
#hibernate.connection.url jdbc:JTurbo://1E1:1433/test

## WebLogic Driver
#hibernate.connection.driver_class weblogic.jdbc.mssqlserver4.Driver
#hibernate.connection.url jdbc:weblogic:mssqlserver4:1E1:1433

## Microsoft Driver (not recommended!)
#hibernate.connection.driver_class com.microsoft.jdbc.sqlserver.SQLServerDriver
#hibernate.connection.url jdbc:microsoft:sqlserver://1E1;DatabaseName=test;SelectMethod=cursor

## The New Microsoft Driver
#hibernate.connection.driver_class com.microsoft.sqlserver.jdbc.SQLServerDriver
#hibernate.connection.url jdbc:sqlserver://localhost

## jTDS (since version 0.9)
#hibernate.connection.driver_class net.sourceforge.jtds.jdbc.Driver
#hibernate.connection.url jdbc:jtds:sqlserver://1E1/test

## Interbase
#hibernate.dialect org.hibernate.dialect.InterbaseDialect
#hibernate.connection.username sysdba
#hibernate.connection.password masterkey

## DO NOT specify hibernate.connection.sqlDialect

## InterClient
#hibernate.connection.driver_class interbase.interclient.Driver
#hibernate.connection.url jdbc:interbase://localhost:3060/C:/firebird/test.gdb

## Pure Java
#hibernate.connection.driver_class org.firebirdsql.jdbc.FBDriver
#hibernate.connection.url jdbc:firebirdsql:localhost/3050:/firebird/test.gdb

## Pointbase
#hibernate.dialect org.hibernate.dialect.PointbaseDialect
#hibernate.connection.driver_class com.pointbase.jdbc.jdbcUniversalDriver
#hibernate.connection.url jdbc:pointbase:embedded:sample
#hibernate.connection.username PBPUBLIC
#hibernate.connection.password PBPUBLIC

## Ingres
## older versions (before Ingress 2006)
#hibernate.dialect org.hibernate.dialect.IngresDialect
#hibernate.connection.driver_class ca.edbc.jdbc.EdbcDriver
#hibernate.connection.url jdbc:edbc://localhost:II7/database
#hibernate.connection.username user
#hibernate.connection.password password

## Ingres 2006 or later
#hibernate.dialect org.hibernate.dialect.IngresDialect
#hibernate.connection.driver_class com.ingres.jdbc.IngresDriver
#hibernate.connection.url jdbc:ingres://localhost:II7/database;CURSOR=READONLY;auto=multi
#hibernate.connection.username user
#hibernate.connection.password password

## Mimer SQL
#hibernate.dialect org.hibernate.dialect.MimerSQLDialect
#hibernate.connection.driver_class com.mimer.jdbc.Driver
#hibernate.connection.url jdbc:mimer:multi1
#hibernate.connection.username hibernate
#hibernate.connection.password hibernate

## InterSystems Cache
#hibernate.dialect org.hibernate.dialect.Cache71Dialect
#hibernate.connection.driver_class com.intersys.jdbc.CacheDriver
#hibernate.connection.username _SYSTEM
#hibernate.connection.password SYS
#hibernate.connection.url jdbc:Cache://127.0.0.1:1972/HIBERNATE

#################################
### Hibernate Connection Pool ###
#################################

#hibernate.connection.pool_size 1

###########################
### C3P0 Connection Pool###
###########################

#hibernate.c3p0.max_size 2
#hibernate.c3p0.min_size 2
#hibernate.c3p0.timeout 5000
#hibernate.c3p0.max_statements 100
#hibernate.c3p0.idle_test_period 3000
#hibernate.c3p0.acquire_increment 2
#hibernate.c3p0.validate false

##############################
### Proxool Connection Pool###
##############################

## Properties for external configuration of Proxool
#hibernate.proxool.pool_alias pool1

## Only need one of the following
#hibernate.proxool.existing_pool true
#hibernate.proxool.xml proxool.xml
#hibernate.proxool.properties proxool.properties

#################################
### Plugin ConnectionProvider ###
#################################

## use a custom ConnectionProvider (if not set, Hibernate will choose a built-in ConnectionProvider using hueristics)
#hibernate.connection.provider_class org.hibernate.connection.DriverManagerConnectionProvider
#hibernate.connection.provider_class org.hibernate.connection.DatasourceConnectionProvider
#hibernate.connection.provider_class org.hibernate.connection.C3P0ConnectionProvider
#hibernate.connection.provider_class org.hibernate.connection.ProxoolConnectionProvider
#hibernate.connection.provider_class com.iisu.tenancy.ConnectionProviderImpl

#######################
### Transaction API ###
#######################

## Enable automatic flush during the JTA beforeCompletion() callback
## (This setting is relevant with or without the Transaction API)
#hibernate.transaction.flush_before_completion

## Enable automatic session close at the end of transaction
## (This setting is relevant with or without the Transaction API)
#hibernate.transaction.auto_close_session

## the Transaction API abstracts application code from the underlying JTA or JDBC transactions
#hibernate.transaction.factory_class org.hibernate.transaction.JTATransactionFactory
#hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory

## to use JTATransactionFactory, Hibernate must be able to locate the UserTransaction in JNDI
## default is java:comp/UserTransaction
## you do NOT need this setting if you specify hibernate.transaction.manager_lookup_class

#jta.UserTransaction jta/usertransaction
#jta.UserTransaction javax.transaction.UserTransaction
#jta.UserTransaction UserTransaction

## to use the second-level cache with JTA, Hibernate must be able to obtain the JTA TransactionManager
#hibernate.transaction.manager_lookup_class org.hibernate.transaction.JBossTransactionManagerLookup
#hibernate.transaction.manager_lookup_class org.hibernate.transaction.WeblogicTransactionManagerLookup
#hibernate.transaction.manager_lookup_class org.hibernate.transaction.WebSphereTransactionManagerLookup
#hibernate.transaction.manager_lookup_class org.hibernate.transaction.OrionTransactionManagerLookup
#hibernate.transaction.manager_lookup_class org.hibernate.transaction.ResinTransactionManagerLookup

##############################
### Miscellaneous Settings ###
##############################

## print all generated SQL to the console
hibernate.show_sql true

## format SQL in log and console
hibernate.format_sql false

## add comments to the generated SQL
#hibernate.use_sql_comments true

## generate statistics
hibernate.generate_statistics false

## auto schema export
#hibernate.hbm2ddl.auto create-drop
#hibernate.hbm2ddl.auto create
hibernate.hbm2ddl.auto update
#hibernate.hbm2ddl.auto validate

## specify a default schema and catalog for unqualified tablenames
#hibernate.default_schema test
#hibernate.default_catalog test

## enable ordering of SQL UPDATEs by primary key
#hibernate.order_updates true

## set the maximum depth of the outer join fetch tree
hibernate.max_fetch_depth 1

## set the default batch size for batch fetching
hibernate.default_batch_fetch_size 32

## rollback generated identifier values of deleted entities to default values
#hibernate.use_identifer_rollback true

## enable bytecode reflection optimizer (disabled by default)
#hibernate.bytecode.use_reflection_optimizer true

#####################
### JDBC Settings ###
#####################

## specify a JDBC isolation level
hibernate.connection.isolation 2

## enable JDBC autocommit (not recommended!)
hibernate.connection.autocommit false

## set the JDBC fetch size
hibernate.jdbc.fetch_size 25

## set the maximum JDBC 2 batch size (a nonzero value enables batching)
hibernate.jdbc.batch_size 5

## enable batch updates even for versioned data
hibernate.jdbc.batch_versioned_data false

## enable use of JDBC 2 scrollable ResultSets (specifying a Dialect will cause Hibernate to use a sensible default)
hibernate.jdbc.use_scrollable_resultset true

## use streams when writing binary types to / from JDBC
hibernate.jdbc.use_streams_for_binary true

## use JDBC 3 PreparedStatement.getGeneratedKeys() to get the identifier of an inserted row
#hibernate.jdbc.use_get_generated_keys false

## choose a custom JDBC batcher
# hibernate.jdbc.factory_class

## enable JDBC result set column alias caching
## (minor performance enhancement for broken JDBC drivers)
# hibernate.jdbc.wrap_result_sets

## choose a custom SQL exception converter
#hibernate.jdbc.sql_exception_converter

##########################
### Second-level Cache ###
##########################

## optimize chache for minimal "puts" instead of minimal "gets" (good for clustered cache)
#hibernate.cache.use_minimal_puts true

## set a prefix for cache region names
hibernate.cache.region_prefix com.test.apps

## disable the second-level cache
hibernate.cache.use_second_level_cache true

## enable the query cache
hibernate.cache.use_query_cache true

## store the second-level cache entries in a more human-friendly format
hibernate.cache.use_structured_entries false

## choose a cache implementation
#hibernate.cache.region.factory_class org.hibernate.cache.infinispan.InfinispanRegionFactory
#hibernate.cache.region.factory_class org.hibernate.cache.infinispan.JndiInfinispanRegionFactory
hibernate.cache.region.factory_class org.hibernate.cache.ehcache.EhCacheRegionFactory
#hibernate.cache.region.factory_class org.hibernate.cache.internal.SingletonEhCacheRegionFactory
#hibernate.cache.region.factory_class org.hibernate.cache.internal.NoCachingRegionFactory

## choose a custom query cache implementation
#hibernate.cache.query_cache_factory

############
### JNDI ###
############

## specify a JNDI name for the SessionFactory
#hibernate.session_factory_name hibernate/session_factory

## Hibernate uses JNDI to bind a name to a SessionFactory and to look up the JTA UserTransaction;
## if hibernate.jndi.* are not specified, Hibernate will use the default InitialContext() which
## is the best approach in an application server

#file system
#hibernate.jndi.class com.sun.jndi.fscontext.RefFSContextFactory
#hibernate.jndi.url file:/

#WebSphere
#hibernate.jndi.class com.ibm.websphere.naming.WsnInitialContextFactory
#hibernate.jndi.url iiop://localhost:900/


2.spring mvc配置文件

<?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"
xmlns:util="http://www.springframework.org/schema/util" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" default-autowire="no" default-lazy-init="false">

<context:property-placeholder location="classpath*:com.test.properties" />
<context:annotation-config />
<!-- 自动扫描的包名 -->
<context:component-scan base-package="com.test.*.controller" />
<context:component-scan base-package="com.test.**.controller" />
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven/>

<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources/ directory -->
<!-- 对静态资源文件的访问 -->
<mvc:resources mapping="/resource/**" location="/resource/" />
<mvc:resources mapping="/static/**" location="/static/" />
<!-- theme -->
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
<property name="paramName" value="theme"></property>
</bean>
<!-- View resolvers can also be configured with ResourceBundles or XML files.
If you need different view resolving based on Locale, you have to use the
resource bundle resolver. -->
<!-- 视图解释类 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- Saves a locale change using a cookie -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

<!-- Application Message Bundle -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:/messages/message-info" />
<property name="cacheSeconds" value="0" />
</bean>

<!-- 映射所有没有在controller中配置的path,对应到 jsp 目录中 -->
<mvc:view-controller path="/**" />

<!-- this bean with the well known name generates view names for us -->
<bean id="viewNameTranslator"
class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator">

</bean>

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>209715200</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>

</beans>


3.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd" version="2.5">
<display-name>licensing</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com.test.context.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 设置编码 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>path-servlet</servlet-name>
<servlet-class>com.test.common.PathServlet</servlet-class>
<load-on-startup>10</load-on-startup>
</servlet>

<!-- 登录过滤 -->
<filter>
<filter-name>LocalLoginFilter</filter-name>
<filter-class>com.test.filter.LocalLoginFilter</filter-class>
<init-param>
<param-name>excludes</param-name>
<param-value>/static/*,/resource/*</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>LocalLoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>LocalLoginFilter</filter-name>
<url-pattern>/intent/*</url-pattern>
</filter-mapping>

<!-- spring-mvc配置 -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>*.list</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>*.dlg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>

<!-- sitemesh -->
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 错误页配置 -->
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/error/404.jsp</location>
</error-page>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>


4.日志配置文件logbakc-test.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<configuration scan="true" scanPeriod="30 seconds">

<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ssS} %5p [%c]:%L-%m%n</pattern>
</encoder>
</appender>

<logger name="com.test" level="debug" additivity="true"/>
<root level="info">
<appender-ref ref="stdout" />
</root>

</configuration>


进行以上操作后,配置已经完成,下面创建controller进行测试,在src/main/java包下,com/test目录下创建controller包,在该包下创建IndexController.java,代码如下:

package com.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

@RequestMapping("/")
@ResponseBody
public String index(){
return "hello";
}

}


三、运行项目

选中项目->右键->debug as->Maven build…,在弹出的窗口内Goals输入框内输入”tomcat:run”,选中“source”tag->add…->workspacce->ok->debug

系统开始启动,初次启动会下载较多的依赖包会很慢,当项目正式启动后,访问localhost:8888会在浏览器内看到“hello”的返回内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: