⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 blog.csdn.net/jiahao1186 「春风化作秋雨」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注**微信公众号:【芋道源码】**有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言将得到认真回复。甚至不知道如何读源码也可以请教噢
  4. 新的源码解析文章实时收到通知。每周更新一篇左右
  5. 认真的源码交流微信群。

1、控制器层

controller 层在 MVC 设计属于控制层设计初衷:设计初衷:请求并响应请求;所以该层轻似接受,涉及业务的。

之前,使用下分开的开发设计模式,推荐使用@RestController注解它@ResponseBody + @Controller的组合。

  1. 如果只是将Controller中的内容解开,@RestController则将Controller中的内容解析器的视图的解法,或者将配置方法重新设置为返回使用HTML格式的方法,或者返回解析器返回常用的方法InternalResourceViewResolver,返回js的内容。
  2. 如果需要返回到指定的页面,则需要用@Controller视图来指定解析器InternalResourceViewResolver才行。mediaType``@ResponseBody

如,使用@Controller注释解,在的方法上,查看解析器可以解析返回的jsp,html页面,跳转到相应页面;若返回json等内容到页面,则需要加@ResponseBody注解

1)设置请求路径

使用注解@PostMapping("/page"),类命名和方法除掉都可以加。

注意按照不同业务划分使用,避免乱写乱用。

2)设置请求方式

常用的POST/GET。使用注解:@RequestMapping@GetMapping @PostMapping

4.3中的介绍@GetMapping、介绍@PostMapping、提高的方法、@PutMapping来帮助解决快速表达方式的HTTP和地@DeleteMapping``@PatchMapping

该注解HTTP Get方法将映射到特定的处理上

  • @GetMapping是一个注释解,它是一个组合@RequestMapping(method = RequestMethod.GET)的缩写
  • @PostMapping是一个注释解,它是一个组合@RequestMapping(method = RequestMethod.POST)的缩写

3)设置请求参数方式

①提交提交,直接使用vo类或具体参数名接收;

@Controller
public class LoginController {

@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(UserVO user){
System.out.println("POJO: " + user.getClass().getName() +
", hash code: " + user.hashCode() + ", " + user.toString());
return "redirect:/";
}

}

②@RequestParam

@RequestParam(value="", required=true, defaultValue="")

@RequestParam有三个属性:

  • **value:**请求参数名(必须配置)
  • **required:**必须,默认为true 请求中必须包含该参数,如果包含没有,即抛出异常(可选配置)
  • **defaultValue:**默认值,如果设置了该值,必填 将自动设为 false

@ApiOperation(value = "根据id查询") 
@PostMapping("/show")
public Responses show(@RequestParam(value="userId",defaultValue="-1") Long userId) {
Record data = recordService.getOne(vo.getId());
return Responses.success(data);

}

③n提交,使用注解@RequestBody

@RequestBody`主要接收接收端以POST方式传递给使用`@RequestBody`数据时(JSON字符串中的数据请求体中的数据的);GET方式无请求体,所以接收端不能使用GET方式提交数据,只是可以用同一个POST方式进行提交。可以在同一个接收方法中,`@RequestBody`最多可以有一个,并且有多个。`@RequestParam()``@RequestBody``@RequestParam()

注:一个请求,只有一个RequestBody请求,可以有多个RequestParam

@ApiOperation(value = "根据id查询") 
@PostMapping("/get")
public Responses getOne(@Validated @RequestBody IdVO vo){
Record data = recordService.getOne(vo.getId());
return Responses.success(data);
}

④ath变量

@RestController
@RequestMapping("/")
public class ChineseDrugController {
@ResponseBody
@RequestMapping(value = "/{name}")
public String showName(@PathVariable String name, @PathVariable(value = "name", required = false) String sex) {
return "Hello " + name + sex;
}

⑤@PathParam

> url:http://127.0.0.1:8080/sexvalue/namevalue?name=唐&sex=男
>

@RestController
@RequestMapping(value = "/{sex}")
public class ChineseDrugController {
@ResponseBody
@RequestMapping(value = "/{name}")
public String showName(@PathVariable(value = "name") String name, @PathParam(value = "sex") String sex) {
return "Hello " + name + " " + sex;
}
}

说明: 示例代码的实用性更高,实际开发中使用了各种功能。

4)请求参数

参数参数

  • 使用注意解说@Validated,有特色的自动评测开始了,它是spring-contex中性的注释解说;
  • vo类中自定义标注,比如@NotNull下等,他是javaxvalidation-api中的注解这里不赘述;
  • 程序表示的验证。

示例方法如下

@ApiOperation(value = "应用类型和应用关系绑定")
@PostMapping("/applicationTypeBind")
public Boolean applicationTypeBind(@Validated @RequestBody ApplicationBindVO vo){
applicationTypeService.applicationTypeBind(vo);
return true;
}

VO 类示例

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;

@Data
@ApiModel(value = "ApplicationBindVO",description = "关系绑定vo")
public class ApplicationBindVO {

@NotNull
@ApiModelProperty("应用类型id")
private Long typeId;

@ApiModelProperty("应用id集合")
private List<Long> applicationIdList;
}

