一. 点睛
Spring MVC
提供了一个DispatcherServlet
来开发Web
应用。在Servlet2.5
以及以下的时候只要在web.xml
下配置Servlet3.0+
无web.xml
的配置方式,在Spring
MVC
里面实现WebApplicationInitializer
接口便可实现等同于web.xml
的配置。
下面将基于Maven
搭建零配置的Spring MVC
原型项目。
二. 示例
1. 快速构建Maven项目
说明:系列文章的内容有依赖关系,后面章节的内容依赖前面章节内容的配置。为了方便后面内容的讲解,所以构建的是多模块
maven
项目,公用的依赖配置在父工程的pom.xml
文件里面,如果在当前工程的pom
文件里面找不到的依赖可以查看父工程的配置,后面的章节也是如此,不再说明。
pom.xml
的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<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>springMvc4.x-learning</groupId>
<artifactId>springMvc4.x-learning</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>springMvc4.x-learning</name>
<url>http://blog.longjiazuo.com</url>
<modules>
<module>springMvc4.x-quickStart</module>
</modules>
<properties>
<!-- Generic properties -->
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<!-- Spring -->
<spring-framework.version>4.1.5.RELEASE</spring-framework.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- 其他web依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- 使用SLF4J和LogBack作为日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 日志配置
在src/main/resources
目录下,新建logback.xml
用来配置日志,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="1 seconds">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<jmxConfigurator/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>logbak: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.web" level="DEBUG"/> <!-- ① -->
<root level="info">
<appender-ref ref="console"/>
</root>
</configuration>
代码解释:
① 将
org.springframework.web
包下的类的日志级别设置为DEBUG
,我们开发Spring
MVC
经常出现和参数类型相关的4XX
错误。设置此项我们将会看到更详细的错误信息。
3. 演示页面
在src/main/resources
下建立views
目录,并在此目录下新建index.jsp
,内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<pre>
Welcome to Spring MVC world
</pre>
</body>
</html>
代码解释:
也许你会问,为什么页面不放在
Maven
标准的src/main/webapp/WEB-INF
下,此处这样建的目的主要是习惯Spring
Boot
的页面的放置方式,Spring
Boot
的页面就放置在src/main/resources
下。
4. Spring MVC配置
package org.light4j.springMvc4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc// ①
@ComponentScan("org.light4j.springMvc4")
public class MyMvcConfig extends WebMvcConfigurerAdapter {// ②
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
}
代码解释:
此处无任何特别之处,只是一个普通的
Spring
配置类。这里我配置了JSP
的ViewResolver
,用来映射路径和实际页面的位置,其中,@EnableWebMvc
注解会开启一些默认配置,如一些ViewResolver
或者MessageConverter
等。在此处要特别解释一下
Spring
MVC
的ViewResolver
,这是Spring
MVC
视图(JSP
下就是html
)渲染的核心机制;Spring
MVC
里有一个接口叫做ViewResolver
(所有的ViewResolver
都实现该接口),实现这个接口要重写方法resolveViewName()
,这个方法的返回值是接口View
,而View
的职责就是使用model
,request
,response
对象,并将渲染的视图(不一定是html
,可能是json
,xml
,ViewResolver
的内容。可能你会对当前路径前缀配置为
/WEB-INF/classes/views/
有些奇怪,怎么和我开发的目录不一致?因为我们看到的页面效果是运行时而不是开发时候的代码,运行时代码会将我们的页面自动编译到/WEB-INF/classes/views/
下,下图是运行时的目录结构,这样我们就能理解前缀为什么写成这样,在Spring
Boot
中,使用Thymeleaf
作为模板,将不需要这样的设置。
![]()
5. Web配置
package org.light4j.springMvc4;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInitializer implements WebApplicationInitializer {// ①
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MyMvcConfig.class);
ctx.setServletContext(servletContext); // ②
Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx)); // ③
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
代码解释:
①
WebApplicationInitializer
是Spring
提供用来配置Servlet3.0
+配置的接口,从而实现替代web.xml
的位置。实现此接口将会自动被SpringServletContainerInitializer
(用来启动Servlet3.0
容器)获取到。
② 新建WebApplicationContext
,注册配置类,并将其和当前servletContext
关联。
③ 注册Spring
MVC
的DispatcherServlet
。
6. 简单控制器
package org.light4j.springMvc4.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
// ①
public class HelloController {
@RequestMapping("/index")
// ②
public String hello() {
return "index";
}
}
代码解释:
① 利用
@Controller
注解声明是一个控制器。
② 利用@RequestMapping
配置URL
和方法之间的映射。
③ 通过上面ViewResolver
的Bean
配置,返回值为index
,说明我们的页面放置的路径为/WEB-INF/classes/views/
。
7.运行
将程序部署到Tomcat
中,我设置的Tomcat
端口是80
,现在启动Tomcat
,并访问http://localhost/springMvc4.x-quickStart/index
,
运行结果如下图所示:
三. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » SpringMvc4.x基础(一):Spring MVC项目快速搭建