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

 

 

posted on 2021-01-15 17:00  dreamstar  阅读(1018)  评论(0编辑  收藏  举报