SpringBoot使用@RestController处理GET和POST请求

在Spring MVC中,@RestController注解的控制器类可以处理多种HTTP请求方法,包括GET和POST。这些请求方法通过特定的注解来映射,比如@GetMapping用于GET请求,@PostMapping用于POST请求。这些注解是@RequestMapping的特定化版本,提供了更清晰的语义。

GET请求

GET请求通常用于请求数据。在@RestController中,你可以使用@GetMapping或@RequestMapping(method = RequestMethod.GET)来映射GET请求。

@RestController  
public class MyController {  
  
    @GetMapping("/greeting")  
    public String greeting() {  
        return "Hello, World!";  
    }  
  
    // 或者使用@RequestMapping  
    @RequestMapping(value = "/hello", method = RequestMethod.GET)  
    public String hello() {  
        return "Hi there!";  
    }  
}

在上面的例子中,/greeting和/hello路径分别映射到greeting和hello方法,这两个方法都会处理GET请求,并返回简单的字符串响应。

GET请求通常通过URL的查询字符串(query string)来传递参数。Spring MVC提供了几种注解来帮助你方便地获取这些参数。

在@RestController中处理GET请求时,@RequestParam是获取查询字符串参数的主要方式,

@PathVariable则用于从URL的路径中获取参数。

@RequestParam

@RequestParam注解用于将请求参数绑定到你的控制器方法的参数上。默认情况下,请求参数名和参数变量名需要相同,但你可以通过value或name属性来明确指定请求参数名。

@RestController  
public class MyController {  
  
    @GetMapping("/greet")  
    public String greet(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {  
        return "Hello, " + name + "!";  
    }  
}

在这个例子中,greet方法通过@RequestParam注解接收一个名为name的请求参数。如果请求中没有提供name参数,那么name变量的值将是默认值"World"。required属性设置为false表示这个参数不是必须的。

@PathVariable

@PathVariable 是 Spring MVC 中用于将 URL 中的变量值绑定到控制器处理器方法参数上的注解。这个注解是 Spring 3.0 引入的,它允许我们从 URL 中提取变量作为方法的参数。

虽然 @PathVariable 不是直接用于GET请求参数的,但它经常与GET请求一起使用,特别是当你想从URL的路径中获取参数时。

@RestController  
public class MyController {  
  
    @GetMapping("/user/{id}")  
    public String getUserById(@PathVariable("id") Long userId) {  
        // 假设这里有一个根据userId获取用户信息的逻辑  
        return "User ID: " + userId;  
    }  
}

在这个例子中,{id}是一个路径变量,它通过@PathVariable注解绑定到userId参数上。当请求/user/123时,userId的值将是123。

@ModelAttribute

@ModelAttribute主要用于将请求参数(包括查询字符串参数、表单数据、路径变量等)绑定到Java对象上,并将这些对象添加到模型中,以便在视图渲染时使用。

@RestController
public class MyController {
    @GetMapping("/search")
    public String search(
            @ModelAttribute MySearchParams searchParams) {
        return "Searching for: " + searchParams.getQuery();
    }

    // 假设MySearchParams类如下
    static class MySearchParams {
        private String query;
        // 省略getter和setter方法
    }
}

默认值和必填性

  • 对于@RequestParam,你可以通过required属性指定参数是否是必须的,以及通过defaultValue属性为缺失的参数提供一个默认值。
  • 对于@PathVariable,没有直接的required或defaultValue属性,但你可以通过控制器方法的逻辑来处理缺失的路径变量(尽管这通常意味着请求的路径是错误的)。

POST请求

POST请求通常用于提交数据给服务器。在@RestController中,你可以使用@PostMapping或@RequestMapping(method = RequestMethod.POST)来映射POST请求。

@RestController  
public class MyController {  
  
    // 使用@PostMapping  
    @PostMapping("/submit")  
    public ResponseEntity<String> submitData(@RequestBody String data) {  
        // 处理数据...  
        return ResponseEntity.ok("Data received: " + data);  
    }  
  
