• SpringMVC中的综合案例


    目录

    一.常用注解

     实例:

     二.参数转递

     2.1. 基础类型

    2.2. 复杂类型

    2.3. @RequestParam

    2.4.@PathVariable

    2.5.@RequestBody

     2.6.RequestHeader 

    2.7. 请求方法

    三.返回值

    3.1.void

     3.2.String

    3.3 String+Model

    3.4 ModelAndView

    四、页面跳转

     4.1.转发

    4.2.重定向

    最后SpringMVC综合案例就到这里,祝大家在敲代码的路上一路通畅!

    感谢大家的观看 !


    一.常用注解

    • @RequestMapping:@RequestMapping注解是一个用来处理请求地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。
    • @RequestParam:@RequestParam主要用于将请求参数区域的数据映射到控制层方法的参数上

    • @ModelAttribute:

    1. 绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;

    2. 暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;

    3. 暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。

    • @SessionAttributes:用于将数据存储到会话(Session)中,在多个请求之间共享数据。

    • @RequestBody:用于将方法的返回值直接作为响应体返回给客户端,常用于返回JSON数据。

    • @RequestHeader:使用 @RequestHeader 注解可以获取指定的请求头信息。

    • @PathVariable:该注解请求URI中的模板变量部分到处理器功能处理方法的方法参数上的绑定。

    • @CookieValue:@CookieValue注解主要是将请求的Cookie数据,映射到功能处理方法的参数上。

     实例:

    @RequestMapping:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/{id}", method = RequestMethod.GET, params = "active=true")
    5. public String getActiveUser(@PathVariable("id") int id) {
    6. // ...
    7. }
    8. }

    @RequestParam:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/create", method = RequestMethod.POST)
    5. public String createUser(@RequestParam("user") User user) {
    6. // ...
    7. }
    8. }

    @ModelAttribute:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/create", method = RequestMethod.POST)
    5. public String createUser(@ModelAttribute("user") @Valid User user, BindingResult result) {
    6. // ...
    7. }
    8. }

    @SessionAttributes:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/edit", method = RequestMethod.GET)
    5. public String editUser(@ModelAttribute("user") User user) {
    6. // ...
    7. }
    8. }

    @RequestBody:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/create", method = RequestMethod.POST)
    5. public String createUser(@RequestBody @Valid User user, BindingResult result) {
    6. // ...
    7. }
    8. }

    @RequestHeader:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/info", method = RequestMethod.POST)
    5. public String updateUserInfo(@RequestHeader("Content-Type") String contentType,
    6. @RequestHeader("Authorization") String authorization) {
    7. // ...
    8. }
    9. }

    @PathVariable:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/{id}/info/{name}", method = RequestMethod.GET)
    5. public String getUserInfo(@PathVariable("id") int userId,
    6. @PathVariable("name") String userName) {
    7. // ...
    8. }
    9. }

    @CookieValue:

    1. @Controller
    2. @RequestMapping("/users")
    3. public class UserController {
    4. @RequestMapping(value = "/info", method = RequestMethod.GET)
    5. public String getUserInfo(@CookieValue("sessionId") String sessionId,
    6. @CookieValue("userId") int userId) {
    7. // ...
    8. }
    9. }

     二.参数转递

    配置项目中的 pom.xml 配置文件 ,以下配置(修改)完后的所有配置:

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.example
    6. index
    7. 1.0-SNAPSHOT
    8. war
    9. index Maven Webapp
    10. http://www.example.com
    11. UTF-8
    12. 1.8
    13. 1.8
    14. 3.7.0
    15. 5.0.2.RELEASE
    16. 3.4.5
    17. 5.1.44
    18. 5.1.2
    19. 1.3.1
    20. 2.1.1
    21. 2.4.3
    22. 2.9.1
    23. 3.2.0
    24. 1.7.13
    25. 4.12
    26. 4.0.0
    27. 1.18.2
    28. 1.2
    29. 1.1.2
    30. 5.0.2.RELEASE
    31. 2.9.3
    32. org.springframework
    33. spring-context
    34. ${spring.version}
    35. org.springframework
    36. spring-orm
    37. ${spring.version}
    38. org.springframework
    39. spring-tx
    40. ${spring.version}
    41. org.springframework
    42. spring-aspects
    43. ${spring.version}
    44. org.springframework
    45. spring-web
    46. ${spring.version}
    47. org.springframework
    48. spring-test
    49. ${spring.version}
    50. org.mybatis
    51. mybatis
    52. ${mybatis.version}
    53. mysql
    54. mysql-connector-java
    55. ${mysql.version}
    56. com.github.pagehelper
    57. pagehelper
    58. ${pagehelper.version}
    59. org.mybatis
    60. mybatis-spring
    61. ${mybatis.spring.version}
    62. org.apache.commons
    63. commons-dbcp2
    64. ${commons.dbcp2.version}
    65. org.apache.commons
    66. commons-pool2
    67. ${commons.pool2.version}
    68. org.slf4j
    69. slf4j-api
    70. ${slf4j.version}
    71. org.slf4j
    72. jcl-over-slf4j
    73. ${slf4j.version}
    74. runtime
    75. com.fasterxml.jackson.core
    76. jackson-databind
    77. ${jackson.version}
    78. com.fasterxml.jackson.core
    79. jackson-core
    80. ${jackson.version}
    81. com.fasterxml.jackson.core
    82. jackson-annotations
    83. ${jackson.version}
    84. org.apache.logging.log4j
    85. log4j-api
    86. ${log4j2.version}
    87. org.apache.logging.log4j
    88. log4j-core
    89. ${log4j2.version}
    90. org.apache.logging.log4j
    91. log4j-slf4j-impl
    92. ${log4j2.version}
    93. org.apache.logging.log4j
    94. log4j-web
    95. ${log4j2.version}
    96. runtime
    97. com.lmax
    98. disruptor
    99. ${log4j2.disruptor.version}
    100. junit
    101. junit
    102. ${junit.version}
    103. javax.servlet
    104. javax.servlet-api
    105. ${servlet.version}
    106. provided
    107. org.projectlombok
    108. lombok
    109. ${lombok.version}
    110. provided
    111. org.springframework
    112. spring-webmvc
    113. ${spring.version}
    114. jstl
    115. jstl
    116. ${jstl.version}
    117. taglibs
    118. standard
    119. ${standard.version}
    120. index
    121. src/main/java
    122. **/*.xml
    123. src/main/resources
    124. jdbc.properties
    125. *.xml
    126. org.apache.maven.plugins
    127. maven-compiler-plugin
    128. ${maven.compiler.plugin.version}
    129. ${maven.compiler.source}
    130. ${maven.compiler.target}
    131. ${project.build.sourceEncoding}
    132. org.mybatis.generator
    133. mybatis-generator-maven-plugin
    134. 1.3.2
    135. mysql
    136. mysql-connector-java
    137. ${mysql.version}
    138. true
    139. maven-clean-plugin
    140. 3.1.0
    141. maven-resources-plugin
    142. 3.0.2
    143. maven-compiler-plugin
    144. 3.8.0
    145. maven-surefire-plugin
    146. 2.22.1
    147. maven-war-plugin
    148. 3.2.2
    149. maven-install-plugin
    150. 2.5.2
    151. maven-deploy-plugin
    152. 2.8.2

     2.1. 基础类型

    1. @RequestMapping("/hello1")
    2. public String toHello1(Integer bid,String bname){
    3. log.info(">>>> 基础类型+String传参:{},{}",bid,bname);
    4. return "index";
    5. }

     新建一个paramController类:

    1. package com.junlinyi.web;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. /**
    6. * @author 君临沂
    7. * @site www.junlinyi.com
    8. * @company 君氏集团
    9. * @create 2023-09-05-14:44
    10. */
    11. @Slf4j
    12. @Controller
    13. @RequestMapping("/param")
    14. public class ParamController {
    15. @RequestMapping("/hello1")
    16. public String index(String bname,Integer bid){
    17. // System.out.println("刘三金去拿奶茶喽。。。");
    18. log.info("简单类型参数:bname:{},bid:{}",bname,bid);
    19. return "index";
    20. }
    21. }

      index.jsp:

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. Title
    3. 看你不爽哦

    效果显示:

     

    2.2. 复杂类型

    1. @RequestMapping("/hello2")
    2. public String toHello2(Book book,
    3. HttpServletRequest req,
    4. HttpServletResponse resp,
    5. HttpSession session){
    6. System.out.println(book);
    7. log.info(">>>> HttpServletRequest/HttpServletResponse/HttpSession等等传参:{}", req.getRequestURI());
    8. return "index";
    9. }

    在paramController类中添加以下方法:

    1. @RequestMapping("/hello2")
    2. public String hello2(Book book, HttpServletRequest request){
    3. // System.out.println("靓仔来了喽。。。");
    4. //servlet参数获取方式
    5. log.info("复杂类型参数:bname:{},bid:{}",
    6. request.getParameter("bname"),
    7. request.getParameter("bid"));
    8. //复杂传参
    9. log.info("复杂类型参数:book:{}",
    10. book.toString());
    11. // fail..error warning info debug
    12. return "index";
    13. }

    效果演示:

    2.3. @RequestParam

    1. @RequestMapping("/hello3")
    2. public String toHello3(@RequestParam Integer bid,
    3. @RequestParam(required = false,value = "price") Integer bookPrice,
    4. @RequestParam("bookName") String bname){
    5. log.info(">>>> 使用@RequestParam注解传递参数:{},{},{}", bid,bname,bookPrice);
    6. return "index";
    7. }

    在paramController类中添加以下方法:

    1. @RequestMapping("/hello3")
    2. public String hello3(
    3. @RequestParam String bname,
    4. @RequestParam(required = false) Integer bid){
    5. // System.out.println("靓仔来了喽。。。");
    6. log.info("@requestParam参数:bname:{},bid:{}",bname,bid);
    7. // fail..error warning info debug
    8. return "index";
    9. }

     注意:

    演示效果:

    根据条件输入 正确地址:

     

     

    2.4.@PathVariable

    1. @RequestMapping("/hello4/{bid}")
    2. public String toHello4(@PathVariable("bid") Integer bid){
    3. log.info(">>>> 使用@PathVariable注解传递参数:{}", bid);
    4. return "index";
    5. }

    在paramController类中添加以下方法:

    1. @RequestMapping("/hello4/{bid}")
    2. public String hello4(@PathVariable("bid") Integer bid){
    3. // System.out.println("靓仔来了喽。。。");
    4. log.info("@requestParam参数:bid:{}",bid);
    5. // fail..error warning info debug
    6. return "index";
    7. }

     演示效果:

     

    2.5.@RequestBody

    在进行@RequestBody传参前先要在pom.xml传入依赖,如下:

    1. 2.9.3
    2. com.fasterxml.jackson.core
    3. jackson-databind
    4. ${jackson.version}
    5. com.fasterxml.jackson.core
    6. jackson-core
    7. ${jackson.version}
    8. com.fasterxml.jackson.core
    9. jackson-annotations
    10. ${jackson.version}

    这里我们需要在Eolink Apikit软件工具上进行测试请求地址:

    按照以下步骤把参数填写好,query参数是往域名链接添加属性,如下:

    然后介绍完Query参数后就开始添加我们的请求体参数,如下:

     2.6.RequestHeader 

    1. @RequestMapping("/hello7")
    2. public String toHello7(Book book, @RequestBody Map map, @RequestHeader("jwt") String jwt){
    3. System.out.println(map);
    4. System.out.println(book);
    5. System.out.println(jwt);
    6. return "index";
    7. }

    方法代码如下:

    1. @RequestMapping("/hello7")
    2. public String hello7(@RequestHeader("jwt") String jwt){
    3. // System.out.println("靓仔来了喽。。。");
    4. log.info("@RequestHeader参数:jwt:{}",jwt);
    5. // fail..error warning info debug
    6. return "index";
    7. }
    8. @RequestMapping("/hello8")
    9. public String hello8(Book book,
    10. @RequestBody Map map,
    11. @RequestHeader("jwt") String jwt){
    12. // System.out.println(""靓仔来了喽。。。");
    13. log.info("Book:Book:{}",book.toString());
    14. log.info("@RequestBody参数:Map:{}",map);
    15. log.info("@RequestHeader参数:jwt:{}",jwt);
    16. // fail..error warning info debug
    17. return "index";
    18. }

    代码完成之后我们需要在Eolink中进行头部请求参数配置,如下: 

    然后进行测试结果如下:

    最后我们再来测试以下方法八,个人配置如下:

     

    2.7. 请求方法

    请求方法有:

    RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping

    他们之间的关系为:

    RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping

    RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping的区别

    RequestMapping不安全,且不具备标识意义。

    测试方法如下:

    1. //查询的请求
    2. @GetMapping
    3. public String type1(){
    4. System.out.println("@GetMapping:对应查询请求");
    5. return "index";
    6. }
    7. //新增的请求
    8. @PostMapping
    9. public String type2(){
    10. System.out.println("@PostMapping:对应新增请求");
    11. return "index";
    12. }
    13. //修改的请求
    14. @PutMapping
    15. public String type3(){
    16. System.out.println("@PutMapping:对应修改请求");
    17. return "index";
    18. }
    19. //删除的请求
    20. @DeleteMapping
    21. public String type4(){
    22. System.out.println("@DeleteMapping:对应删除请求");
    23. return "index";
    24. }
    25. //RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping
    26. //RequestMapping不安全,且不具备标识意义

    依次进行请求,请求的方式不同会进行不同的请求注解,具体操作与效果如下:

    三.返回值

    创建一个ResponseUtil工具类,辅助完成测试代码,如下

    1. package com.junlinyi.utils;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import javax.servlet.http.HttpServletResponse;
    4. import java.io.PrintWriter;
    5. public class ResponseUtil {
    6. public static void write(HttpServletResponse response,Object o)throws Exception{
    7. response.setContentType("text/html;charset=utf-8");
    8. PrintWriter out=response.getWriter();
    9. out.println(o.toString());
    10. out.flush();
    11. out.close();
    12. }
    13. public static void writeJson(HttpServletResponse response,Object o)throws Exception{
    14. ObjectMapper om = new ObjectMapper();
    15. // om.writeValueAsString(o)代表了json串
    16. write(response, om.writeValueAsString(o));
    17. }
    18. }

    创建一个ReturnController类,来进行方法的请求测试(包含关于返回值的所以方法)。如下: 

    1. package com.junlinyi.web;
    2. import com.junlinyi.utils.ResponseUtil;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.ui.Model;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.ResponseBody;
    7. import org.springframework.web.servlet.ModelAndView;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.util.HashMap;
    11. import java.util.Map;
    12. /**
    13. * @author 君临沂
    14. * @site www.junlinyi.com
    15. * @company 君氏集团
    16. * @create 2023-09-05-14:44
    17. */
    18. @Controller
    19. @RequestMapping("/rs")
    20. public class ReturnController {
    21. @RequestMapping("/test01")
    22. public void Test01(HttpServletResponse response) throws Exception {
    23. Map map = new HashMap();
    24. map.put("id",1);
    25. map.put("晚安","亲爱的梦");
    26. map.put("梦","增加成功!!!");
    27. ResponseUtil.writeJson(response,map);
    28. }
    29. @ResponseBody
    30. @RequestMapping("/test02")
    31. public Map Test02(HttpServletResponse response) throws Exception {
    32. Map map = new HashMap();
    33. map.put("id",1);
    34. map.put("晚安","亲爱的梦");
    35. map.put("梦","增加成功!!!");
    36. return map;
    37. }
    38. @RequestMapping("/test03")
    39. public String Test03() {
    40. return "index02";
    41. }
    42. @RequestMapping("/test04")
    43. public String Test04(
    44. Model model,
    45. HttpServletRequest request) {
    46. model.addAttribute("Nobo1","他字字句句喜欢你");
    47. request.setAttribute("Nobo1","我曾经也想过一了百了");
    48. return "index02";
    49. }
    50. @RequestMapping("/test05")
    51. public ModelAndView Test05() {
    52. ModelAndView modelAndView = new ModelAndView();
    53. modelAndView.addObject("Nobo2","他字字句句喜欢你");
    54. modelAndView.addObject("Nobo2","我曾经也想过一了百了");
    55. modelAndView.setViewName("index02");
    56. return modelAndView;
    57. }
    58. }

    创建一个index.jsp页面进行显示测试,如下:

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. Title
    3. 字字句句喜欢你

    4. 歌词上句: ${Nobo1}
    5. 歌词下句: ${Nobo2}

    3.1.void

    处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void。

     3.2.String

    3.3 String+Model

    打开浏览器输入相对应地址,结果如下:

    Model测试:

    将test03换成test04接着输出即可:

    3.4 ModelAndView

    打开浏览器输入相应请求地址,结果如下:

    四、页面跳转

    创建一个PathConterller测试类,进行页面跳转的各种方法测试,代码如下: 

    1. package com.junlinyi.web;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. import org.springframework.web.bind.annotation.ResponseBody;
    5. import javax.servlet.http.HttpServletResponse;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8. /**
    9. * @author 君临沂
    10. * @site www.junlinyi.com
    11. * @company 君氏集团
    12. * @create 2023-09-06-16:19
    13. */@Controller
    14. @RequestMapping("/ts")
    15. public class PathConterller {
    16. @ResponseBody
    17. @RequestMapping("/test02")
    18. public Map Test02(HttpServletResponse response) throws Exception {
    19. Map map = new HashMap();
    20. map.put("id",1);
    21. map.put("晚安","亲爱的梦");
    22. map.put("梦","增加成功!!!");
    23. return map;
    24. }
    25. //返回值中有转发(forward)和重定向(redirect)这两种跳转方式将会绕开视图解析器的前缀和后缀
    26. //转发到(当前类)的某一个方法
    27. @RequestMapping("/Demo01")
    28. public String Demo01(){
    29. System.out.println("请求地址:Demo01");
    30. System.out.println("转发到(当前类)的某一个方法");
    31. return "forward:test02";
    32. }
    33. //转发到(其他类)的某一个方法
    34. @RequestMapping("/Demo02")
    35. public String Demo02(){
    36. System.out.println("请求地址:Demo02");
    37. System.out.println("转发到(其他类)的某一个方法");
    38. return "forward:/rs/test04";
    39. }
    40. //重定向到(其他类)的某一个方法
    41. @RequestMapping("/Demo03")
    42. public String Demo03(){
    43. System.out.println("请求地址:Demo03");
    44. System.out.println("重定向到(其他类)的某一个方法");
    45. return "redirect:test02";
    46. }
    47. //重定向到(其他类)的某一个方法
    48. @RequestMapping("/Demo04")
    49. public String Demo04(){
    50. System.out.println("请求地址:Demo04");
    51. System.out.println("重定向到(其他类)的某一个方法");
    52. return "redirect:/rs/test04";
    53. }
    54. }

     4.1.转发

    它相当于“request.getRequestDispatcher("url").forward(request,response)”。使用转发,既可以转发到jsp, 也可以转发到其他的控制器方法。

     打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo02,结果如下:

    4.2.重定向

    打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo04,结果如下:

    最后SpringMVC综合案例就到这里,祝大家在敲代码的路上一路通畅!

    感谢大家的观看 !

  • 相关阅读:
    Realtime Data Processing at Facebook
    Android 13 隐私权限和安全变更之通知
    Linux的TCP连接问题解决调优观察
    网络安全实战:剖析ThinkPHP 5.1.X反序列化漏洞
    WPF数据模板
    vmware入门之运行RHEL虚拟机
    标准C++中string类函数总结
    力扣(LeetCode)260. 只出现一次的数字 III(2022.09.17)
    pytorch加载的cifar10数据集,到底有没有经过归一化
    1204. 最后一个能进入电梯的人
  • 原文地址:https://blog.csdn.net/m0_74915426/article/details/132723361