详解Maven 构建SpringMVC4.0

准备使用maven构建一个SpringMVC4.0的项目,苦于网上没有现成的资料,于是自己摸索着写了这样一份文档,分享给大家,也给自己留作参考

1.maven插件的安装,参考《maven实战》,其中有详细的安装步骤详解,链接里有扫描的pdf,仅供参考学习 http://pan.baidu.com/s/1jGhMF0i

2.创建maven项目,New->Project->Maven Project,默认下一步

创建一个webapp项目
详解Maven 构建SpringMVC4.0_第1张图片
填写GroupId和ArtifactId
详解Maven 构建SpringMVC4.0_第2张图片
项目结构如图:

直接进入workspace,向物理目录src中添加main/java,test/java.test/resource文件夹,eclipse F5刷新目录,如果目录显示不全,BuildPath->Source->Add Folder添加对应的目录
最终目录结构如图所示:

点击控制台problem,提示错误为:
*Description Resource Path Location Type
The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path index.jsp /MavenDemo/src/main/webapp line 1 JSP Problem*
BuildPath添加位于tomcat目录下lib中的servlet-api.jar即可

3.完成pom.xml,配置参数版本,jar包依赖,构建环境,为下一步准备,直接下载了mybatis的jar包

<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>maven</groupId>
    <artifactId>MavenDemo2</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>MavenDemo2 Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>4.0.6.RELEASE</spring.version>
        <junit.version>4.11</junit.version>
        <jdk.version>1.8</jdk.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0.0</version>
            <type>pom.lastUpdated</type>
        </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.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.4.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
            <version>1.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>1.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcomponents-core</artifactId>
            <version>4.3</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.5</version>
        </dependency>

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <finalName>MavenDemo</finalName>
    </build>
</project>

项目右键,Maven->Update Project,构建项目所需的jar包

4.配置web.xml,打开位于src/mian/webapp/web-inf路径下的web.xml,配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">

  <!-- 初始化配置文件 applicationContext.xml-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>

  <!-- 自动装配ApplicationContext的配置信息 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 字符编码过滤器 -->
  <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>*.do</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

  <!--加载核心 DispatcherServlet -->
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!-- servlet的初始化配置文件 -->
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webapp.root2</param-value>
    </context-param>

</web-app>

5.在web-inf目录下创建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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 系统基础配置 -->
    <bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- 忽略占位符异常 -->
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <!-- 在解析一个占位符的时候,会先用系统属性来尝试,然后才会用指定的属性文件-->
        <property name="ignoreResourceNotFound" value="true" />
    </bean>

    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />

    <!--需要扫描的包 -->
    <context:component-scan base-package="com.zzq.*" />
</beans>

6.新建目录结构如下:
详解Maven 构建SpringMVC4.0_第3张图片

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


    <!-- activates annotation driven binding -->
    <!-- 简写的配置标记,自动注册其中的bean -->
    <mvc:annotation-driven>
        <!-- 允许注册实现了HttpMessageConverter接口的bean,来对requestbody 或responsebody中的数据进行解析 -->
        <mvc:message-converters>
            <bean  class="org.springframework.http.converter.ResourceHttpMessageConverter" />
            <bean  class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
            <bean  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
            <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <context:component-scan base-package="com" />
    <context:annotation-config />
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> 
    <mvc:default-servlet-handler/>
</beans>

root-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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

</beans>

7.测试框架
测试文件结构如图:

在controller中使用了@RestController,@ModelAttribute两个4.0的注解。以下是详细实现。

TestController:

package com.zzq.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.zzq.model.User;


@RestController
@RequestMapping(value = "/api_cat")
public class TestController  {
    @RequestMapping(value = "/add")
    public ModelAndView save(@ModelAttribute User user,HttpServletRequest request, HttpServletResponse response) {
        System.out.println(user.getId()+":"+user.getName());

        Map<String, Object> map=new HashMap<String,Object>();
         map.put("id", user.getId());
         map.put("name", user.getName());


        return new ModelAndView("test", "apiver", map);
    }

}

model User:

package com.zzq.model;

import java.io.Serializable;

public class User implements Serializable {
    private int id;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

index.jsp:

<html>
<body>
<h2>Add Book</h2>
<form method="post" action="api_cat/add.do">
id:<input type="text" name="id" >
name:<input type="text" name="name" >
<input type="submit" value="Add">
<a href="book.do?method=test">test</a>
</form>
</body>
</html>

test.jsp:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
ID : ${apiver.id} <br />
Name : ${apiver.name}
</body>
</html>

maven install后,将项目部署到tomcat上即可访问。

特别注意,执行maven install命令时,可能会出现以下异常:
Cannot change version of project facet Dynamic Web Module to 3.0.

这个异常是由于项目版本问题引起的,解决办法是:修改项目.setting目录下的org.eclipse.wst.common.project.facet.core.xml文件,将其中的

<installed facet="jst.web" version="3.0"/>

一项修改为3.0

配置到这里,整个项目环境就基本搭建完成了,数据持久层我准备使用mybatis来实现,实现后再贴上来,我在搭建环境的过程中也是遇到问题解决问题,所以肯定有一些逻辑混乱和表达不清。如果按照文档实现起来遇到问题,欢迎讨论。如果我的实现办法不周到,欢迎指教。

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