# 前言

今天手把手来教大家如何搭建基于 Maven 的 SpringMVC WEB 项目。

# 正文

# 开发环境介绍

IDE: MyEclipse 2017
jdk: 1.7
maven:apache-maven-3.1.1
好了,基本环境只要上面这些就行,maven 不需要安装,只要有解压包就行。

# MyEclipse 2014 中 Maven 的配置

打开 myeclipse 中的 Window=>Preferences=>Java=>Installed JREs
配置 jdk,这里我们选择 1.7

配置好 maven 路径,也就是你之前存放 maven 解压包的路径

指定 User Settings , 对应 settings.xml 以及本地仓库地址,我这边是建在盘,路径为 D:\maven\repo3.1.1

# 创建 WEB 项目

新建一个 web 项目

配置项目基本信息,项目名,java EE,java 版本,其中记得要勾上 Add maven support,这样才会生成带有 maven 的工程。

创建成功后出正确的项目结构应该是这样,如果不是下图中这样,src 下面没有以下这些包也没事,自己创建 src/main/java , src/main/resources , src/test/java , src/test/resources , 然后指定以下这些包为 source 就行。

# 配置需要的安装包

下面列出目前需要用到包,直接在 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>SpringMVCMybatis</groupId>
  <artifactId>SpringMVCMybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>SpringMVCMybatis</name>
  <description/>
  <properties>
    	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  		<spring.version>4.1.1.RELEASE</spring.version>
  		<cxf.version>2.7.15</cxf.version>
    	<slf4j-version>1.7.12</slf4j-version>
    	<log4j-version>1.2.17</log4j-version>
    	<mybatis-version>3.3.0</mybatis-version>
    	<mybatis-spring-version>1.2.3</mybatis-spring-version>
  </properties>
  <dependencies>
  	<!-- 日志配置-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j-version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j-version}</version>
    </dependency>
      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j-version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-lang3</artifactId>
       <version>3.3</version>
    </dependency>
    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>fastjson</artifactId>
       <version>1.2.1</version>
    </dependency>
    <!-- 数据源配置 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.1</version>
    </dependency>
    <!--数据库相关, mysql, mybatis-->
    <dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.37</version>
	</dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis-spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis-version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.2</version>
    </dependency>
    <!-- spring用到的包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</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-context</artifactId>
        <version>4.1.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</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-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.1.1.RELEASE</version>
        <scope>test</scope>
    </dependency>
        
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>javax.servlet.jsp.jstl</artifactId>
      <version>1.2.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <version>3.1</version>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

# 配置 SpringMVC 需要的配置文件

web.xml 配置,注意里面配置 springMVC 需要用到的 DispatcherServlet ,指向的地址是 classpath:spring/applicationContext.xml ,当然此时还没创建这个 applicationCVontext.xml , 下一个步骤来创建

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>springmvctouchbaidu</display-name>
    <servlet>
        <servlet-name>springmvctouchbaidu</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvctouchbaidu</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <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>
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
</web-app>

src/main/resources 下面创建个 spring 目录用来存放 applicationContext.xml
后期会用的的配置很多,所以我一般会根据不同用途创建不同别名的 spring 配置文件,然后用 applicationContext.xml 统一起来。
这里我创建了 applicationContext.xml 以及 applicationContext-mvc.xml
applicationContext.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: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/mvc 
       http://www.springframework.org/schema/mvc/spring-mvc.xsd"
       default-lazy-init="true">
    <context:component-scan base-package="com.lxl.demo"/>
	<mvc:resources location="/WEB-INF/pages/" mapping="/pages/**"/>
	<!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
	<!-- 默认的注解映射的支持 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=utf-8</value>
                        <value>application/json;charset=utf-8</value>
                        <value>application/x-www-form-urlencoded</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

其中一些重要的配置下篇文章详细的说明

context:component-scan 用来扫描指定的路径下的包,来加载组件用的
mvc:resources 指定静态资源路径

# 实现一个简单的 springMVC 请求

配置文件配置好了,我们就来测试一下,写一个 controller 来实现前后台交互
在 src/main/java 下面创建如下格式的文件夹。这是我习惯的写法。

common 用来存放公共的类
controller 控制层
service 层用来处理业务逻辑
dao 层用来处理数据库操作
dto 层用来存放 mybatis 根据表自动生成的实体对象

具体结构如下图:

controller包 下面创建一个类 SendToBaiduController

package com.lxl.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value="/sendBaidu")
public class SendToBaiduController {
    @RequestMapping(value="/view",method = RequestMethod.GET)
    public String index(){
        System.out.println("进来了");
        return "index";
    }
    
}

index.jsp 代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  <body>
        跳转进来,表示springMVC流程成功!
  </body>
</html>

部署到 tomcat 启动服务看看 输入地址是否控制台会打印 “进来了” 这 3 字,并跳转到 index 界面
http://localhost:8080/springmvctouchbaidu/sendBaidu/view
大家看,如图表示 springMVC 整体流程成功了

# 总结

到此,基于 Maven 的 SpringMVC WEB 项目搭建算是成功了,后续会基于这个基础添加其他的功能,比如整合数据库框架 mybatis,多数据源处理,定时任务等等。下篇文章将整体上介绍 springMVC 的配置文件以及注解标签的使用。