- 内容提要
- 作者简介
- 译者简介
- 前言
- HTTP
- Servlet 和 JSP
- 下载 Spring 或使用 STS 与 Maven/Gradle
- 手动下载 Spring
- 使用 STS 和 Maven/Gradle
- 下载 Spring 源码
- 本书内容简介
- 下载示例应用
- 第 1 章Spring 框架
- 第 2 章模型 2 和 MVC 模式
- 第 3 章Spring MVC 介绍
- 第 4 章基于注解的控制器
- 第 5 章数据绑定和表单标签库
- 第 6 章转换器和格式化
- 第 7 章验证器
- 第 8 章表达式语言
- 第 9 章JSTL
- 第 10 章国际化
- 第 11 章上传文件
- 第 12 章下载文件
- 第 13 章应用测试
- 附录 A Tomcat
- 附录 B Spring Tool Suite 和 Maven
- 附录 C Servlet
- 附录 D JavaServer Pages
- 附录 E 部署描述符
4.3 应用基于注解的控制器
本章的示例应用 annotated1 基于第 2 章和第 3 章的例子重写,展示了包含有两个请求处理方法的一个控制器类。
annotated1 和前面的应用程序间的主要区别在于,annotated1 的控制器类增加了注解 @Controller。此外,Spring 配置文件也增加了一些元素,后续小节中会详细介绍。
4.3.1 目录结构
图 4.1 展示了 annotated1 的目录结构。注意,annotated1 中只有一个控制器类,而不是两个,同时新增了一个名为 index.html 的 HTML 文件,以便 Spring MVC Servlet 的 URL 模式设置为“/”时,依然可以访问静态资源。
4.3.2 配置文件
annotated1 有两个配置文件。第一个为部署描述符(web.xml 文件)中注册 Spring MVC 的 Dispatcher Servlet。第二个为 springmvc-config.xml,即 Spring MVC 的配置文件。
清单 4.1 和清单 4.2 分别展示部署描述符和 Spring MVC 的配置文件。
清单 4.1 annotated1(web.xml) 的部署描述符
< ?xml version="1.0" encoding="UTF-8"?>
< web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
< servlet>
< servlet-name>springmvc< /servlet-name>
< servlet-class>
org.springframework.web.servlet.DispatcherServlet
< /servlet-class>
< init-param>
< param-name>contextConfigLocation< /param-name>
< param-value>
/WEB-INF/config/springmvc-config.xml
< /param-value>
< /init-param>
< load-on-startup>1< /load-on-startup>
< /servlet>
< servlet-mapping>
< servlet-name>springmvc< /servlet-name>
< url-pattern>/< /url-pattern>
< /servlet-mapping>
< /web-app>
图 4.1 为 annotated1 的目录结构。
图 4.1 annotated1 的目录结构
另外,在部署描述符中的<servlet-mapping/>元素,Spring MVC 的 dispatcher-servlet 的 URL 模式设置为“/”,当 URL 模式设置为“/”时,意味着所有请求(包括那些用于静态资源)都被映射到 Dispatcher Servlet。为了正确处理静态资源,需要在 Spring MVC 配置文件中添加一些<resources/>元素。
清单 4.2 springmvc-config.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:p="http://www.springframework.org/schema/p"
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.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/springcontext.xsd">
< context:component-scan base-package="controller"/>
< mvc:annotation-driven/>
< mvc:resources mapping="/css/ **" location="/css/"/>
< mvc:resources mapping="/ *.html" location="/"/>
< bean id="viewResolver"
class="org.springframework.web.servlet.view.
→InternalResourceViewResolver">
< property name="prefix" value="/WEB-INF/jsp/"/>
< property name="suffix" value=".jsp"/>
< /bean>
< /beans>
清单 4.2(Spring MVC 的配置文件)中最主要的是<component-scan/>元素。这是要指示 Spring MVC 扫描目标包中的类,本例是 controller 包。接下去是一个<annotation-driven/>元素和两个<resources/>元素。<annotation-driven/>元素做了很多的事情,其中包括注册用于控制器注解的 bean 对象。<resources/>元素则指示 Spring MVC 哪些静态资源需要单独处理(不通过 Dispatcher Servlet)。
在清单 4.2 的配置文件中,有两个<resources/>元素。第一个确保在/ CSS 目录下的所有文件可见,第二个允许显示所有的.html 文件。
注意
如果没有<annotation-driven/>,<resources/>元素会阻止任意控制器被调用。若不需要使用 resources,则不需要<annotation-driven/>元素。
4.3.3 Controller 类
如前所述,使用 Controller 注释类型的一个优点在于:一个控制器类可以包含多个请求处理方法。如清单 4.3 所示,ProductController 类中有 inputProduct 和 saveProduct 两个方法。
清单 4.3 ProductController 类
package controller;
import java.match.Bigoecimal
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import domain.Product;
import form.ProductForm;
@Controller
public class ProductController {
private static final Log logger =
LogFactory.getLog(ProductController.class);
@RequestMapping(value="/input-product")
public String inputProduct() {
logger.info("inputProduct called");
return "ProductForm";
}
@RequestMapping(value="/save-product")
public String saveProduct(ProductForm productForm, Model model){
logger.info("saveProduct called");
// no need to create and instantiate a ProductForm
// create Product
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try {
product.setPrice(new BigDecimal(productForm.getPrice()));
} catch (NumberFormatException e) {
}
// add product
model.addAttribute("product", product);
return "ProductDetails"; } }
其中,ProductController 的 saveProduct 方法的第二个参数是 org.springframework.ui.Model 类型。无论是否会使用,Spring MVC 都会在每一个请求处理方法被调用时创建一个 Model 实例,用于增加需要显示在视图中的属性。例如,通过调用 model.addAttribute 来添加 Product 实例:
model.addAttribute("product", product);
Product 实例就可以像被添加到 HttpServletRequest 中那样访问了。
4.3.4 View
annotated1 也有与前面章节示例类似的两个视图:ProductForm.jsp 页面(见清单 4.4)和 ProductDetails.jsp 页面(见清单 4.5)。
清单 4.4 ProductForm.jsp 页面
<!DOCTYPE HTML>
<html>
<head>
<title>Add Product Form</title>
<style type="text/css">@import url(css/main.css);</style>
</head>
<body>
<div id="global">
<form action="save-product" method="post">
<fieldset>
<legend>Add a product</legend>
<p>
<label for="name">Product Name: </label>
<input type="text" id="name" name="name"
>
</p>
<p>
<label for="description">Description: </label>
<input type="text" id="description"
name="description">
</p>
<p>
<label for="price">Price: </label>
<input type="text" id="price" name="price"
>
</p>
<p id="buttons">
<input id="reset" type="reset">
<input id="submit" type="submit"
value="Add Product">
</p>
</fieldset>
</form>
</div>
</body>
</html>
清单 4.5 ProductDetails.jsp 页面
<!DOCTYPE HTML>
<html>
<head>
<title>Save Product</title>
<style type="text/css">@import url(css/main.css);</style>
</head>
<body>
<div id="global">
<h4>The product has been saved.</h4>
<p>
<h5>Details:</h5>
Product Name: ${product.name}<br/>
Description: ${product.description}<br/>
Price: $${product.price}
</p>
</div>
</body>
</html>
4.3.5 测试应用
在浏览器中输入如下 URL 来测试 annotated1。
http://localhost:8080/annotated1/input-product
浏览器会显示 Product 表单,如图 4.2 所示。
单击“Add Product”按钮,会调用 saveProduct 方法。
图 4.2 Product 表单
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论