Spring MVC+Maven+Freemarker+Mybatis开发环境搭建

利用STS(Spring Tool Suite)开发工具可以很方便的创建一个基于Maven的Spring MVC工程项目。然后再分别集成Freemarker以及Mybatis。
STS官网下载地址:点此下载Spring Tool Suite 运行STS后,
设置下工作空间的默认编码方式为UTF-8,Window->Preferences->General->Workspace。
配置下JRE,选择你自己安装的JDK(如1.8的版本),Window->Preferences->Java->Installed JREs 。
配置Maven本地仓库位置,默认是C盘路径,Window->Preferences->Maven->User Settings,可以自己安装个Maven,若嫌麻烦则默认用STS自带的即可不用配置。

1.创建一个Spring MVC项目

File->New->Spring Legacy Project,弹出向导后输入项目名称并选择Spring MVC Project,然后Next,
输入包名,Finish。第一次创建会提示下载模板文件,点下载即可,创建好的工程目录如下:
Spring MVC+Maven+Freemarker+Mybatis开发环境搭建_第1张图片
运行项目Run as -> Run on Server ,可以用Tomcat 作为服务器,自己自行配置。如果项目有错误,请检查Build Path 以及pom.xml中的jar包是否在maven本地仓库中下载好了。
运行成功后,会打印出Hello world 以及服务器的时间,时间若是乱码,在jsp中 加上charset=utf-8即可。

2.集成Freemarker

表现层技术主要有三种:jsp、freemarker、velocity。
其实集成Freemarker是可选的,jsp就很好了。三者优缺点都有,看个人喜好吧。
1)在pom.xml中添加Freemarker 依赖:

        
        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.23version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
        dependency>

2)找到servlet-context.xml,添加Freemarker的配置
为了看起来更简洁,beans和mvc的命名空间前缀调换了下,自己可以对照着更改。
文件在最后列出来了,在此不重复列出

Freemarker配置中的视图后缀可以是任意的,默认的是.ftl .
如果要配置多个视图解析器,如同时配置jsp和Freemarker,那么Freemarker的优先级要设置的比jsp的高,通过order来设置。
很简单,就这两步,配置完后,运行成功则表示Freemarker配置成功。

3.集成Mybatis

实体映射框架可能会选择Hibernate,个人觉得Hibernate难学点,特别是那些对应关系。而Mybatis是半自动映射框架,灵活性高,学起来也简单。
1)依赖jar

 
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.2.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.2.2version>
        dependency>  
        
        <dependency>
            <groupId>net.sourceforge.jtdsgroupId>
            <artifactId>jtdsartifactId>
            <version>1.3.1version>
        dependency>
        
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-jdbcartifactId>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-txartifactId>  
        dependency>  
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>${org.aspectj-version}version>
        dependency>
          
        <dependency>  
            <groupId>commons-dbcpgroupId>  
            <artifactId>commons-dbcpartifactId>  
            <version>1.4version>  
        dependency>

驱动是Sqlserver的,自己可以替换成其他的
2)jdbc.properties

hibernate.dialect=org.hibernate.dialect.SQLServerDialect
driverClassName=net.sourceforge.jtds.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/PTMPDB
jdbc_password=12345
jdbc_username=part_user

3)spring-mybatis.xml
文件在后面列举出来了,在此不重复列举

4)最后别忘了将spring-mytabis.xml 让spring容器加载进去,在web.xml中加入:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml,classpath:spring-mybatis.xml</param-value>
    </context-param>

至此配置已经完成了,最后还得测试下是否集成成功。

4.Mybatis自动生成工具

