记录常用的Web服务实现方式,常用注解如下图源码:
image.png

添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. 本文依赖SpringBoot版本信息:
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.5.0</version>
  10. <relativePath/> <!-- lookup parent from repository -->
  11. </parent>

各种响应

  1. /**
  2. * HTTP的所有请求方式: GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
  3. *
  4. * @param request 注入
  5. * @return 返回字符串
  6. */
  7. @RequestMapping("all")
  8. public String all(HttpServletRequest request) {
  9. log.info("request:{}", JSONUtil.toJsonStr(request));
  10. return "all";
  11. }
  12. @Data
  13. @Builder //支持构建者模式
  14. public static class R<T> implements Serializable {
  15. protected Integer code;
  16. protected String msg;
  17. protected T data;
  18. /**
  19. * 响应状态码
  20. */
  21. interface Code {
  22. int SUCCESS_CODE = 1;
  23. int FAIL_CODE = 0;
  24. }
  25. /**
  26. * 响应状态码
  27. */
  28. interface Message {
  29. String SUCCESS_MESSAGE = "成功";
  30. String FAIL_MESSAGE = "失败";
  31. }
  32. public static <T> R<T> ok() {
  33. return new R<>(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, null);
  34. }
  35. }
  36. /**
  37. * 响应自定义Bean
  38. *
  39. * @return R
  40. * @see R
  41. */
  42. @RequestMapping("returnR")
  43. public R<String> returnR() {
  44. log.warn("returnR");
  45. return R.ok();
  46. }
  47. /**
  48. * 响应ResponseEntity
  49. *
  50. * @return ResponseEntity
  51. * @see ResponseEntity
  52. */
  53. @RequestMapping("returnResponseEntity")
  54. public ResponseEntity<String> returnResponseEntity() {
  55. log.warn("returnResponseEntity");
  56. return ResponseEntity.ok("SUCCESS");
  57. }
  58. /**
  59. * 响应自定义ResponseEntity
  60. *
  61. * @return ResponseEntity
  62. * @see ResponseEntity
  63. */
  64. @RequestMapping("returnResponseEntityHttpStatus")
  65. public ResponseEntity<String> returnResponseEntityHttpStatus() {
  66. log.warn("returnResponseEntityHttpStatus");
  67. return ResponseEntity.status(HttpStatus.BAD_REQUEST)//400
  68. .build();
  69. }
  70. /**
  71. * 注解实现响应自定义HTTP状态码
  72. *
  73. * @return ResponseEntity
  74. */
  75. @ResponseStatus(HttpStatus.BAD_REQUEST)
  76. @RequestMapping("returnResponseStatus")
  77. public String returnResponseStatus() {
  78. log.warn("returnResponseStatus");
  79. return "returnResponseStatus";
  80. }

