Spring MVC 處理 GET請求


 

HTTP請求有8種方法:  GET,POST, PUT,DELETE,HEAD,OPTIONS, TRACE 和 CONNECT 。在Spring MVC中常用的用GET, PUT, POST, DELETE, 這里先介紹GET請求在Spring MVC中的應用。

 

1.使用@PathVariable注解 接收  GET請求中, url參數

     處理url中帶有參數的請求時,在@GetMapping路徑中添加占位符,占位符的名稱要用大括號(“{”和“}”)括起來,路徑中的其他部分要與所處理的請求完全匹配。

     然后在方法參數上添加@PathVariable注解,並且@PathVariable屬性的值 和占位符的名稱相同

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/person")
public class PersonController {

    Logger logger = LoggerFactory.getLogger(PersonController.class);

    @GetMapping("/{firstName}/{lastName}")
    public void findByName(@PathVariable String firstName, @PathVariable String lastName) {

        logger.info("firstName is : " + firstName);
        logger.info("lastName is : " + lastName);

    }

}

 提交請求 http://localhost:8200/api/person/nicky

 

 

2.使用@RequestParam注解來接收  GET請求中   的請求參數

    用Spring MVC @RequestParam注解處理帶有查詢參數的請求 ,@RequestParam()有兩個屬性,value屬性指定請求參數名字,defaultValue屬性指定如果請求url中沒有參數時的默認值。並且因為查詢參數都是String類型的,因此defaultValue屬性需要String類型的

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/person")
public class PersonController {

    Logger logger = LoggerFactory.getLogger(PersonController.class);

    @GetMapping("/list")
    public void findList(@RequestParam String firstName, @RequestParam String lastName) {

        logger.info("wow, firstName is : " + firstName);
        logger.info("wow, lastName is : " + lastName);

    }

}

提交請求 http://localhost:8200/api/person/list?firstName=nicky&lastName=wang

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM