SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model
2016-03-04 15:03
633 查看
一、RequestMapping
1.可以写在方法上或类上,且值可以是数组
2.测试
3.jsp
二、在controller中使用model,model实际就是一个map
1.controller
(1)
如果在addAttribute时没有指定key,则spring会根据存入的数据类型来生成key,如上面存入的数据类型是List<Spittle>,所以key就是spittleList
(2)也可以明确key
(3)也可用map替换model
(4)不返回string,直接返回数据类型
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解析数据
3.测试
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; } }
相关文章推荐
- iOS 引入支付宝 缺少 #include <openssl/asn1.h>
- iOS ,不提交审核,修复某些线上bug以及线上更新
- WebView组件的常用方法
- android listview点赞问题
- 将packages/apps/下的app导入eclipse
- Android Listview加载不同布局,ViewHolder类型转换异常!!!
- iOS开发资源汇总
- Object.wait()与Object.notify()的用法
- android---TextView中电话号码、网址自动链接的实现方法
- android ToastShow 直接切换文字,不闪烁
- 【jeecg移动开发能力】表单移动开发能力,提供多套表单模板(移动端、PC端),支持自定义
- Android Gridview 属性集合
- Android Studio 与 NDK
- Android自定义view+程序启动引导页面
- 微信内置浏览器图片放大轮播
- 仅需6步,教你轻易撕掉app开发框架的神秘面纱(5):数据持久化
- android Application类的详细介绍
- iOS KVC和一些基础知识了解
- 调用支付宝接口,完成付款功能
- android apk变相打包技术。