《自己动手写云盘》- 搭建SpringMVC + Spring + Mybatis + Velocity的Web环境

人个主页链接:http://www.tongtongxue.com/archives/4849.html

这一节主要是利用SpringMVC、Spring、MybatisVelocity,首先将其整合在一起,搭建Web开发的环境,以下会列出核心代码。

    pom.xml

    由于本工程是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.tongtongxue</groupId>
  <artifactId>ttx-yp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ttx-yp Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>3.2.4.RELEASE</spring.version>
  </properties>

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

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>


    <!--spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </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-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.5</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>

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

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>

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

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

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>1.7</version>
    </dependency>
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity-tools</artifactId>
      <version>2.0</version>
      <exclusions>
          <exclusion>
              <artifactId>struts-core</artifactId>
              <groupId>org.apache.struts</groupId>
          </exclusion>
          <exclusion>
              <artifactId>struts-tiles</artifactId>
              <groupId>org.apache.struts</groupId>
          </exclusion>
          <exclusion>
              <artifactId>struts-taglib</artifactId>
              <groupId>org.apache.struts</groupId>
          </exclusion>
          <exclusion>
              <artifactId>commons-chain</artifactId>
              <groupId>commons-chain</groupId>
          </exclusion>
          <exclusion>
              <artifactId>commons-validator</artifactId>
              <groupId>commons-validator</groupId>
          </exclusion>
          <exclusion>
              <artifactId>sslext</artifactId>
              <groupId>sslext</groupId>
          </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>

    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>3.2.0</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>ttx-yp</finalName>
  </build>
</project>

    spring-servlet.xml

    该配置主要是配置视图及跟Web相关的,如下:

<?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.1.xsd 
           http://www.springframework.org/schema/mvc 
           http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.1.xsd"
    default-lazy-init="true">

    <!-- 启用spring mvc 注解 -->
    <context:annotation-config />

	<!-- 自动扫描与装配bean -->
    <context:component-scan base-package="com.tongtongxue.yp.*.controller">
    </context:component-scan>

    <mvc:annotation-driven/>

    <!-- 映射静态资源 -->
    <mvc:resources mapping="/resources/**" location="/resources/"/>

    <!-- 模板信息设置 -->
    <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
       <property name="resourceLoaderPath"  value="WEB-INF/template"/> <!-- 設置模板放置位置-->
       <property name="velocityProperties">
           <props>
               <prop key="directive.foreach.counter.name">loopCounter</prop>
               <prop key="directive.foreach.counter.initial.value">0</prop>
               <prop key="input.encoding">UTF-8</prop> <!-- 指定模板引擎进行模板处理的编码 -->
               <prop key="output.encoding">UTF-8</prop> <!-- 指定输出流的编码 -->
           </props>
       </property>
   </bean>

    <!-- 设置视图解析工具 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
        <property name="suffix" value=".vm"/>
        <!-- 避免乱码 -->
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="requestContextAttribute" value="rc"/>
        <property name="exposeRequestAttributes" value="true"/>
        <property name="exposeSessionAttributes" value="true"/>
        <property name="viewClass" value="com.tongtongxue.yp.common.web.Toolbox20View"/>
        <property name="toolboxConfigLocation" value="WEB-INF/conf/tools.xml" />
   </bean>  
</beans>

    spring-beans.xml

    该配置中主要配置数据库、事务及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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
    default-lazy-init="true">

    <!-- 自动扫描与装配bean -->
    <context:component-scan base-package="com.tongtongxue.yp">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 数据源连接配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 数据源配置 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <property name="maxWait" value="${jdbc.maxWait}" />
    </bean>

    <!-- spring和mybatis整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.tongtongxue.yp.common.model"/>
        <property name="mapperLocations" value="classpath:com/tongtongxue/yp/common/model/*Mapper.xml" />
    </bean>

    <!-- 扫描basePackage下所有以@Repository标识的 接口进行自动生成代理的Dao -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.tongtongxue.yp"/>
        <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    </bean>

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

    <!-- 注解式事务管理,需要在Service类上标注@Transactional -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

   web.xml

    配置Web容器相关,如下:

<?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>yp</display-name>

    <distributable/>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>yp.root</param-value>
    </context-param>

    <!--Encoding filter-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--contextConfigLocation -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-beans.xml</param-value>
    </context-param>

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

    <!--mvc-->
    <servlet>
        <servlet-name>yp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:spring-servlet.xml</param-value>  
        </init-param> 
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>yp</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--<error-page>-->
    <!--<error-code>404</error-code>-->
    <!--<location>/index.jsp</location>-->
    <!--</error-page>-->

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

   Toolbox20View

     为了使用原生的Spring派发的同时,有支持Velocity Tools 2.0,必须引入的对象,如下:

package com.tongtongxue.yp.common.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.servlet.view.velocity.VelocityToolboxView;

/**
 * 实现了Velocity Tools 2.0的装载
 * @author 芝加哥
 * @since [2017-01-08]
 */
public class Toolbox20View extends VelocityToolboxView {
    private static ToolboxFactory toolboxFactory = null;

    @Override
    protected Context createVelocityContext(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ViewToolContext vtc;
        vtc = new ViewToolContext(getVelocityEngine(), request, response, getServletContext());
        vtc.putAll(model);

        if (toolboxFactory == null) {
            ToolManager toolManager = new ToolManager();
            toolManager.setVelocityEngine(getVelocityEngine());
            toolManager.configure(getServletContext().getRealPath(getToolboxConfigLocation()));
            toolboxFactory = toolManager.getToolboxFactory();
        }

        if (this.getToolboxConfigLocation() != null) {

            if (toolboxFactory.hasTools(Scope.REQUEST)) {
                vtc.addToolbox(toolboxFactory.createToolbox(Scope.REQUEST));
            }
            if (toolboxFactory.hasTools(Scope.APPLICATION)) {
                vtc.addToolbox(toolboxFactory.createToolbox(Scope.APPLICATION));
            }
            if (toolboxFactory.hasTools(Scope.SESSION)) {
                vtc.addToolbox(toolboxFactory.createToolbox(Scope.SESSION));
            }
        }
        return vtc;
    }
}

   AuthController

    用户登录信息的控制器类,如下:

package com.tongtongxue.yp.auth.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 用户登录信息的控制器类
 * @author 芝加哥
 * @since [2017-01-08]
 *
 */
@Controller
@RequestMapping("/auth")
public class AuthController {
    private Logger logger = Logger.getLogger(getClass());

    /**
     * 加载出用户注册页面
     * @return
     */
    @RequestMapping(value = "signup", method = RequestMethod.GET)
    public String signup() {
        return "auth/signup";
    }
}

   效果

    此节主要目的是为了配置Web开发的环境,所以启动tomcat后,输入如下链接:

http://localhost:8080/yp/auth/signup

效果如下:


《自己动手写云盘》- 搭建SpringMVC + Spring + Mybatis + Velocity的Web环境
 以后章节会继续往下开发,希望大家不断关注,谢谢。。。

   关注微信公众号

《自己动手写云盘》- 搭建SpringMVC + Spring + Mybatis + Velocity的Web环境
 

相关推荐