关于自定义响应对象,示例如下:

  1. package com.initit.sbweb.controller;
  2. import cn.hutool.db.PageResult;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.fasterxml.jackson.annotation.JsonFormat;
  5. import io.swagger.annotations.ApiModel;
  6. import io.swagger.annotations.ApiModelProperty;
  7. import lombok.AllArgsConstructor;
  8. import lombok.Builder;
  9. import lombok.Data;
  10. import lombok.NoArgsConstructor;
  11. import java.io.Serializable;
  12. import java.time.LocalDateTime;
  13. /**
  14. * Result
  15. * 统一响应解构
  16. */
  17. @Data
  18. @AllArgsConstructor
  19. @NoArgsConstructor
  20. @Builder //支持构建者模式
  21. @ApiModel(value = "R对象", description = "统一响应对象")
  22. public class R<T> implements Serializable {
  23. @ApiModelProperty(value = "状态码 0失败 1成功", required = true)
  24. protected Integer code;
  25. @ApiModelProperty(value = "提示信息")
  26. protected String msg;
  27. @ApiModelProperty(value = "数据")
  28. protected T data;
  29. @ApiModelProperty(value = "服务器响应时间 yyyy-MM-dd HH:mm:ss GMT+8", required = true)
  30. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  31. protected LocalDateTime responseTime = LocalDateTime.now();
  32. /**
  33. * 响应状态码
  34. */
  35. interface Code {
  36. int SUCCESS_CODE = 1;
  37. int FAIL_CODE = 0;
  38. }
  39. /**
  40. * 响应状态码
  41. */
  42. interface Message {
  43. String SUCCESS_MESSAGE = "成功";
  44. String FAIL_MESSAGE = "失败";
  45. }
  46. //构造函数
  47. private R(Integer code, String msg, T data) {
  48. this.code = code;
  49. this.msg = msg;
  50. this.data = data;
  51. }
  52. //----------- 封装常用方法-----------------
  53. public static <T> R<T> result(Integer code, String message, T data) {
  54. return new R<T>(code, message, data);
  55. }
  56. /**
  57. * 封装特有的boolean类型
  58. * 根据boolean类型自动封装返回类型
  59. *
  60. * @param result 结果
  61. * @return R
  62. */
  63. public static R<Boolean> result(Boolean result) {
  64. if (result) {
  65. return ok();
  66. } else {
  67. return fail();
  68. }
  69. }
  70. public static <T> R<T> ok() {
  71. return result(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, null);
  72. }
  73. public static <T> R<T> ok(T data) {
  74. return result(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, data);
  75. }
  76. public static <T> R<T> ok(String message, T data) {
  77. return result(Code.SUCCESS_CODE, message, data);
  78. }
  79. public static <T> R<T> fail() {
  80. return result(Code.FAIL_CODE, Message.FAIL_MESSAGE, null);
  81. }
  82. public static <T> R<T> fail(T data) {
  83. return result(Code.FAIL_CODE, Message.FAIL_MESSAGE, data);
  84. }
  85. public static <T> R<T> fail(String message, T data) {
  86. return result(Code.FAIL_CODE, message, data);
  87. }
  88. //支持各种分页框架 需要引入Mybatis-Plus框架
  89. // public static <T> R<PageResult<T>> ok(IPage<T> page) {
  90. // return result(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, PageResult.page(page));
  91. // }
  92. public static <T> R<T> okMsg(String msg) {
  93. return R.ok(msg, null);
  94. }
  95. public static <T> R<T> failMsg(String msg) {
  96. return R.fail(msg, null);
  97. }
  98. }

