SpringMVC 视图方法的参数, 已经在这个文章中写得非常清楚了, 链接为 https://www.cnblogs.com/morethink/p/8028664.html

这篇文章做一些补充. 被@RequestMapping 注解的方法的签名非常灵活, Spring会自动注入各种类型的实参, 另外返回值类型也可以有多种选择.

=============================
View 方法的形式参数
=============================
View 形参种类和数量可以非常多, 这里仅列几种重要的类型:
1. ServletRequest 或 HttpServletRequest 类型的形参, 在运行时Spring MVC会自动注入 request 实参.
2. HttpSession 类型的形参, 在运行时Spring MVC会自动注入 session 实参.
3. java.util.Map/org.springframework.io.Model/org.springframework.ui.ModelMap 类型的参数, 该参数会被Spring自动注入, 我们可以通过该参数进一步控制视图层模型(向FreeMarker模版传参). 推荐使用 Model 或者 ModelMap 类型, 它们比 java.util.Map 更好用.
4. 处理 request 模版变量的参数, 这类参数需要加上 @PathVariable 注解.
5. 处理 request header的参数, 这类参数需要加上 @CookieValue 或 @RequestHeader 注解.
6. 处理 request paramater的参数, 这类参数需要加上 @RequestParam 注解, 该注解其实是调用 Request.getParameter() 获取request 参数值, 它既可获取GET的 queryString, 也可以POST的body data值. 但需要说明的是该注解修饰的参数只能是简单类型, 不能是复杂的用户定义类.
7. 处理 request body的参数, 这类参数需要加上 @RequestBody 注解, 该注解多用于 Restful 接口.
8. 处理 request body的参数, 也可以使用 @ModelAttribute 注解, @ModelAttribute 用法较复杂, 参见 https://www.cnblogs.com/morethink/p/8028664.html

-----------------------------------
@PathVariable示例
-----------------------------------
@PathVariable注解虽然可以加上required参数, 但即使加了 required=false 的话, 对应的参数也不能缺省, 也许Spring未来版本会改进点吧.
测试url为:
http://localhost:8080/pathVariableDemo1/1111/harry

    @RequestMapping("/pathVariableDemo1/{userId}/{userName}")
@ResponseBody
public String pathVariableDemo(HttpSession session, @PathVariable String userId, @PathVariable String userName) {
return "userId:"+userId+", userName:"+userName;
}

-----------------------------------
@RequestParam 示例1
-----------------------------------
@RequestParam, 可以加上 required 参数, 并可以指定缺省值.
测试url为:
http://localhost:8080/requestParamDemo?userId=1111&userName=harry
http://localhost:8080/requestParamDemo?userId=1111&userName=
http://localhost:8080/requestParamDemo?userId=1111

    @RequestMapping("/requestParamDemo")
@ResponseBody
public String requestParamDemo(HttpSession session,
@RequestParam(name = "userId", required = true) String userId,
@RequestParam(name = "userName", required = false, defaultValue = "unamed") String userName) {
return "userId:" + userId + ", userName:" + userName;
}

-----------------------------------
@RequestParam 示例2
-----------------------------------
@RequestParam 也可以注解数组或List容器类型的参数
测试url为:
http://localhost:8080/requestParamDemo2?userId=1111&roles=Admin,User
http://localhost:8080/requestParamDemo2?userId=1111

    @RequestMapping("/requestParamDemo2")
@ResponseBody
public String requestParamDemo2(HttpSession session,
@RequestParam(name = "userId", required = true) String userId,
@RequestParam(name = "roles", required = false, defaultValue = "Guest,UnknownRole") List<String> roles) {
return "userId:" + userId + ", roles:" + String.join(",", roles);
}

============================= 
View 方法的返回类型
============================= 
Spring MVC的view函数支持多种返回值类型:
1. [非restful]返回值类型为 String 时: 返回值即为目标视图名, 完整的目标视图是: prefix前缀+返回值字符串+suffix后缀名.
2. 返回值类型为 void/Map/Model/ModelMap 时: 真正的目标视图是: prefix前缀+方法名称+suffix后缀名. 
3. 返回值类型为 ModelAndView 时: 真正的视图是通过 ModelAndView 对象设置的. 
4. [restful]返回值类型为 String 时: 直接将string返回给 API 客户端
5. [restful]返回值类型为 ResponseEntity<T> 时: 将返回对象json序列化后返回给API客户端.

