SpringMvc 部分註解的理解

SpringMvc註解

1.@Valid

可以實現數據的驗證,你可以定義實體,在實體的屬性上添加校驗規則,而在API接收數據時添加@valid關鍵字,這時你的實體將會開啓一個校驗的功能。(在相關的實體類的相關字段添加用於充當驗證條件的註解)

@Valid 註解類型

@Null限制只能爲null

@NotNull限制必須不爲null

@AssertFalse限制必須爲false

@AssertTrue限制必須爲true

@DecimalMax(value)限制必須爲一個不大於指定值的數字

@DecimalMin(value)限制必須爲一個不小於指定值的數字

@Digits(integer,fraction)限制必須爲一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction

@Future限制必須是一個將來的日期

@Max(value)限制必須爲一個不大於指定值的數字

@Min(value)限制必須爲一個不小於指定值的數字

@Past限制必須是一個過去的日期

@Pattern(value)限制必須符合指定的正則表達式

@Size(max,min)限制字符長度必須在min到max之間

@Past驗證註解的元素值(日期類型)比當前時間早

@NotEmpty驗證註解的元素值不爲null且不爲空(字符串長度不爲0、集合大小不爲0)

@NotBlank驗證註解的元素值不爲空(不爲null、去除首位空格後長度爲0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格

@Email驗證註解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式

示例代碼:

@ApiOperation(value = “Ogg 啓動”)
@PostMapping("/start/{id}")
@ApiImplicitParam(paramType = “path”, name = “id”, value = “id”, required = true, dataType = “String”)
public Result startOgg(@PathVariable(“id”) String id, @Valid OggGpProcessDto prorcessDto) throws Exception {
RtOggGp start = this.rtOggGpService.start(id, prorcessDto);
return new Result<>(CODE_SUCCESS, “”, start.getStatus());
}
在OggGpProcessDto類前面有@Valid註解

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = “oggGp process dto”)
public class OggGpProcessDto {

@ApiModelProperty(value = “extractProcess”,dataType = “String”)
@NotBlank(message = “extractProcess不能空”)
private String extractProcess;

@ApiModelProperty(value = “pumpProcess”,dataType = “String”)
@NotBlank(message = “pumpProcess不能空”)
private String pumpProcess;

@ApiModelProperty(value = “replicateProcess”,dataType = “String”)
@NotBlank(message = “replicateProcess不能空”)
private String replicateProcess;
這個類裏面就有@NotBlank註解校驗

2.@RequestParam

作用:將請求參數綁定到你控制器的方法參數上(是springmvc中接收普通參數的註解)

示例代碼:

//greenplum配置
@GetMapping("/DBs/tableColumn/{id}")
public Result<List> getSelectTablesById(
@PathVariable Integer id,@RequestParam(“oggName”)String oggName) throws Exception {
List rtOggTableInfo = rtOggGpTableService.getRtOggGpTableInfo(id,oggName);
return new Result<>(CODE_SUCCESS, “”, rtOggTableInfo);
}
請求的url就應該是:

http://xxxxxxxxx/etl/rt/ogg/gp/DBs/tableColumn/369?oggName=gp24

有三個參數設置 value required defaultValue

value可以默認不寫,之前像上方一樣,直接寫入“oggName"即默認是value。

required=true 代表這個參數必須給出,如果不給出就會報錯。

在required參數爲true時,可以給他一個默認值 避免出錯。 required=true, defaultValue=“hello”

完整的參數設置可以是:(@RequestParam(value=“name”,required=true,defaultValue=“hello”)String name)

3.@PathVariable

通過 @PathVariable 可以將URL中佔位符參數{xxx}綁定到處理器類的方法形參中@PathVariable(“xxx“)

也就是說不用寫成name = “xxx” 而是直接在請求後面跟參數值

示例代碼:

@ApiOperation(value = “獲取 Ogg 狀態 “)
@GetMapping(”/getState/{id}”)
@ApiImplicitParam(paramType = “path”, name = “id”, value = “RT_OGG_Id”, required = true, dataType = “String”)
public Result<List> getOggState(@PathVariable(required = true) String id) throws Exception {
List list = this.rtOggGpService.getState(id);
return new Result<>(CODE_SUCCESS, “”, list);
}
請求的url就是:

http://xxxxxxxxx/etl/rt/ogg/gp/getState/369 (369就是參數id的值)

如果是RequestParam(“id”) 就會變成 getState/id=369

4.@RequestBody

@RequestBody主要用來接收前端傳遞給後端的json字符串中的數據的(請求體中的數據的);GET方式無請求體,所以使用@RequestBody接收數據時,前端不能使用GET方式提交數據,而是用POST方式進行提交。在後端的同一個接收方法裏,@RequestBody與@RequestParam()可以同時使用,@RequestBody最多只能有一個,而@RequestParam()可以有多個。

示例代碼:

@ApiOperation(value = “修改”)
@PutMapping("/{id}")
@ApiImplicitParam(paramType = “path”, name = “id”, value = “RT_OGGid”, required = true, dataType = “String”)
// @PreAuthorize(“hasAuthority(@auth.genAuthCode(’{accessCodePrefix}.update’))”)
public Result grantAuth(@PathVariable(“id”) String id, @RequestBody RtOggGpDto dto) throws Exception {
rtOggGpService.update(id, dto);
return new Result<>(CODE_SUCCESS, “”, “ok”);
}
代碼中對於前端返回的RtOggGpDto類前面有 @RequestBody註解

所以前端傳回值的時候是寫在請求體的body中的,而不是直接跟在請求後面。比如這裏面是需要需要某個實體的信息,那麼傳回來的肯定是整個實體的所有信息。

5.@RestController

@RestController @Controller 都是用來表示Spring某個類的是否可以接收HTTP請求

組合註解,組合了@Controller和@ResponseBody,當我們只開發一個和頁面交互數據的控制層的時候可以使用此註解

@RequestMapping("/rt/ogg/gp")
@RestController
@Slf4j
public class OggGpController extends AuthorityController {}
這樣這個類返回的數據就都是json數據

在類上使用了@RestController時,類下面的方法就不再需要寫@ResponseBody註解了。

6.@ResponseBody

@ResponseBody的作用其實是將java對象轉爲json格式的數據。(將返回值放在response體內。返回的是數據而不是頁面)

是將controller的方法返回的對象通過適當的轉換器轉換爲指定的格式之後,寫入到response對象的body區,通常用來返回JSON數據或者是XML數據。

@ResponseBody是作用在方法上的,@ResponseBody 表示該方法的返回結果直接寫入 HTTP response body 中,一般在異步獲取數據時使用【也就是AJAX】

如果沒有這個轉化的話,前端得到的就是Object對象 ,不方便使用。

而加了ResponseBody,比如傳給前端是個User對象,下面有age,name,id等字段

{“id”:“1”, “name”:“張三”, “age”:“22”}

7.@RequestMapping

@RequestMapping用來定義訪問的URL,你可以爲整個類定義一個@RequestMapping,或者爲每個方法指定一個。 把@RequestMapping放在類級別上,這可令它與方法級別上的@RequestMapping註解協同工作,取得縮小選擇範圍的效果。

//Class
@Api(value = “REST interface RT_OGG_GP”, tags = {“RT_OGG_GP 接口”})
@RequestMapping("/rt/ogg/gp")
@RestController
@Slf4j
public class OggGpController extends AuthorityController {}
//Method
@RequestMapping("/list")
public getAll() {
}

8.@Transactional

看了一下源碼:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
首先 他是作用在類或者方法上的。 ElementType.METHOD, ElementType.TYPE

  • {@link org.springframework.transaction.interceptor.DefaultTransactionAttribute}* (rolling back on {@link RuntimeException} and {@link Error} but not on checked* exceptions).
    這一段是說 只有在拋出RunTimeException異常或者Error類型的異常會導致事務回滾。

太多了 不想讀了 頭疼 難受呀 讀源碼還是很重要的 下次讀完再更新!!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章