HTTP各种请求方式

  1. /**
  2. * GET请求
  3. *
  4. * @param str url变量,字符串类型参数
  5. * @param num url变量, 数字类型参数
  6. * @param param1 path参数1
  7. * @param param3 path参数2,测试别名
  8. * @return 返回字符串
  9. */
  10. @GetMapping("get/{param1}/{param2}/test")
  11. public String get(String str,
  12. Long num,
  13. @PathVariable String param1,
  14. @PathVariable("param2") String param3
  15. ) {
  16. log.warn("str:{},num:{},param1:{},param2:{}", str, num, param1, param3);
  17. return "get";
  18. }
  19. /**
  20. * POST请求,地址变量
  21. *
  22. * @param str url变量,字符串类型参数
  23. * @param num url变量, 数字类型参数
  24. * @param pathVariable path变量
  25. * @return 返回字符串
  26. */
  27. @PostMapping("postPathVariable/{pathVariable}")
  28. public String postPathVariable(
  29. String str,
  30. Long num,
  31. @PathVariable String pathVariable
  32. ) {
  33. log.warn("str:{},num:{}", str, num);
  34. log.warn("pathVariable:{}", pathVariable);
  35. return "postPathVariable";
  36. }
  37. /**
  38. * POST请求,body转为JSON对象
  39. *
  40. * @param map json字符串转为map
  41. * @param request 请求对象
  42. * @return 返回字符串
  43. */
  44. @PostMapping("postRequestBodyJson")
  45. public String postRequestBodyJson(
  46. @RequestBody Map<String, Object> map,
  47. HttpServletRequest request
  48. ) {
  49. log.warn("map:{}", JSONUtil.toJsonStr(map));
  50. log.warn(request.getRequestURI());
  51. return "postRequestBodyJson";
  52. }
  53. /**
  54. * POST请求,body转为字符串
  55. *
  56. * @param txt 字符串请求,使用js/xml/html等
  57. * @param request 请求对象
  58. * @return 返回字符串
  59. */
  60. @PostMapping("postRequestBodyStr")
  61. public String postRequestBodyStr(
  62. @RequestBody String txt,
  63. HttpServletRequest request
  64. ) {
  65. log.warn("txt:{}", txt);
  66. log.warn(request.getRequestURI() + " " + request.getContentType());
  67. return "postRequestBodyStr";
  68. }
  69. /**
  70. * POST 表单提交
  71. *
  72. * @param str 表单数据,文本类型
  73. * @param file 表单数据,文件类型
  74. * @return 返回字符串类型
  75. */
  76. @PostMapping("postFormData")
  77. public String postFormData(
  78. String str,
  79. MultipartFile file
  80. ) {
  81. log.warn("str:{}", str);
  82. log.warn("file:{}--{}--{}--{}--{}",
  83. JSONUtil.toJsonStr(file), file.getOriginalFilename(), file.getName(), file.getSize(), file.getContentType());
  84. return "postFormData";
  85. }
  86. /**
  87. * POST请求,多文件上传
  88. *
  89. * @param files 多个文件
  90. * @return 返回字符串
  91. */
  92. @PostMapping("postFiles")
  93. public String postFiles(List<MultipartFile> files) {
  94. log.warn("files:{}", files.size());
  95. for (MultipartFile file : files) {
  96. log.warn("file:{}--{}--{}--{}--{}",
  97. JSONUtil.toJsonStr(file), file.getOriginalFilename(), file.getName(), file.getSize(), file.getContentType());
  98. }
  99. return "postFiles";
  100. }
  101. /**
  102. * DELETE请求
  103. *
  104. * @param str url参数,字符串类型
  105. * @param num url参数,数字类型
  106. * @param pathVariable path参数
  107. * @return 返回字符串
  108. */
  109. @DeleteMapping("delete/{pathVariable}")
  110. public String delete(String str,
  111. Long num,
  112. @PathVariable String pathVariable
  113. ) {
  114. log.warn("str:{},num:{}", str, num);
  115. log.warn("pathVariable:{}", pathVariable);
  116. return "delete";
  117. }
  118. /**
  119. * PUT请求
  120. *
  121. * @param str url参数,字符串类型
  122. * @param num url参数,数字类型
  123. * @param pathVariable path参数
  124. * @return 返回字符串
  125. */
  126. @PutMapping("put/{pathVariable}")
  127. public String put(
  128. String str,
  129. Long num,
  130. @PathVariable String pathVariable
  131. ) {
  132. log.warn("str:{},num:{}", str, num);
  133. log.warn("pathVariable:{}", pathVariable);
  134. return "put";
  135. }
  136. /**
  137. * PATH请求
  138. *
  139. * @return 返回字符串
  140. */
  141. @PatchMapping("patch")
  142. public String put() {
  143. log.warn("patch");
  144. return "patch";
  145. }

请求头

  1. /**
  2. * 请求头示例
  3. *
  4. * @param str 请求头数据,字符串类型,测试别名
  5. * @param num 请求头数据,数字类型
  6. * @return 字符串类型
  7. */
  8. @GetMapping("requestHeader")
  9. public String requestHeader(@RequestHeader("headerStr") String str, @RequestHeader Integer num) {
  10. log.warn("str:{},num:{}", str, num);
  11. return "requestHeader";
  12. }
  13. /**
  14. * 请求头示例,自定义模式获取
  15. *
  16. * @param request 请求对象
  17. * @return 字符串类型
  18. */
  19. @GetMapping("requestHeaderRequest")
  20. public String requestHeaderRequest(HttpServletRequest request) {
  21. String str = request.getHeader("str");
  22. String num = request.getHeader("num");
  23. log.warn("str:{},num:{}", str, num);
  24. return "requestHeaderRequest";
  25. }