============================= 
View 方法如何向FreeMarker模版传值?
============================= 
我们至少有两个方式可以向FreeMarker模版传值:
1. 将任意类型对象压到Model/ModelMap/ModelAndView/Map中, 可以完成简单值/自定义对象/集合等的传值. 
2. 通过 session.setAttribute() 或者 request.setAttribute(), 同样, 可以完成简单值/自定义对象/集合等的传值. 
如果上面两个方式同时被使用, 优先取Model和ModelMap的传值(Model和ModelMap是同一个东西,谁最后赋值的就取谁的), 然后是request, 最后是从session中获取.

request.getSession().setAttribute("test", "haiwei2Session");
request.setAttribute("test", "haiwei1request"); 
map.addAttribute("test", "haiweiModelMap");
model.addAttribute("test", "haiweiModel");

=============================
页面跳转
=============================
常用的页面跳转方式有:
1. 视图方法返回类型为 ModelAndView, 直接在 ModelAndView 返回值中设置目标页面
2. 视图方法返回类型为 String, 直接用返回值确定目标页面
3. 视图方式返回值类似于 "redirect:another_view", 重定向至 another_view 视图取进一步处理
4. 视图方式返回值类似于 "forward:another_view", 请求转发至 another_view 视图取进一步处理

redirect(重定向) 和 forward(请求转发) 简单区别:
redirect 相当于有两次request. 要向给第二次request传值, 只能通过url传参方式为第二次request传值. 另外, 最后浏览器的url地址是重定向后的地址,
forward 可以看作只有一次服务器和浏览器之间的 request. 请求转发全过程都在服务器端完成, 所以在转发之前, 可以通过request.setAttribute() 传值. 另外, 最后浏览器的url地址是最初的请求地址.

@GetMapping("index/")
public String index() {
return "redirect:/form";
} @GetMapping("index2/")
public String index2() {
return "forward:/form2";
}

=============================
参考
=============================
1. springMVC 返回类型选择 以及 SpringMVC中model,modelMap.request,session取值顺序 https://blog.csdn.net/zb0567/article/details/7921155
2. @RequestParam @RequestBody @PathVariable 等参数绑定注解详解 https://blog.csdn.net/walkerJong/article/details/7946109
3. Spring MVC@RequestMapping 方法所支持的参数类型和返回类型详解 https://www.tianmaying.com/tutorial/request-mapping-parameter-type
4. SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解——跟着开涛学SpringMVC http://jinnianshilongnian.iteye.com/blog/1705701
5. freemarker迭代list、map等常规操作 https://blog.csdn.net/wickedvalley/article/details/65937189
6. http://www.cnblogs.com/Hymen/p/3296952.html
7. https://blog.csdn.net/xiangwanpeng/article/details/53069533
8. https://www.jianshu.com/p/b4b2c38d31ee

