SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model
一、RequestMapping
1.可以写在方法上或类上,且值可以是数组
package spittr.web; import static org.springframework.web.bind.annotation.RequestMethod.*; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
//@Component //也可用这个,但没有见名知义
//@RequestMapping("/")
@RequestMapping({"/", "/homepage"})
public class HomeController { //@RequestMapping(value="/", method=GET)
@RequestMapping(method = GET)
public String home(Model model) {
return "home";
} }
2.测试
package spittr.web;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc; import spittr.web.HomeController; public class HomeControllerTest { @Test
public void testHomePage() throws Exception {
HomeController controller = new HomeController();
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get("/homepage"))
.andExpect(view().name("home"));
} }
3.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Spitter</title>
<link rel="stylesheet"
type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Welcome to Spitter</h1> <a href="<c:url value="/spittles" />">Spittles</a> |
<a href="<c:url value="/spitter/register" />">Register</a>
</body>
</html>
二、在controller中使用model,model实际就是一个map
1.controller
(1)
package spittr.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spittr.Spittle;
import spittr.data.SpittleRepository;
@Controller
@RequestMapping("/spittles")
public class SpittleController {
private SpittleRepository spittleRepository; @Autowired
public SpittleController(SpittleRepository spittleRepository) {
this.spittleRepository = spittleRepository;
} @RequestMapping(method = RequestMethod.GET)
public String spittles(Model model) {
model.addAttribute(spittleRepository.findSpittles(Long.MAX_VALUE, 20));
return "spittles";
}
}
如果在addAttribute时没有指定key,则spring会根据存入的数据类型来生成key,如上面存入的数据类型是List<Spittle>,所以key就是spittleList
(2)也可以明确key
@RequestMapping(method = RequestMethod.GET)
public String spittles(Model model) {
model.addAttribute("spittleList",spittleRepository.findSpittles(Long.MAX_VALUE, 20));
return "spittles";
}
(3)也可用map替换model
@RequestMapping(method = RequestMethod.GET)
public String spittles(Map model) {
model.put("spittleList",spittleRepository.findSpittles(Long.MAX_VALUE, 20));
return "spittles";
}
(4)不返回string,直接返回数据类型
@RequestMapping(method = RequestMethod.GET)
public List < Spittle > spittles() {
return spittleRepository.findSpittles(Long.MAX_VALUE, 20));
}
When a handler method returns an object or a collection like this, the value returned is put into the model, and the model key is inferred from its type ( spittleList , as in the other examples).
As for the logical view name, it’s inferred from the request path. Because this method handles GET requests for /spittles, the view name is spittles (chopping off the leading slash).
2.View
在jsp中用jstl解析数据
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <html>
<head>
<title>Spitter</title>
<link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />" >
</head>
<body>
<div class="spittleForm">
<h1>Spit it out...</h1>
<form method="POST" name="spittleForm">
<input type="hidden" name="latitude">
<input type="hidden" name="longitude">
<textarea name="message" cols="80" rows="5"></textarea><br/>
<input type="submit" value="Add" />
</form>
</div>
<div class="listTitle">
<h1>Recent Spittles</h1>
<ul class="spittleList">
<c:forEach items="${spittleList}" var="spittle" >
<li id="spittle_<c:out value="spittle.id"/>">
<div class="spittleMessage"><c:out value="${spittle.message}" /></div>
<div>
<span class="spittleTime"><c:out value="${spittle.time}" /></span>
<span class="spittleLocation">(<c:out value="${spittle.latitude}" />, <c:out value="${spittle.longitude}" />)</span>
</div>
</li>
</c:forEach>
</ul>
<c:if test="${fn:length(spittleList) gt 20}">
<hr />
<s:url value="/spittles?count=${nextCount}" var="more_url" />
<a href="${more_url}">Show more</a>
</c:if>
</div>
</body>
</html>
3.测试
package spittr.web;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.view.InternalResourceView; import spittr.Spittle;
import spittr.data.SpittleRepository;
import spittr.web.SpittleController; public class SpittleControllerTest { @Test
public void shouldShowRecentSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(20);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(Long.MAX_VALUE, 20))
.thenReturn(expectedSpittles); SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build(); mockMvc.perform(get("/spittles"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
} @Test
public void shouldShowPagedSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(50);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(238900, 50))
.thenReturn(expectedSpittles); SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build(); mockMvc.perform(get("/spittles?max=238900&count=50"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
} @Test
public void testSpittle() throws Exception {
Spittle expectedSpittle = new Spittle("Hello", new Date());
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findOne(12345)).thenReturn(expectedSpittle); SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build(); mockMvc.perform(get("/spittles/12345"))
.andExpect(view().name("spittle"))
.andExpect(model().attributeExists("spittle"))
.andExpect(model().attribute("spittle", expectedSpittle));
} @Test
public void saveSpittle() throws Exception {
SpittleRepository mockRepository = mock(SpittleRepository.class);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build(); mockMvc.perform(post("/spittles")
.param("message", "Hello World") // this works, but isn't really testing what really happens
.param("longitude", "-81.5811668")
.param("latitude", "28.4159649")
)
.andExpect(redirectedUrl("/spittles")); verify(mockRepository, atLeastOnce()).save(new Spittle(null, "Hello World", new Date(), -81.5811668, 28.4159649));
} private List<Spittle> createSpittleList(int count) {
List<Spittle> spittles = new ArrayList<Spittle>();
for (int i=0; i < count; i++) {
spittles.add(new Spittle("Spittle " + i, new Date()));
}
return spittles;
}
}
SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model的更多相关文章
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error
一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...
- SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍
一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)
一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)
一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)
一.显示注册表单 1.访问资源 @Test public void shouldShowRegistration() throws Exception { SpitterRepository mock ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-003-示例项目用到的类及配置文件
一.配置文件 1.由于它继承AbstractAnnotationConfigDispatcherServletInitializer,Servlet容器会把它当做配置文件 package spittr ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice
No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver
一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
随机推荐
- 第一章 认识jQuery
jQuery是一个优秀的JavaScript库,它凭借简洁地语法和跨平台的兼容性,极大地简化了开发人员遍历HTML文档,操作DOM,处理事件,执行动画和开发Ajax操作. jQuery优势:1.轻量级 ...
- 精妙SQL语句介绍
说明:复制表(只复制结构,源表名:a 新表名:b) SQL: select * into b from a where 1<>1 说明:拷贝表(拷贝数据,源表名:a 目标表名:b) SQL ...
- python内置函数大全
一.数学运算类 abs(x) 求绝对值1.参数可以是整型,也可以是复数2.若参数是复数,则返回复数的模 complex([real[, imag]]) 创建一个复数 divmod(a, b) 分别取商 ...
- SDL_Test库(1)——SDL不用TTF库绘制文字
SDL库有很多的扩展,这很方便.但是每个扩展库都很臃肿,一般都会拖上额外的两三个开源库,更有甚者,扩展库的大小比SDL库本身还大得多.但有一个自带的.很有用的库很容易被大家忽视.它就是本文要讲的SDL ...
- [.Net MVC] 过滤器以及异常处理
项目:后台管理平台 意义:程序发布后,不应该对用户显示因程序出错和崩溃而出现的错误信息,采用统一友好的错误页面,并将错误信息记录到日志中供管理人员查看. 一.过滤器Filter Filter(筛选器) ...
- 393. UTF-8 Validation
393. UTF-8 Validation 这个题很明确,刚开始我以为只能是一个utf,长度大于5的都判断为false,后来才明白题意. 有个小trick,就是长度大于1的时候,判断第一个数字开始1的 ...
- hdu 1753 大明A+B(高精度小数加法)
//深刻认识到自己的粗心,为此浪费了一天.. Problem Description 话说,经过了漫长的一个多月,小明已经成长了许多,所以他改了一个名字叫"大明". 这时他已经不是 ...
- 在Mac OS X中搭建STM32开发环境(1)
本文原创于http://www.cnblogs.com/humaoxiao,非法转载者请自重! 本文方法必须好用!绝不坑爹!看了N多英文资料才搞明白的,适用于STM32F4DISCOVERY评估板,带 ...
- 排序算法SIX:冒泡排序BubbleSort
/** *冒泡排序: * 两个两个比较,一轮过后最大的排在了最后面 * n个数变为n-1个没排好的数 * 再进行一轮 * 第二大的排在了倒数第二个 * 以此类推 * 直到排到第一个为止 * * 弄两个 ...
- Linux CPU亲缘性详解
前言 在淘宝开源自己基于nginx打造的tegine服务器的时候,有这么一项特性引起了笔者的兴趣.“自动根据CPU数目设置进程个数和绑定CPU亲缘性”.当时笔者对CPU亲缘性没有任何概念,当时作者只是 ...