添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
本文依赖SpringBoot版本信息:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
各种响应
/**
* HTTP的所有请求方式: GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
*
* @param request 注入
* @return 返回字符串
*/
@RequestMapping("all")
public String all(HttpServletRequest request) {
log.info("request:{}", JSONUtil.toJsonStr(request));
return "all";
}
@Data
@Builder //支持构建者模式
public static class R<T> implements Serializable {
protected Integer code;
protected String msg;
protected T data;
/**
* 响应状态码
*/
interface Code {
int SUCCESS_CODE = 1;
int FAIL_CODE = 0;
}
/**
* 响应状态码
*/
interface Message {
String SUCCESS_MESSAGE = "成功";
String FAIL_MESSAGE = "失败";
}
public static <T> R<T> ok() {
return new R<>(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, null);
}
}
/**
* 响应自定义Bean
*
* @return R
* @see R
*/
@RequestMapping("returnR")
public R<String> returnR() {
log.warn("returnR");
return R.ok();
}
/**
* 响应ResponseEntity
*
* @return ResponseEntity
* @see ResponseEntity
*/
@RequestMapping("returnResponseEntity")
public ResponseEntity<String> returnResponseEntity() {
log.warn("returnResponseEntity");
return ResponseEntity.ok("SUCCESS");
}
/**
* 响应自定义ResponseEntity
*
* @return ResponseEntity
* @see ResponseEntity
*/
@RequestMapping("returnResponseEntityHttpStatus")
public ResponseEntity<String> returnResponseEntityHttpStatus() {
log.warn("returnResponseEntityHttpStatus");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)//400
.build();
}
/**
* 注解实现响应自定义HTTP状态码
*
* @return ResponseEntity
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@RequestMapping("returnResponseStatus")
public String returnResponseStatus() {
log.warn("returnResponseStatus");
return "returnResponseStatus";
}
关于自定义响应对象,示例如下:
package com.initit.sbweb.controller;
import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* Result
* 统一响应解构
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder //支持构建者模式
@ApiModel(value = "R对象", description = "统一响应对象")
public class R<T> implements Serializable {
@ApiModelProperty(value = "状态码 0失败 1成功", required = true)
protected Integer code;
@ApiModelProperty(value = "提示信息")
protected String msg;
@ApiModelProperty(value = "数据")
protected T data;
@ApiModelProperty(value = "服务器响应时间 yyyy-MM-dd HH:mm:ss GMT+8", required = true)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
protected LocalDateTime responseTime = LocalDateTime.now();
/**
* 响应状态码
*/
interface Code {
int SUCCESS_CODE = 1;
int FAIL_CODE = 0;
}
/**
* 响应状态码
*/
interface Message {
String SUCCESS_MESSAGE = "成功";
String FAIL_MESSAGE = "失败";
}
//构造函数
private R(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
//----------- 封装常用方法-----------------
public static <T> R<T> result(Integer code, String message, T data) {
return new R<T>(code, message, data);
}
/**
* 封装特有的boolean类型
* 根据boolean类型自动封装返回类型
*
* @param result 结果
* @return R
*/
public static R<Boolean> result(Boolean result) {
if (result) {
return ok();
} else {
return fail();
}
}
public static <T> R<T> ok() {
return result(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, null);
}
public static <T> R<T> ok(T data) {
return result(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, data);
}
public static <T> R<T> ok(String message, T data) {
return result(Code.SUCCESS_CODE, message, data);
}
public static <T> R<T> fail() {
return result(Code.FAIL_CODE, Message.FAIL_MESSAGE, null);
}
public static <T> R<T> fail(T data) {
return result(Code.FAIL_CODE, Message.FAIL_MESSAGE, data);
}
public static <T> R<T> fail(String message, T data) {
return result(Code.FAIL_CODE, message, data);
}
//支持各种分页框架 需要引入Mybatis-Plus框架
// public static <T> R<PageResult<T>> ok(IPage<T> page) {
// return result(Code.SUCCESS_CODE, Message.SUCCESS_MESSAGE, PageResult.page(page));
// }
public static <T> R<T> okMsg(String msg) {
return R.ok(msg, null);
}
public static <T> R<T> failMsg(String msg) {
return R.fail(msg, null);
}
}
HTTP各种请求方式
/**
* GET请求
*
* @param str url变量,字符串类型参数
* @param num url变量, 数字类型参数
* @param param1 path参数1
* @param param3 path参数2,测试别名
* @return 返回字符串
*/
@GetMapping("get/{param1}/{param2}/test")
public String get(String str,
Long num,
@PathVariable String param1,
@PathVariable("param2") String param3
) {
log.warn("str:{},num:{},param1:{},param2:{}", str, num, param1, param3);
return "get";
}
/**
* POST请求,地址变量
*
* @param str url变量,字符串类型参数
* @param num url变量, 数字类型参数
* @param pathVariable path变量
* @return 返回字符串
*/
@PostMapping("postPathVariable/{pathVariable}")
public String postPathVariable(
String str,
Long num,
@PathVariable String pathVariable
) {
log.warn("str:{},num:{}", str, num);
log.warn("pathVariable:{}", pathVariable);
return "postPathVariable";
}
/**
* POST请求,body转为JSON对象
*
* @param map json字符串转为map
* @param request 请求对象
* @return 返回字符串
*/
@PostMapping("postRequestBodyJson")
public String postRequestBodyJson(
@RequestBody Map<String, Object> map,
HttpServletRequest request
) {
log.warn("map:{}", JSONUtil.toJsonStr(map));
log.warn(request.getRequestURI());
return "postRequestBodyJson";
}
/**
* POST请求,body转为字符串
*
* @param txt 字符串请求,使用js/xml/html等
* @param request 请求对象
* @return 返回字符串
*/
@PostMapping("postRequestBodyStr")
public String postRequestBodyStr(
@RequestBody String txt,
HttpServletRequest request
) {
log.warn("txt:{}", txt);
log.warn(request.getRequestURI() + " " + request.getContentType());
return "postRequestBodyStr";
}
/**
* POST 表单提交
*
* @param str 表单数据,文本类型
* @param file 表单数据,文件类型
* @return 返回字符串类型
*/
@PostMapping("postFormData")
public String postFormData(
String str,
MultipartFile file
) {
log.warn("str:{}", str);
log.warn("file:{}--{}--{}--{}--{}",
JSONUtil.toJsonStr(file), file.getOriginalFilename(), file.getName(), file.getSize(), file.getContentType());
return "postFormData";
}
/**
* POST请求,多文件上传
*
* @param files 多个文件
* @return 返回字符串
*/
@PostMapping("postFiles")
public String postFiles(List<MultipartFile> files) {
log.warn("files:{}", files.size());
for (MultipartFile file : files) {
log.warn("file:{}--{}--{}--{}--{}",
JSONUtil.toJsonStr(file), file.getOriginalFilename(), file.getName(), file.getSize(), file.getContentType());
}
return "postFiles";
}
/**
* DELETE请求
*
* @param str url参数,字符串类型
* @param num url参数,数字类型
* @param pathVariable path参数
* @return 返回字符串
*/
@DeleteMapping("delete/{pathVariable}")
public String delete(String str,
Long num,
@PathVariable String pathVariable
) {
log.warn("str:{},num:{}", str, num);
log.warn("pathVariable:{}", pathVariable);
return "delete";
}
/**
* PUT请求
*
* @param str url参数,字符串类型
* @param num url参数,数字类型
* @param pathVariable path参数
* @return 返回字符串
*/
@PutMapping("put/{pathVariable}")
public String put(
String str,
Long num,
@PathVariable String pathVariable
) {
log.warn("str:{},num:{}", str, num);
log.warn("pathVariable:{}", pathVariable);
return "put";
}
/**
* PATH请求
*
* @return 返回字符串
*/
@PatchMapping("patch")
public String put() {
log.warn("patch");
return "patch";
}
请求头
/**
* 请求头示例
*
* @param str 请求头数据,字符串类型,测试别名
* @param num 请求头数据,数字类型
* @return 字符串类型
*/
@GetMapping("requestHeader")
public String requestHeader(@RequestHeader("headerStr") String str, @RequestHeader Integer num) {
log.warn("str:{},num:{}", str, num);
return "requestHeader";
}
/**
* 请求头示例,自定义模式获取
*
* @param request 请求对象
* @return 字符串类型
*/
@GetMapping("requestHeaderRequest")
public String requestHeaderRequest(HttpServletRequest request) {
String str = request.getHeader("str");
String num = request.getHeader("num");
log.warn("str:{},num:{}", str, num);
return "requestHeaderRequest";
}
Cookies
/**
* 设置cookie
*
* @param response 响应对象
* @return 字符串类型
*/
@GetMapping("setCookies")
public String setCookies(HttpServletResponse response) {
Cookie cookie = new Cookie("cookieStr", "test");
//设置过期时间 7天过期
cookie.setMaxAge(7 * 24 * 60 * 60);
//Https 安全cookie 该Cookie将无法在Http连接中传输,只能是Https连接中传输
// cookie.setSecure(true);
response.addCookie(cookie);
log.warn("setCookies");
return "setCookies";
}
/**
* 获取cookie
*
* @param request 请求对象
* @return 字符串类型
*/
@GetMapping("getCookiesRequest")
public String getCookiesRequest(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
log.warn("cookies:{}", cookies.length);
for (Cookie cookie : cookies) {
log.warn("cookie:{}", cookie);
}
return "getCookiesRequest";
}
/**
* 获取cookie
*
* @param str cookie数据,字符串类型,测试别名
* @param num cookie数据,数字类型
* @return 返回字符串类型
*/
@GetMapping("getCookies")
public String getCookies(@CookieValue(name = "cookieStr", defaultValue = "默认数据") String str, Integer num) {
log.warn("str:{},num:{}", str, num);
return "getCookies";
}
Session
/**
* 设置Session
*
* @param request 请求对象
* @return 返回字符串
*/
@GetMapping("setSession")
public String setSession(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("sessionStr", "test");
session.setAttribute("num", 123);
//设置过期时间
session.setMaxInactiveInterval(30 * 60);
log.warn("setSession:{}", session);
return "setSession";
}
/**
* 获取Session
*
* @param request 请求对象
* @return 返回字符串
*/
@GetMapping("getSession")
public String getSession(HttpServletRequest request) {
HttpSession session = request.getSession();
Object sessionStr = session.getAttribute("sessionStr");
log.warn("sessionStr:{}", sessionStr);
log.warn("getSession:{}", session);
return "getSession";
}
/**
* 获取Session,使用@SessionAttribute注解
*
* @param str session数据,字符串类型,别名测试
* @return 返回字符串类型
*/
@GetMapping("getSessionSessionAttribute")
public String getSessionSessionAttribute(@SessionAttribute("sessionStr") String str) {
log.warn("str:{}", str);
return "getSessionSessionAttribute";
}
//@SessionAttributes({"sessionStr", "num"})
@SessionAttributes
public class WebController {
/**
* 获取Session,使用@SessionAttributes注解
*
* @param str session数据,字符串类型,别名测试
* @param num session数据,数字类型
* @return 返回字符串类型
* <p>
* 注解@SessionAttributes抓取域对象分为两步;
* 1. 在类上添加注解@SessionAttributes;
* 2. 在方法的参数中通过@ModelAttribute获取域对象;
*/
@GetMapping("getSessionSessionAttributes")
public String getSessionSessionAttributes(@ModelAttribute("sessionStr") String str, @ModelAttribute Integer num) {
log.warn("str:{},num:{}", str, num);
return "getSessionSessionAttributes";
}