SpringBoot系列: Spring MVC视图方法的补充的更多相关文章

  1. SpringBoot集成Spring MVC视图

    SpringBoot在springmvc的视图解析器方面就默认集成了ContentNegotiatingViewResolver和BeanNameViewResolver,在视图引擎上就已经集成自动配 ...

  2. 【深度分析】:阿里,腾讯面试题 SpringBoot整合Spring MVC

    Java学习总结 SpringBoot整合Spring MVC 1.SpringMVC概述 MVC(Model–view–controller)是软件工程中的一种软件架构模式,基于此模式把软件系统分为 ...

  3. SpringMVC(八):使用Servlet原生API作为Spring MVC hanlder方法的参数

    在SpringMVC开发中,是有场景需要在Handler方法中直接使用ServletAPI. 在Spring MVC Handler的方法中都支持哪些Servlet API作为参数呢? --Respo ...

  4. spring mvc: 参数方法名称解析器(用参数来解析控制器下的方法)MultiActionController/ParameterMethodNameResolver/ControllerClassNameHandlerMapping

    spring mvc: 参数方法名称解析器(用参数来解析控制器下的方法)MultiActionController/ParameterMethodNameResolver/ControllerClas ...

  5. spring mvc: 属性方法名称解析器(多动作控制器)MultiActionController/ControllerClassNameHandlerMapping/PropertiesMethodNameResolver

    spring mvc: 属性方法名称解析器(多动作控制器) 加入控制器是StudentContrller.java,里面有3个方法 index,add,remove 那么访问地址是: http://l ...

  6. 2分钟在eclipse下使用SpringBoot搭建Spring MVC的WEB项目

    1. 首先用eclipse创建一个maven工程, 普通maven工程即可 2. 修改pom如下: <?xml version="1.0" encoding="UT ...

  7. Spring MVC视图解析器

    Spring MVC提供的视图解析器使用ViewResolver进行视图解析,实现浏览器中渲染模型.ViewResolver能够解析JSP.Velocity模板.FreeMarker模板和XSLT等多 ...

  8. SpringBoot系列: Spring支持的异常处理方式

    ===================================视图函数返回 status code 的方式===================================Spring 有 ...

  9. Spring MVC的方法返回值和参数传递

    1. SpringMVC方法的返回值类型 3.1String类作为返回值 3.1.1Controller层 /** * 返回值类型为String时,一般用于返回视图名称 * 1.当方法返回值为null ...

随机推荐

  1. Equivalent Sets HDU - 3836 (Tarjan)

    题目说给出一些子集,如果A是B的子集,B是A的子集,那么A和B就是相等的,然后给出n个集合m个关系,m个关系表示u是v的子集,问你最小再添加多少个关系可以让这n个集合都是相等的 如果这n个几个都是互相 ...

  2. hdu 2859 Phalanx (最大对称子矩阵)

    Problem Description Today is army day, but the servicemen are busy with the phalanx for the celebrat ...

  3. 状压DP总结

    状态压缩就是将一行的状态压成一个二进制数,这个数的二进制形式反映了这一行的情况 比如0100111的意义为:这一排的第一个数没被使用,第二个被占用了,第三四个没被占用,第五六七个被占用 我们知道位运算 ...

  4. 使用Docker Swarm搭建分布式爬虫集群

    https://mp.weixin.qq.com/s?__biz=MzIxMjE5MTE1Nw==&mid=2653195618&idx=2&sn=b7e992da6bd1b2 ...

  5. BZOJ3881 Divljak

    解:对被包含的那些串建AC自动机. 每次加一个串,就在AC自动机上面跑,可知能够跑到一些节点. 这些节点都是一些前缀的形式,我们跳fail树就是跳后缀,这样就能够得到所有能匹配的子串. 我们分别对AC ...

  6. A1034. Head of a Gang

    One way that the police finds the head of a gang is to check people's phone calls. If there is a pho ...

  7. [agc016B][Colorful Hats]

    题目链接 思路 首先,如果没人说谎那么序列中肯定只有一大一小两种数,假设大的数为x,小的数为y.因为对于每个人只有两种情况,要么自己与除自己外的某个人拥有相同的颜色,此时总颜色数就是这个人所能看到的颜 ...

  8. Django 配置数据库

    Django提到配置那大多数都是在settings.py配置文件 在配置文件里的 DATABASES 内进行设置 # 数据库配置 DATABASES = { #连接mysql 'default': { ...

  9. Vue+koa2开发一款全栈小程序(4.Koa入门)

    1.Koa是什么? 基于nodejs平台的下一代web开发框架 1.Express原班人马打造,更精简 2.Async+await处理异步 3.洋葱圈型的中间件机制 新建一个koa项目 1.打开cmd ...

  10. bash 5

    1)bash支持一维数组(不支持多维数组),并且没有限定数组的大小. 类似于 C 语言,数组元素的下标由 0 开始编号.获取数组中的元素要 利用下标,下标可以是整数或算术表达式,其值应大于或等于 0. ...