Spring MVC是Spring框架提供的构建Web应用程序的全功能MVC模块。功能强大,使用方便,只要是同网络应用相关的,无论是有同用户互动的(带UI的)或者没有互动的情况,Spring mvc都是种成熟、功能齐全的架构。

本文以一个欢迎页面为例,使用两种方式搭建Spring MVC应用:

  1. 基于xml配置与DispatcherServlet
  2. 基于注解

基于xml配置和DispatcherServlet

最终的工程配置如图

创建步骤

1、创建web应用工程

2、导入Spring MVC依赖的jar库

3、web.xml配置应用greeting,以及servlet的xml配置

web.xml 配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>greeting</display-name>
  
  <servlet>
  	<servlet-name>greeting_controller</servlet-name>
  	<servlet-class>
  		org.springframework.web.servlet.DispatcherServlet
  	</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>greeting_controller</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

注意:

greeting_controller-servlet.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  
 <bean name="/"
  class="hello.GreetingController">
 </bean>

</beans>

4、添加 WEB-INF/jsp/greeting.jsp

jsp文件依赖一个java代码注入的name对象,如果对象为空,则显示”Hello world”,否则显示对应的name。

<%@ 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>greeting</title>
    </head>
    <body>
        <p>
            Hello, ${empty name ? "world" : name}
        </p>
    </body>
</html>

5、java代码Controller,并注入name

package hello;

import javax.servlet.http.*;

import org.apache.commons.logging.*;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.Controller;

public class GreetingController implements Controller {
    @Override
    public ModelAndView handleRequest( HttpServletRequest req, HttpServletResponse res ) throws Exception {
        String name = req.getParameter("name");
        return new ModelAndView("/WEB-INF/jsp/greeting.jsp", "name", name);
    }
}

6、创建Server

工程右键,添加web容器 tomcat 作为Server:

启动server后,访问http://localhost:8080/greeting/?name=suninf,会展示 “Hello, suninf”

基于注解

使用官网的示例:Serving Web Content with Spring MVC

1、创建项目框架

创建一个目录作为项目的根目录,进入根目录

mkdir -p src/main/java/hello

Spring Boot Maven plugin插件提供很多便利:

2、创建基于注解的controller

src/main/java/hello/GreetingController.java

package hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}

注解 @RequestMapping 确保指向 /greeting 的http请求会映射到greeting()方法。

3、创建velocity的模板vm文件

src/main/resources/templates/greeting.vm

<!DOCTYPE HTML>
<html>
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p>Hello, ${name}</p>
</body>
</html>

注意:

4、让应用可独立部署执行

src/main/java/hello/Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

5、打包与执行