一、RequestMapping

1.可以写在方法上或类上,且值可以是数组

  1. package spittr.web;
  2.  
  3. import static org.springframework.web.bind.annotation.RequestMethod.*;
  4.  
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.Model;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8.  
  9. @Controller
  10. //@Component //也可用这个,但没有见名知义
  11. //@RequestMapping("/")
  12. @RequestMapping({"/", "/homepage"})
  13. public class HomeController {
  14.  
  15. //@RequestMapping(value="/", method=GET)
  16. @RequestMapping(method = GET)
  17. public String home(Model model) {
  18. return "home";
  19. }
  20.  
  21. }

2.测试

  1. package spittr.web;
  2. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
  3. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
  4. import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
  5.  
  6. import org.junit.Test;
  7. import org.springframework.test.web.servlet.MockMvc;
  8.  
  9. import spittr.web.HomeController;
  10.  
  11. public class HomeControllerTest {
  12.  
  13. @Test
  14. public void testHomePage() throws Exception {
  15. HomeController controller = new HomeController();
  16. MockMvc mockMvc = standaloneSetup(controller).build();
  17. mockMvc.perform(get("/homepage"))
  18. .andExpect(view().name("home"));
  19. }
  20.  
  21. }

3.jsp

  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  2. <%@ page session="false" %>
  3. <html>
  4. <head>
  5. <title>Spitter</title>
  6. <link rel="stylesheet"
  7. type="text/css"
  8. href="<c:url value="/resources/style.css" />" >
  9. </head>
  10. <body>
  11. <h1>Welcome to Spitter</h1>
  12.  
  13. <a href="<c:url value="/spittles" />">Spittles</a> |
  14. <a href="<c:url value="/spitter/register" />">Register</a>
  15. </body>
  16. </html>

二、在controller中使用model,model实际就是一个map

1.controller

(1)

  1. package spittr.web;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import spittr.Spittle;
  8. import spittr.data.SpittleRepository;
  9. @Controller
  10. @RequestMapping("/spittles")
  11. public class SpittleController {
  12. private SpittleRepository spittleRepository;
  13.  
  14. @Autowired
  15. public SpittleController(SpittleRepository spittleRepository) {
  16. this.spittleRepository = spittleRepository;
  17. }
  18.  
  19. @RequestMapping(method = RequestMethod.GET)
  20. public String spittles(Model model) {
  21. model.addAttribute(spittleRepository.findSpittles(Long.MAX_VALUE, 20));
  22. return "spittles";
  23. }
  24. }

如果在addAttribute时没有指定key,则spring会根据存入的数据类型来生成key,如上面存入的数据类型是List<Spittle>,所以key就是spittleList

(2)也可以明确key

  1. @RequestMapping(method = RequestMethod.GET)
  2. public String spittles(Model model) {
  3. model.addAttribute("spittleList",spittleRepository.findSpittles(Long.MAX_VALUE, 20));
  4. return "spittles";
  5. }

(3)也可用map替换model

  1. @RequestMapping(method = RequestMethod.GET)
  2. public String spittles(Map model) {
  3. model.put("spittleList",spittleRepository.findSpittles(Long.MAX_VALUE, 20));
  4. return "spittles";
  5. }

