SpringBoot Controller中的常用注解
概述
Controller是Spring接受并處理網(wǎng)頁請求的組件,是整個應用的入口,因此學會Controller的常用注解對理解一個應用是重中之重。SpringBoot的Controller中經(jīng)常會用到注解@Controller、@RestController、@RequestMapping、@RequestBody等,本短文主要對這些常用的Controller注解進行簡單介紹。
常用注解簡介
1.@Controller
@Controller是最基本的控制層注解,繼承了Spring的@Component注解,會把對應的類聲明為Spring對應的Bean,并且可以被Web組件管理。使用@Controller注解返回的是view,而不是Json數(shù)據(jù),例:
@Controller
@RequestMapping("/test")
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello World!");
return "index";
}
}在該段代碼中,用戶若訪問/test/hello,則會返回index頁面。
2.@RestController
和@Controller一樣,@RestController也是用于一個類的標注,不同的是@RestController標注的類的方法返回json。
例如:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/index")
public String testMethod(Model model) {
return "index/index";
}
}訪問的返回結果如圖所示 :

3.@RequestMapping
@RequestMapping是用于標識類或者方法的訪問地址的,提供路由信息,完成從url到controller的映射。例如上面代碼塊中的類上的@RequestMapping("/test")表示訪問端口的/test就能訪問到改控制器,而訪問/test/index則能訪問到該類的相應方法。@GetMapping/@PostMapping其實就是@RequestMapping和Get/Post的集合。@GetMapping(value = “hello”) 等價于@RequestMapping(value = “hello”, method = RequestMethod.GET)
4.@RequestBody
該注解的作用是將方法的返回值,以特定的格式寫入到response的body區(qū)域,進而將數(shù)據(jù)返回給客戶端。當方法上面沒有寫ResponseBody,底層會將方法的返回值封裝為ModelAndView對象。如果返回值是字符串,那么直接將字符串寫到客戶端;如果是一個對象,會將對象轉化為json串,然后寫到客戶端。@Controller+@ResponseBody等于@RestController。
5.@RequestParam
@RequestParam用于獲取請求參數(shù),從而使用請求所帶的參數(shù),
例如:
@RequestMapping("/user")
public String testRequestParam(@RequestParam("name") String name){
System.out.println("請求姓名參數(shù)="+name);
return "success";
}該段代碼會解析請求參數(shù)name,用于方法中的使用。
6.@PathVariable
@PathVariable與@RequestMapping配合使用,通過解析url中的占位符進行參數(shù)獲取。
例如:
@RequestMapping("/user/{id}")
public String testPathVariable(@PathVariable("id") String id){
System.out.println("路徑上的占位符的值="+id);
return "success";
}上面的代碼塊就能從url中解析出id字段,用于方法中的使用。
總結
本文只是對常用的一些@Controller層的注解進行簡介,對這些注解組合使用,才能夠達到想要完成的目的任務。
到此這篇關于SpringBoot Controller中的常用注解的文章就介紹到這了,更多相關SpringBoot Controller 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot如何為web層添加統(tǒng)一請求前綴
這篇文章主要介紹了springboot如何為web層添加統(tǒng)一請求前綴,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
Java?基于Hutool實現(xiàn)DES加解密示例詳解
這篇文章主要介紹了Java基于Hutool實現(xiàn)DES加解密,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
解決IDEA使用springBoot創(chuàng)建項目,lombok標注實體類后編譯無報錯,但是運行時報錯問題
文章詳細描述了在使用lombok的@Data注解標注實體類時遇到編譯無誤但運行時報錯的問題,分析了可能的原因,并提供了解決步驟2025-01-01
Intellij IDEA基于Springboot的遠程調試(圖文)
這篇文章主要介紹了Intellij IDEA基于Springboot的遠程調試(圖文),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10

