maven+spring mvc+junit+msql+国际化的简单代码案例

注:此案例已经测试通过,方便自己以后查阅

damo整体结构如图:

maven+spring mvc+junit+msql+国际化的简单代码案例_第1张图片

一、搭建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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.self</groupId>
  <artifactId>_meven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>mymaven</name>
  <url>http://maven.apache.org</url>
  
  <properties>
        <!-- spring版本号 -->
        <spring.version>3.2.4.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.2.4</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.9</log4j.version>
        <!-- 设置编码字符集 -->
        <project.build.sourceEncoding>
            UTF-8
        </project.build.sourceEncoding>
    </properties>
    
   
  
  <dependencies>
        
     <!-- spring核心包 -->
        <!-- springframe start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- springframe end -->
 
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <!-- junit测试包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- 阿里巴巴数据源包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.2</version>
        </dependency>
 
        <!-- json数据 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
 
        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        <!--  -->
        <!-- <dependency>
          <groupId>org.eclipse.jetty.orbit</groupId>
          <artifactId>javax.servlet</artifactId>
          <version>2.5.0.v201103041518</version>
        </dependency> -->
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>servlet-api</artifactId>
         <version>2.4</version>
         <scope>provided</scope>
        </dependency> 
        <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        </dependency>
        <dependency>
          <groupId>taglibs</groupId>
          <artifactId>standard</artifactId>
          <version>1.1.2</version>
        </dependency>
        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.4</version>
        </dependency>
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.2.2</version>
        </dependency>
  </dependencies>
  <!--  <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-war-plugin</artifactId>
         <version>2.1.1</version> 
         <configuration> 
           http://maven.apache.org/plugins/maven-war-plugin/
            <packagingExcludes>WEB-INF/web.xml</packagingExcludes>
         </configuration>
    </plugin> -->
    <repositories>
		<repository>
			<id>central</id>
			<name>Central Repository</name>
			<url>http://repo.maven.apache.org/maven2</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>repo.springsource.org</id>
			<name>repo.springsource.org-releases</name>
			<url>http://repo.springsource.org/libs-milestone-local</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spy</id>
			<name>Spy Repository</name>
			<url>http://files.couchbase.com/maven2/</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
	
	<build>
	<plugins>
             <plugin> 
              <groupId>org.codehaus.mojo</groupId> 
              <artifactId>sonar-maven-plugin</artifactId> 
              <version>2.4</version> 
             </plugin> 

			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0</version>
				<configuration>
					<port>80</port>
					<path>/</path>
				</configuration>
			</plugin>
			<!-- <plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<webResources>
						<resource>
							<directory>src/main/resources/${package.environment}/WEB-INF</directory>
							<targetPath>WEB-INF</targetPath>
						</resource>
						<resource>
							<directory>src/main/resources/${package.environment}/global</directory>
							<targetPath>WEB-INF/common</targetPath>
						</resource>
					</webResources>
				</configuration>
			</plugin> -->
			<plugin>
				<!-- YUI Compressor Maven压缩插件 -->
				<groupId>net.alchim31.maven</groupId>
				<artifactId>yuicompressor-maven-plugin</artifactId>
				<version>1.3.0</version>
				<configuration>
					<!-- 读取js,css文件采用UTF-8编码 -->
					<encoding>UTF-8</encoding>
					<!-- 不显示js可能的错误 -->
					<jswarn>false</jswarn>
					<!-- 若存在已压缩的文件,会先对比源文件是否有改动。有改动便压缩,无改动就不压缩 -->
					<force>false</force>
					<!-- 在指定的列号后插入新行 -->
					<linebreakpos>-1</linebreakpos>
					<!-- 压缩之前先执行聚合文件操作 -->
					<preProcessAggregates>true</preProcessAggregates>
					<!-- 压缩后保存文件后缀 -->
					<suffix>.min</suffix>
					<!-- 源目录,即需压缩的根目录 -->
					<sourceDirectory>src/main/webapp/static</sourceDirectory>
					<!-- 压缩js和css文件 -->
					<includes>
						<include>**/*.js</include>
						<include>**/*.css</include>
					</includes>
					<!-- 以下目录和文件不会被压缩 -->
			<!--		<excludes>
						<exclude>**/*.min.js</exclude>
						<exclude>**/*.min.css</exclude>
						<exclude>**/plugin/**</exclude>
						<exclude>**/ueditor_1.2.6/**</exclude>
						<exclude>**/color/**</exclude>
					</excludes> --!>
					<!-- 压缩后输出文件目录 -->
					<outputDirectory>src/main/webapp/static</outputDirectory>
				</configuration>
			</plugin>
		</plugins>
		<!-- build标签解决了mapper.xml文件打包打不进去的问题  begin -->
	
		<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
		<outputDirectory>${basedir}/target/classes</outputDirectory>
		<testOutputDirectory>${basedir}/target/test-classes</testOutputDirectory>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
			</resource>
		</resources>
	<!-- build标签解决了mapper.xml文件打包打不进去的问题 end -->
	</build>
</project>

二、配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Archetype Created Web Application</display-name>
 
    <!-- 读取spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:jdbc-properties/spring.xml;
            classpath:jdbc-properties/spring-mabatis.xml
        </param-value>
    </context-param>
<!--     设计路径变量值
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc.root</param-value>
    </context-param>
  -->
   
    <!-- Spring字符集过滤器 -->
    <filter>
        <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
    <!-- 日志记录 -->
    <context-param>
        <!-- 日志配置文件路径 -->
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:conf/log4j.properties</param-value>
    </context-param>
    <context-param>
       <!--  日志页面的刷新间隔 -->
        <param-name>log4jRefreshInterval</param-name>
        <param-value>6000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- springMVC核心配置 -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:conf/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
    <!-- 错误跳转页面 -->
   <!--  <error-page>
        路径不正确
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
    <error-page>
        没有访问权限,访问被禁止
        <error-code>405</error-code>
        <location>/WEB-INF/errorpage/405.jsp</location>
    </error-page>
    <error-page>
        内部错误
        <error-code>500</error-code>
        <location>/WEB-INF/errorpage/500.jsp</location>
    </error-page> -->
    
    
</web-app>

三、下面就开始配置web.xml里面所引用到的各个配置文件

(1)spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 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.xsd">
 
   <!-- 引入jdbc配置文件 -->
    <context:property-placeholder location="classpath:jdbc-properties/jdbc-source.properties"/> 
    <!-- 扫描文件(自动将service层注入) -->
   <!--  <context:component-scan base-package="cn.mymaven.mytest.service"/> -->
   
</beans>

(2)jdbc-source.properties:spring.xml中引用的数据库相关信息的配置文件

jdbc_dirver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://192.168.**.**:3306/table_name
jdbc_username=root
jdbc_password=password


(3)spring-mybatis:配置数据源相关信息

<?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:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">
 
 
 
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    destroy-method="close" >
    <property name="driverClassName"><value>${jdbc_dirver}</value></property>
    <property name="url"><value>${jdbc_url}</value></property>
    <property name="username"><value>${jdbc_username}</value></property>
    <property name="password"><value>${jdbc_password}</value></property>
    <!-- 连接池最大使用连接数 -->
    <property name="maxActive"><value>20</value></property>
    <!-- 初始化连接大小 -->
    <property name="initialSize"><value>1</value></property>
    <!-- 获取连接最大等待时间 -->
    <property name="maxWait"><value>60000</value></property>
    <!-- 连接池最大空闲 -->
    <property name="maxIdle"><value>20</value></property>
    <!-- 连接池最小空闲 -->
    <property name="minIdle"><value>3</value></property>
    <!-- 自动清除无用连接 -->
    <property name="removeAbandoned"><value>true</value></property>
    <!-- 清除无用连接的等待时间 -->
    <property name="removeAbandonedTimeout"><value>180</value></property>
    <!-- 连接属性 -->
    <property name="connectionProperties"><value>clientEncoding=UTF-8</value></property>
    </bean>
     
    <!-- mybatis文件配置,扫描所有mapper文件 -->
      <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:mapperLocations="classpath*:cn/mymaven/mytest/mapper/*.xml"/>
        
   <!-- spring与mybatis整合配置,扫描所有dao -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="cn.mymaven.mytest.dao"
        p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
  
   <!-- 对数据源进行事务管理 -->
  <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource"/>
</beans>

(4)log4j.properties:日志配置文件

### set log levels ###
#log4j.rootLogger = debug , stdout , D , E
log4j.rootLogger = debug , stdout , D
 
###  output to the console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
 
### Output to the log file ###
#log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.log
#log4j.appender.D.Append = true
#log4j.appender.D.Threshold = DEBUG 
#log4j.appender.D.layout = org.apache.log4j.PatternLayout
#log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
 
### Save exception information to separate file ###
#log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/error.log 
#log4j.appender.D.Append = true
#log4j.appender.D.Threshold = ERROR 
#log4j.appender.D.layout = org.apache.log4j.PatternLayout
#log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 



(5)spring-mvc.xml:springmvc的核心配置,配置了对包的扫描以及视图配置,在这里我添加了上篇博客的国际化配置。

<?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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		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">

	<!-- annotation的方法映射适配器 <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> -->
	<!-- annotation默认的方法映射适配器 <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" 
		/> -->


	<mvc:default-servlet-handler />
	<context:component-scan base-package="cn.mymaven.mytest" />
	<context:annotation-config />
	<mvc:annotation-driven />

	<!-- 2015.04.20 -->
	<!-- 上传文件配置 -->
	<!-- <bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="100000" />
		<property name="maxInMemorySize" value="10240" />
	</bean> -->
	<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<!-- <property name="order" value="1" /> <property name="mediaTypes"> <map> 
			<entry key="json" value="application/json" /> <entry key="html" value="text/html" 
			/> </map> </property> -->
		<property name="viewResolvers">
			<list>
				<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
				<bean
					class="org.springframework.web.servlet.view.InternalResourceViewResolver">
					<property name="viewClass"
						value="org.springframework.web.servlet.view.JstlView" />
					<property name="prefix" value="/WEB-INF/view/" />
					<property name="suffix" value=".jsp" />
				</bean>
			</list>
		</property>
		<property name="defaultViews">
			<list>
				<bean
					class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>
	<!-- 添加国际化配置 -->
	<mvc:interceptors>        <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
		<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
	</mvc:interceptors><!-- Saves a locale change using a session -->
	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
		<!--国际化文件 -->
	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="/WEB-INF/language" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
</beans>





 四、配置文件完毕就可以在controller,service,dao,mapper,model中再添加java代码了

 注:初次搭建 如有不妥请多指正,谢谢

你可能感兴趣的:(spring,maven,mvc,JUnit,msql)