(4)不返回string,直接返回数据类型

  1. @RequestMapping(method = RequestMethod.GET)
  2. public List < Spittle > spittles() {
  3. return spittleRepository.findSpittles(Long.MAX_VALUE, 20));
  4. }

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解析数据

  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  2. <%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
  3. <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
  4.  
  5. <html>
  6. <head>
  7. <title>Spitter</title>
  8. <link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />" >
  9. </head>
  10. <body>
  11. <div class="spittleForm">
  12. <h1>Spit it out...</h1>
  13. <form method="POST" name="spittleForm">
  14. <input type="hidden" name="latitude">
  15. <input type="hidden" name="longitude">
  16. <textarea name="message" cols="80" rows="5"></textarea><br/>
  17. <input type="submit" value="Add" />
  18. </form>
  19. </div>
  20. <div class="listTitle">
  21. <h1>Recent Spittles</h1>
  22. <ul class="spittleList">
  23. <c:forEach items="${spittleList}" var="spittle" >
  24. <li id="spittle_<c:out value="spittle.id"/>">
  25. <div class="spittleMessage"><c:out value="${spittle.message}" /></div>
  26. <div>
  27. <span class="spittleTime"><c:out value="${spittle.time}" /></span>
  28. <span class="spittleLocation">(<c:out value="${spittle.latitude}" />, <c:out value="${spittle.longitude}" />)</span>
  29. </div>
  30. </li>
  31. </c:forEach>
  32. </ul>
  33. <c:if test="${fn:length(spittleList) gt 20}">
  34. <hr />
  35. <s:url value="/spittles?count=${nextCount}" var="more_url" />
  36. <a href="${more_url}">Show more</a>
  37. </c:if>
  38. </div>
  39. </body>
  40. </html>

3.测试

  1. package spittr.web;
  2. import static org.hamcrest.Matchers.*;
  3. import static org.mockito.Mockito.*;
  4. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
  5. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
  6. import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Date;
  10. import java.util.List;
  11.  
  12. import org.junit.Test;
  13. import org.springframework.test.web.servlet.MockMvc;
  14. import org.springframework.web.servlet.view.InternalResourceView;
  15.  
  16. import spittr.Spittle;
  17. import spittr.data.SpittleRepository;
  18. import spittr.web.SpittleController;
  19.  
  20. public class SpittleControllerTest {
  21.  
  22. @Test
  23. public void shouldShowRecentSpittles() throws Exception {
  24. List<Spittle> expectedSpittles = createSpittleList(20);
  25. SpittleRepository mockRepository = mock(SpittleRepository.class);
  26. when(mockRepository.findSpittles(Long.MAX_VALUE, 20))
  27. .thenReturn(expectedSpittles);
  28.  
  29. SpittleController controller = new SpittleController(mockRepository);
  30. MockMvc mockMvc = standaloneSetup(controller)
  31. .setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
  32. .build();
  33.  
  34. mockMvc.perform(get("/spittles"))
  35. .andExpect(view().name("spittles"))
  36. .andExpect(model().attributeExists("spittleList"))
  37. .andExpect(model().attribute("spittleList",
  38. hasItems(expectedSpittles.toArray())));
  39. }
  40.  
  41. @Test
  42. public void shouldShowPagedSpittles() throws Exception {
  43. List<Spittle> expectedSpittles = createSpittleList(50);
  44. SpittleRepository mockRepository = mock(SpittleRepository.class);
  45. when(mockRepository.findSpittles(238900, 50))
  46. .thenReturn(expectedSpittles);
  47.  
  48. SpittleController controller = new SpittleController(mockRepository);
  49. MockMvc mockMvc = standaloneSetup(controller)
  50. .setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
  51. .build();
  52.  
  53. mockMvc.perform(get("/spittles?max=238900&count=50"))
  54. .andExpect(view().name("spittles"))
  55. .andExpect(model().attributeExists("spittleList"))
  56. .andExpect(model().attribute("spittleList",
  57. hasItems(expectedSpittles.toArray())));
  58. }
  59.  
  60. @Test
  61. public void testSpittle() throws Exception {
  62. Spittle expectedSpittle = new Spittle("Hello", new Date());
  63. SpittleRepository mockRepository = mock(SpittleRepository.class);
  64. when(mockRepository.findOne(12345)).thenReturn(expectedSpittle);
  65.  
  66. SpittleController controller = new SpittleController(mockRepository);
  67. MockMvc mockMvc = standaloneSetup(controller).build();
  68.  
  69. mockMvc.perform(get("/spittles/12345"))
  70. .andExpect(view().name("spittle"))
  71. .andExpect(model().attributeExists("spittle"))
  72. .andExpect(model().attribute("spittle", expectedSpittle));
  73. }
  74.  
  75. @Test
  76. public void saveSpittle() throws Exception {
  77. SpittleRepository mockRepository = mock(SpittleRepository.class);
  78. SpittleController controller = new SpittleController(mockRepository);
  79. MockMvc mockMvc = standaloneSetup(controller).build();
  80.  
  81. mockMvc.perform(post("/spittles")
  82. .param("message", "Hello World") // this works, but isn't really testing what really happens
  83. .param("longitude", "-81.5811668")
  84. .param("latitude", "28.4159649")
  85. )
  86. .andExpect(redirectedUrl("/spittles"));
  87.  
  88. verify(mockRepository, atLeastOnce()).save(new Spittle(null, "Hello World", new Date(), -81.5811668, 28.4159649));
  89. }
  90.  
  91. private List<Spittle> createSpittleList(int count) {
  92. List<Spittle> spittles = new ArrayList<Spittle>();
  93. for (int i=0; i < count; i++) {
  94. spittles.add(new Spittle("Spittle " + i, new Date()));
  95. }
  96. return spittles;
  97. }
  98. }

SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model的更多相关文章

  1. 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 ...

  2. SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍

    一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...

  3. 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 ...

  4. 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 ...

  5. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)

    一.显示注册表单 1.访问资源 @Test public void shouldShowRegistration() throws Exception { SpitterRepository mock ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-003-示例项目用到的类及配置文件

    一.配置文件 1.由于它继承AbstractAnnotationConfigDispatcherServletInitializer,Servlet容器会把它当做配置文件 package spittr ...

  7. 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 ...

  8. 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 ...

  9. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

随机推荐

  1. Sql的实际应用

    sql实际应用-递归查询   1.既然要谈到sql,数据库表是必须的   2.数据结构     3.获取某个节点的所有子节点     传统的写法(sql2000) 很麻烦,暂且就不写了     来看看 ...

  2. CSS经典布局-圣杯布局、双飞翼布局

    圣杯布局的来历是2006年发在a list part上的这篇文章:In Search of the Holy Grail · An A List Apart Article圣杯是西方表达“渴求之物&q ...

  3. 可发布指定的ASP.NET页面的插件:LimusicAddin

    涉及到的技术点 VS插件开发.推荐阅读:Visual Studio 2008 可扩展性开发 asp.net 预编译.使用aspnet_comlier.exe(在目录:C:\Windows\Micros ...

  4. Android四大组件之BroadcastReceiver

    什么是BroadcastReceiver? BroadcastReceiver也就是“广播接收者”的意思,顾名思义,它就是用来接收来自系统和应用中的广播. 在Android系统中,广播体现在方方面面, ...

  5. Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)

    Android端的代码: 布局文件:activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/ ...

  6. JavaScript中关于创建对象的笔记

    1,最基本的两种创建对象的方式:构造函数|| 字面量 构造函数: var person = new Object(); person.name = "chen1zee1"; per ...

  7. IO流03_流的分类和概述

    [概述] Java的IO流是实现输入/输出的基础,它可以方便的实现数据的输入/输出操作. Java中把不同的输入/输出源(键盘.文件.网络连接)抽象表述为"流"(Stream). ...

  8. SQL Constraint/Index

    1.SQL Constraint Integrity Constraints are used to apply business rules for the database tables. The ...

  9. linux系统使用密钥登录设置

    使用密钥登录linux的操作步骤(使用putty): 1.用putty远程登录linux服务器,然后使用puttygen生成密钥,将生成的密钥保存,保存私钥将公钥复制保存到linux服务器的autho ...

  10. 前端资源多个产品整站一键打包&包版本管理(一)

    来新公司工作的第五个月.整站资源打包管理也提上了日程. 问题: 首先.什么是整站的打包管理呢? 我们公司的几个重要产品都在同一个webapp里面,但是,不同的开发部门独立开发不同的产品,长期以来,我们 ...