可以根据数据库表自动生成dao、mapping、entity。Mybatis实体映射自动生成工具下载
运行项目,看是否能成功连接数据库并且能查出数据以验证是否配置成功。
Spring MVC+Maven+Freemarker+Mybatis开发环境搭建_第2张图片
1)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.0modelVersion>
    <groupId>com.jykjgroupId>
    <artifactId>demoartifactId>
    <name>Demoname>
    <packaging>warpackaging>
    <version>1.0.0-BUILD-SNAPSHOTversion>
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <java-version>1.6java-version>
        <org.springframework-version>4.1.2.RELEASEorg.springframework-version>
        <org.aspectj-version>1.6.10org.aspectj-version>
        <org.slf4j-version>1.6.6org.slf4j-version>
    properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-framework-bomartifactId>
                <version>${org.springframework-version}version>

                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>
    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <exclusions>
                
                <exclusion>
                    <groupId>commons-logginggroupId>
                    <artifactId>commons-loggingartifactId>
                 exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
        dependency>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjrtartifactId>
            <version>${org.aspectj-version}version>
        dependency>   

        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>${org.slf4j-version}version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>jcl-over-slf4jartifactId>
            <version>${org.slf4j-version}version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>${org.slf4j-version}version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.15version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mailgroupId>
                    <artifactId>mailartifactId>
                exclusion>
                <exclusion>
                    <groupId>javax.jmsgroupId>
                    <artifactId>jmsartifactId>
                exclusion>
                <exclusion>
                    <groupId>com.sun.jdmkgroupId>
                    <artifactId>jmxtoolsartifactId>
                exclusion>
                <exclusion>
                    <groupId>com.sun.jmxgroupId>
                    <artifactId>jmxriartifactId>
                exclusion>
            exclusions>
            <scope>runtimescope>
        dependency>

        
        <dependency>
            <groupId>javax.injectgroupId>
            <artifactId>javax.injectartifactId>
            <version>1version>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.1version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.7version>
            <scope>testscope>
        dependency>  
        
        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.23version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
        dependency>
         
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.2.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.2.2version>
        dependency>  
        
        <dependency>
            <groupId>net.sourceforge.jtdsgroupId>
            <artifactId>jtdsartifactId>
            <version>1.3.1version>
        dependency>
        
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-jdbcartifactId>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-txartifactId>  
        dependency>  
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>${org.aspectj-version}version>
        dependency>
          
        <dependency>  
            <groupId>commons-dbcpgroupId>  
            <artifactId>commons-dbcpartifactId>  
            <version>1.4version>  
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-pluginartifactId>
                <version>2.9version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnatureprojectnature>
                    additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilderbuildcommand>
                    additionalBuildcommands>
                    <downloadSources>truedownloadSources>
                    <downloadJavadocs>truedownloadJavadocs>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>2.5.1version>
                <configuration>
                    <source>1.6source>
                    <target>1.6target>
                    <compilerArgument>-Xlint:allcompilerArgument>
                    <showWarnings>trueshowWarnings>
                    <showDeprecation>trueshowDeprecation>
                configuration>
            plugin>
            <plugin>
                <groupId>org.codehaus.mojogroupId>
                <artifactId>exec-maven-pluginartifactId>
                <version>1.2.1version>
                <configuration>
                    <mainClass>org.test.int1.MainmainClass>
                configuration>
            plugin>
        plugins>
    build>
project>

2)web.xml


<web-app version="2.5" 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">

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/spring/root-context.xml,classpath:spring-mybatis.xmlparam-value>
    context-param>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>appServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    <servlet-mapping>
        <servlet-name>appServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
         <init-param>
              <param-name>forceEncodingparam-name>
              <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>


    
    <context-param>
      <param-name>log4jConfigLocationparam-name>
      <param-value>classpath:log4j.xmlparam-value>
    context-param>
    <listener>
      <listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
    listener>


web-app>

3)servlet-context.xml


<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">

    

    
    <mvc:annotation-driven />

    
    <mvc:resources mapping="/resources/**" location="/resources/" />

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="2" />
    bean>
      
    <bean id="freemarkerConfigurer"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="/WEB-INF/views/" />  
        <property name="defaultEncoding" value="utf-8" />  
        <property name="freemarkerSettings">  
            <props>  
                <prop key="template_update_delay">5prop>
                <prop key="default_encoding">UTF-8prop>
               
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ssprop>
                <prop key="time_format">HH:mm:ssprop>
                <prop key="number_format">0.####prop>
                <prop key="boolean_format">true,falseprop>
                <prop key="whitespace_stripping">trueprop>
                <prop key="tag_syntax">auto_detectprop>
                <prop key="url_escaping_charset">UTF-8prop>
            props>  
        property>  
    bean> 
      
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="order" value="1" />
        <property name="cache" value="true" />
        <property name="prefix" value="" />
        <property name="suffix" value=".ftl" />
        <property name="contentType" value="text/html;charset=UTF-8">property>
        <property name="requestContextAttribute" value="request" />
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
    bean>
    
    <context:component-scan base-package="com.jykj.demo.controller" />
    
    <context:component-scan base-package="com.jykj.demo.service" />
beans>

4)spring-mybatis.xml


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

    
      
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    bean>  
    
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
         destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        
        <property name="initialSize" value="0" />
        
        <property name="maxActive" value="20" />
        
        <property name="minIdle" value="0" />
        
        <property name="maxWait" value="60000" />

        <property name="poolPreparedStatements" value="true" /> 
        

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <property name="minEvictableIdleTimeMillis" value="25200000" />

        
        <property name="removeAbandoned" value="true" />
        
        <property name="removeAbandonedTimeout" value="1800" />
        
        <property name="logAbandoned" value="true" />

        
        
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations" value="classpath:com/jykj/demo/mapping/*.xml" />
        <property name="typeAliasesPackage" value="com.jykj.demo.entity" />
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jykj.demo.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    bean>

    
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>

    
    

    
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="append*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="insert*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="save*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="modify*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="edit*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="delete*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="remove*" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="repair" propagation="REQUIRED"
                rollback-for="Exception" />
            <tx:method name="delAndRepair" propagation="REQUIRED"
                rollback-for="Exception" />

            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="search*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="datagrid*" propagation="SUPPORTS"
                read-only="true" />

            <tx:method name="*" propagation="SUPPORTS" rollback-for="Exception" />
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.jykj.demo.service.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="transactionAdvice" />
    aop:config>
beans>

总的来说,集成的话就是spring的配置。如果集成出现问题,请不要灰心,找出原因,多半是pom.xml中的jar包没有成功下载下来,这样的话需要手动下载后放到maven本地仓库中。
也可以参考其他人的博客:
参考链接一
参考链接二
参考链接三
Mybatis实体映射自动生成工具下载

你可能感兴趣的:(框架)