    // 或者使用@RequestMapping  
    @RequestMapping(value = "/postData", method = RequestMethod.POST)  
    public ResponseEntity<String> postData(@RequestBody String data) {  
        // 处理数据...  
        return ResponseEntity.ok("Data posted: " + data);  
    }  
}

在上面的例子中,/submit和/postData路径分别映射到submitData和postData方法,这两个方法都会处理POST请求。

注意,@RequestBody注解用于将请求体中的数据绑定到方法的参数上。

在实际应用中,你可能会使用@RequestBody来接收一个Java对象,Spring会自动将请求体中的数据映射到这个对象的属性上。

Form请求

@RestController  
public class MyRestController {  
  
    @PostMapping("/submitForm")  
    public String submitForm(@RequestParam("username") String username,  
                             @RequestParam("password") String password) {  
        return "Received username: " + username + ", password: " + password;  
    }  
}

JSON请求

@RestController  
public class MyJsonRestController {  
  
    @PostMapping("/submitJson")  
    public String submitJson(@RequestBody MyFormObject formObject) {  
        return "Received user: " + formObject.getUsername() + ", password: " + formObject.getPassword();  
    }  
  
    // 假设你有一个MyFormObject类来接收JSON数据  
    static class MyFormObject {  
        private String username;  
        private String password;
        // 省略getter和setter方法
    }  
}

 上传图片

@PostMapping(value = "/uploadFile", name = "上传文件")
public String uploadImage(MultipartFile file) {
    //获取文件原名
    String fileName = file.getOriginalFilename();
    //设置上传路径
    //判断上传路径是否存在,不存在则创建目录
    File fileDir = new File(realPath);
    if (!fileDir.exists()) {
        fileDir.mkdirs();
    }
    String strYmd= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    File fileYmdDir = new File(realPath + "/" + strYmd);
    if (!fileYmdDir.exists()) {
        fileYmdDir.mkdirs();
    }
    fileName = getFileName(fileName);
    String outputPath = "";
    //上传文件
    try {
        outputPath = realPath +"/"+strYmd+ "/" + fileName;
        InputStream input = file.getInputStream();
        FileOutputStream fos = new FileOutputStream(outputPath);
        IOUtils.copy(input, fos);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }
    System.out.println("uploadFile:"+outputPath);
    return outputPath;
}

@RequestHeader

@RequestHeader 是获取请求头中的数据,通过指定参数 value 的值来获取请求头中指定的参数值。其他参数用法和 @RequestParam 完全一样。

@ResponseBody
@GetMapping("/RequestHeader")
public Map test(@RequestHeader("host") String host){
    Map map = new HashMap();
    map.put("header", host);
    return map;
}
@ResponseBody
@GetMapping("/RequestHeader")
public Map test(@RequestHeader Map<String, String> headers){
    Map map = new HashMap();
    map.put("headers", headers);
    return map;
}

相关推荐

  1. SpringBoot使用@RestController处理GETPOST请求

    2024-07-11 22:08:03       21 阅读
  2. 使用axios发送getpost请求

    2024-07-11 22:08:03       60 阅读
  3. GETPOST请求

    2024-07-11 22:08:03       59 阅读
  4. vue使用axios解决跨域getpost请求

    2024-07-11 22:08:03       33 阅读
  5. GET POST 请求方式的区别

    2024-07-11 22:08:03       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 22:08:03       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 22:08:03       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 22:08:03       62 阅读
  4. Python语言-面向对象

    2024-07-11 22:08:03       72 阅读

热门阅读

  1. python的内置函数和模块(网安)

    2024-07-11 22:08:03       25 阅读
  2. (C++哈希02) 四数相加 赎金信

    2024-07-11 22:08:03       23 阅读
  3. 超详细Python教程——面向对象相关知识

    2024-07-11 22:08:03       17 阅读
  4. 2024前端面试每日一更——简述MVVM?

    2024-07-11 22:08:03       25 阅读
  5. 呼叫中心遭遇UDP攻击,如何快速恢复服务?

    2024-07-11 22:08:03       24 阅读
  6. conda 重命名虚拟环境

    2024-07-11 22:08:03       22 阅读
  7. conda

    2024-07-11 22:08:03       20 阅读