5)入参出参设计

到期业务而定,格式轻松统一;

响应前端(APP/PC)的参数,一般重新处理,按顺序排列,方便统一

Responses.success(data);
import com.fasterxml.jackson.annotation.JsonView;
import com.myfutech.common.util.enums.ResponseCode;
import com.myfutech.common.util.vo.BaseView;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "Responses",description = "响应信息")
public class Responses<T> {

@JsonView({BaseView.class})
@ApiModelProperty("响应编码")
private String code;

@JsonView({BaseView.class})
@ApiModelProperty("响应消息")
private String msg;

@JsonView({BaseView.class})
@ApiModelProperty("响应体")
private T result;

public static <T> Responses<T> success() {
return new Responses(ResponseCode.SUCCESS_CODE, "", (Object)null);
}

public static <T> Responses<T> success(T result) {
return new Responses(ResponseCode.SUCCESS_CODE, "", result);
}

public static <T> Responses<T> success(String msg, T result) {
return new Responses(ResponseCode.SUCCESS_CODE, msg, result);
}

public static <T> Responses<T> error(String msg) {
return new Responses(ResponseCode.ERROR_CODE, msg, (Object)null);
}

public static <T> Responses<T> error(ResponseCode code) {
return new Responses(code, code.getDefaultMsg(), (Object)null);
}

public static <T> Responses<T> error(ResponseCode code, String msg) {
return new Responses(code, msg, (Object)null);
}

public Responses() {
}

private Responses(ResponseCode code, String msg, T result) {
this.code = code.getCode();
this.msg = msg;
this.result = result;
}

public String getCode() {
return this.code;
}

public boolean notSuccess() {
return !ResponseCode.SUCCESS_CODE.getCode().equals(this.code);
}

public String getMsg() {
return this.msg;
}

public T getResult() {
return this.result;
}

public void setCode(String code) {
this.code = code;
}

public void setMsg(String msg) {
this.msg = msg;
}

public void setResult(T result) {
this.result = result;
}


}

6) 自动生成接口文档

使用SwaggerAPI,常用注解

//加载类名之上
@Api(tags = "日志相关接口", description="操作日志",
consumes= MediaType.APPLICATION_JSON_UTF8_VALUE,
produces=MediaType.APPLICATION_JSON_UTF8_VALUE)


//加在方法名之上
@ApiOperation(value = "查询分页列表")

//加载实体或VO类名之上
@Data
@ApiModel(value = "ApprovalRoleModifyVO",description = "审批角色修改信息")
public class ApprovalRoleModifyVO{

**@Api:**作用在类上,标注该类具体实现内容。表示该类是swagger的资源。

参数:

  • **标签:**可以使用tags()允许您为操作设置多个标签的属性,而不是使用该属性。
  • **description:**可描述描述该类的作用。

**@ApiOperation:**用于方法,表示一个http请求的操作。

**@ApiModel:**方法用于,更改字段数据,表示对模型属性的说明或操作

2、相对标准控制器类示例

package com.myfutech.employee.service.provider.ctrl;

import com.myfutech.common.util.Responses;
import com.myfutech.common.util.vo.IdVO;
import com.myfutech.common.util.vo.Page;
import com.myfutech.common.util.vo.Pageable;
import com.myfutech.employee.service.api.vo.response.record.RecordListVo;
import com.myfutech.employee.service.provider.model.Record;
import com.myfutech.employee.service.provider.service.RecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
* 相关接口
*/
@Api(tags = "日志相关接口", description="操作日志",
consumes= MediaType.APPLICATION_JSON_UTF8_VALUE,
produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/record")
public class RecordCtrl {


private static final Logger log = LoggerFactory.getLogger(RecordCtrl.class);

@Resource(name="recordService")
private RecordService recordService;

@ApiOperation(value = "查询分页列表")
@PostMapping("/page")
public Page<RecordListVo> page( @RequestBody Pageable pageable){
Page<RecordListVo> list = recordService.findConditionPage(pageable);
return list;
}
@ApiOperation(value = "根据id查询")
@PostMapping("/get")
public Responses getOne(@Validated @RequestBody IdVO vo){
Record data = recordService.getOne(vo.getId());
return Responses.success(data);
}
@ApiOperation(value = "新增")
@PostMapping("/add")
public Responses add(@Validated(Record.Create.class) @RequestBody Record data){
recordService.save(data);
return Responses.success();
}
@ApiOperation(value = "更新")
@PostMapping("/update")
public Responses update(@Validated(Record.Update.class) @RequestBody Record data){
recordService.save(data);
return Responses.success();
}
@ApiOperation(value = "删除")
@PostMapping("/delete")
public Responses delete(@Validated @RequestBody IdVO vo){
recordService.deleteById(vo.getId());
return Responses.success();
}
}

文章目录
  1. 1. 1、控制器层
    1. 1.1. 1)设置请求路径
    2. 1.2. 2)设置请求方式
    3. 1.3. 3)设置请求参数方式
    4. 1.4. 4)请求参数
    5. 1.5. 5)入参出参设计
    6. 1.6. 6) 自动生成接口文档
  2. 2. 2、相对标准控制器类示例