Controller 層編碼規(guī)范
胖虎和朋友原創(chuàng)的視頻教程有興趣的可以看看:
(文末附課程大綱)

1、控制器層
controller 層在 MVC 設(shè)計屬于控制層設(shè)計初衷:設(shè)計初衷:請求并響應(yīng)請求;所以該層輕似接受,涉及業(yè)務(wù)的。
之前,使用下分開的開發(fā)設(shè)計模式,推薦使用@RestController注解它@ResponseBody + @Controller的組合。
-
如果只是將Controller中的內(nèi)容解開, @RestController則將Controller中的內(nèi)容解析器的視圖的解法,或者將配置方法重新設(shè)置為返回使用HTML格式的方法,或者返回解析器返回常用的方法InternalResourceViewResolver,返回js的內(nèi)容。 -
如果需要返回到指定的頁面,則需要用 @Controller視圖來指定解析器InternalResourceViewResolver才行。mediaType``@ResponseBody
如,使用@Controller注釋解,在的方法上,查看解析器可以解析返回的jsp,html頁面,跳轉(zhuǎn)到相應(yīng)頁面;若返回json等內(nèi)容到頁面,則需要加@ResponseBody注解
1)設(shè)置請求路徑
使用注解@PostMapping("/page"),類命名和方法除掉都可以加。
注意按照不同業(yè)務(wù)劃分使用,避免亂寫亂用。
2)設(shè)置請求方式
常用的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)設(shè)置請求參數(shù)方式
①提交提交,直接使用vo類或具體參數(shù)名接收;
@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: 請求參數(shù)名(必須配置) -
required: 必須,默認(rèn)為true 請求中必須包含該參數(shù),如果包含沒有,即拋出異常(可選配置) -
defaultValue: 默認(rèn)值,如果設(shè)置了該值,必填 將自動設(shè)為 false
@ApiOperation(value = "根據(jù)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`數(shù)據(jù)時(JSON字符串中的數(shù)據(jù)請求體中的數(shù)據(jù)的);GET方式無請求體,所以接收端不能使用GET方式提交數(shù)據(jù),只是可以用同一個POST方式進行提交。可以在同一個接收方法中,`@RequestBody`最多可以有一個,并且有多個。`@RequestParam()``@RequestBody``@RequestParam()
注:一個請求,只有一個
RequestBody請求,可以有多個RequestParam。
@ApiOperation(value = "根據(jù)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;
}
}
說明: 示例代碼的實用性更高,實際開發(fā)中使用了各種功能。
4)請求參數(shù)
參數(shù)參數(shù)
-
使用注意解說 @Validated,有特色的自動評測開始了,它是spring-contex中性的注釋解說; -
vo類中自定義標(biāo)注,比如 @NotNull下等,他是javaxvalidation-api中的注解這里不贅述; -
程序表示的驗證。
示例方法如下
@ApiOperation(value = "應(yīng)用類型和應(yīng)用關(guān)系綁定")
@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 = "關(guān)系綁定vo")
public class ApplicationBindVO {
@NotNull
@ApiModelProperty("應(yīng)用類型id")
private Long typeId;
@ApiModelProperty("應(yīng)用id集合")
private List<Long> applicationIdList;
}
5)入?yún)⒊鰠⒃O(shè)計
到期業(yè)務(wù)而定,格式輕松統(tǒng)一;
響應(yīng)前端(APP/PC)的參數(shù),一般重新處理,按順序排列,方便統(tǒng)一
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 = "響應(yīng)信息")
public class Responses<T> {
@JsonView({BaseView.class})
@ApiModelProperty("響應(yīng)編碼")
private String code;
@JsonView({BaseView.class})
@ApiModelProperty("響應(yīng)消息")
private String msg;
@JsonView({BaseView.class})
@ApiModelProperty("響應(yīng)體")
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 = "日志相關(guān)接口", 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: 作用在類上,標(biāo)注該類具體實現(xiàn)內(nèi)容。表示該類是swagger的資源。
參數(shù):
-
標(biāo)簽: 可以使用 tags()允許您為操作設(shè)置多個標(biāo)簽的屬性,而不是使用該屬性。 -
description: 可描述描述該類的作用。
@ApiOperation: 用于方法,表示一個http請求的操作。
@ApiModel: 方法用于,更改字段數(shù)據(jù),表示對模型屬性的說明或操作
基于 Spring Boot + MyBatis Plus + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能
項目地址:https://github.com/YunaiV/ruoyi-vue-pro 視頻教程:https://doc.iocoder.cn/video/
2、相對標(biāo)準(zhǔn)控制器類示例
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;
/**
* 相關(guān)接口
*/
@Api(tags = "日志相關(guān)接口", 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 = "根據(jù)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();
}
}
![]()
胖虎聯(lián)合兩位大佬朋友,一位是知名培訓(xùn)機構(gòu)講師和科大訊飛架構(gòu),聯(lián)合打造了《Java架構(gòu)師成長之路》的視頻教程。完全對標(biāo)外面2萬左右的培訓(xùn)課程。
除了基本的視頻教程之外,還提供了超詳細的課堂筆記,以及源碼等資料包..
課程階段:
Java核心 提升閱讀源碼的內(nèi)功心法 深入講解企業(yè)開發(fā)必備技術(shù)棧,夯實基礎(chǔ),為跳槽加薪增加籌碼
分布式架構(gòu)設(shè)計方法論。為學(xué)習(xí)分布式微服務(wù)做鋪墊 學(xué)習(xí)NetFilx公司產(chǎn)品,如Eureka、Hystrix、Zuul、Feign、Ribbon等,以及學(xué)習(xí)Spring Cloud Alibabba體系 微服務(wù)架構(gòu)下的性能優(yōu)化 中間件源碼剖析 元原生以及虛擬化技術(shù) 從0開始,項目實戰(zhàn) SpringCloud Alibaba電商項目
點擊下方超鏈接查看詳情
(或者點擊文末閱讀原文):
(點擊查看) 2023年,最新Java架構(gòu)師成長之路 視頻教程!
以下是課程大綱,大家可以雙擊打開原圖查看


