Spring MVC是Spring框架提供的构建Web应用程序的全功能MVC模块。功能强大,使用方便,只要是同网络应用相关的,无论是有同用户互动的(带UI的)或者没有互动的情况,Spring mvc都是种成熟、功能齐全的架构。
本文以一个欢迎页面为例,使用两种方式搭建Spring MVC应用:
- 基于xml配置与DispatcherServlet
- 基于注解
基于xml配置和DispatcherServlet
最终的工程配置如图
创建步骤
1、创建web应用工程
2、导入Spring MVC依赖的jar库
- 下载Spring jar包
- 下载common-logging
- 导入创建Spring MVC依赖的lib,放在WEB-INF/lib目录下
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>
注意:
- display-name表示了应用的启动路径
/greeting
- servlet-name用于绑定Controller的配置文件
greeting_controller-servlet.xml
- servlet-mapping表示应用的url-pattern的匹配策略
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
根目录下建立 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>org.springframework</groupId> <artifactId>gs-serving-web-content</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-velocity</artifactId> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestone</id> <url>https://repo.spring.io/libs-release</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestone</id> <url>https://repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories> </project>
Spring Boot Maven plugin插件提供很多便利:
- 能收集classpath上的jar包,并打出可以独立运行的jar包
- 搜索包含
public static void main()
的类作为运行类
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>
注意:
- 参考Spring Boot Reference Guide,了解关于Spring boot可用的模板引擎。
- 这里使用了velocity来解析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、打包与执行
mvn install
java -jar target/gs-serving-web-content-0.1.0.jar
- 访问http://localhost:8080/greeting/?name=suninf,会展示 “Hello, suninf”