Cookies

  1. /**
  2. * 设置cookie
  3. *
  4. * @param response 响应对象
  5. * @return 字符串类型
  6. */
  7. @GetMapping("setCookies")
  8. public String setCookies(HttpServletResponse response) {
  9. Cookie cookie = new Cookie("cookieStr", "test");
  10. //设置过期时间 7天过期
  11. cookie.setMaxAge(7 * 24 * 60 * 60);
  12. //Https 安全cookie 该Cookie将无法在Http连接中传输,只能是Https连接中传输
  13. // cookie.setSecure(true);
  14. response.addCookie(cookie);
  15. log.warn("setCookies");
  16. return "setCookies";
  17. }
  18. /**
  19. * 获取cookie
  20. *
  21. * @param request 请求对象
  22. * @return 字符串类型
  23. */
  24. @GetMapping("getCookiesRequest")
  25. public String getCookiesRequest(HttpServletRequest request) {
  26. Cookie[] cookies = request.getCookies();
  27. log.warn("cookies:{}", cookies.length);
  28. for (Cookie cookie : cookies) {
  29. log.warn("cookie:{}", cookie);
  30. }
  31. return "getCookiesRequest";
  32. }
  33. /**
  34. * 获取cookie
  35. *
  36. * @param str cookie数据,字符串类型,测试别名
  37. * @param num cookie数据,数字类型
  38. * @return 返回字符串类型
  39. */
  40. @GetMapping("getCookies")
  41. public String getCookies(@CookieValue(name = "cookieStr", defaultValue = "默认数据") String str, Integer num) {
  42. log.warn("str:{},num:{}", str, num);
  43. return "getCookies";
  44. }

Session

  1. /**
  2. * 设置Session
  3. *
  4. * @param request 请求对象
  5. * @return 返回字符串
  6. */
  7. @GetMapping("setSession")
  8. public String setSession(HttpServletRequest request) {
  9. HttpSession session = request.getSession();
  10. session.setAttribute("sessionStr", "test");
  11. session.setAttribute("num", 123);
  12. //设置过期时间
  13. session.setMaxInactiveInterval(30 * 60);
  14. log.warn("setSession:{}", session);
  15. return "setSession";
  16. }
  17. /**
  18. * 获取Session
  19. *
  20. * @param request 请求对象
  21. * @return 返回字符串
  22. */
  23. @GetMapping("getSession")
  24. public String getSession(HttpServletRequest request) {
  25. HttpSession session = request.getSession();
  26. Object sessionStr = session.getAttribute("sessionStr");
  27. log.warn("sessionStr:{}", sessionStr);
  28. log.warn("getSession:{}", session);
  29. return "getSession";
  30. }
  31. /**
  32. * 获取Session,使用@SessionAttribute注解
  33. *
  34. * @param str session数据,字符串类型,别名测试
  35. * @return 返回字符串类型
  36. */
  37. @GetMapping("getSessionSessionAttribute")
  38. public String getSessionSessionAttribute(@SessionAttribute("sessionStr") String str) {
  39. log.warn("str:{}", str);
  40. return "getSessionSessionAttribute";
  41. }
  42. //@SessionAttributes({"sessionStr", "num"})
  43. @SessionAttributes
  44. public class WebController {
  45. /**
  46. * 获取Session,使用@SessionAttributes注解
  47. *
  48. * @param str session数据,字符串类型,别名测试
  49. * @param num session数据,数字类型
  50. * @return 返回字符串类型
  51. * <p>
  52. * 注解@SessionAttributes抓取域对象分为两步;
  53. * 1. 在类上添加注解@SessionAttributes;
  54. * 2. 在方法的参数中通过@ModelAttribute获取域对象;
  55. */
  56. @GetMapping("getSessionSessionAttributes")
  57. public String getSessionSessionAttributes(@ModelAttribute("sessionStr") String str, @ModelAttribute Integer num) {
  58. log.warn("str:{},num:{}", str, num);
  59. return "getSessionSessionAttributes";
  60. }