SpringMVC常用注解-@RequestParam

本文详细解析了@RequestParam注解在Spring MVC中的作用,包括GET和POST请求参数的处理方式,以及不同编码格式下参数的接收方法。同时介绍了如何在无注解情况下通过HttpServletRequest.getParameter()获取参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • @RequestParam
    GET和POST请求传的参数会自动转换赋值到@RequestParam 所注解的方法中的形参上
  1. get请求
@RequestMapping
@RestController
public class TestController {

    @RequestMapping("/test")
    public String test(@RequestParam("name") String userName, @RequestParam("password") String password) {
        return userName + "-" + password;
    }
}
  1. post请求

    form表单post方式提交时,有三种编码格式:
    application/x-www-form-urlencoded:将表单内的数据转换为键值对
    multipart/form-data:既可以上传文件等二进制数据,也可以上传表单键值对,只是最后会转化为一条信息
    text/plain:文件设置为纯文本的形式,浏览器在获取到这种文件时并不会对其进行处理
    post请求时,在http请求头的Content-Type属性可以查看到上面的三种编码格式,该格式用于指定提交表单数据到服务器的编码格式

  • 当post提交的编码格式为application/x-www-form-urlencoded时,@RequestParam直接接收
  • 当post提交的编码格式为multipart/form-data时,@RequestParam直接接收,因为multipart/form-data即可上传文件,也可以上传键值对
@RequestMapping
@RestController
public class TestController {

    @PostMapping("/test")
    public String test(@RequestParam("name") String userName, @RequestParam("password") String password) {
        return userName + "-" + password;
    }
}

3.总结
(1)RequestParam实质是将HttpServletRequest.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。
(2)可以不使用@RequestParam注解,而直接接收,此时要求controller方法中的参数名称要跟form标签中name名称一致

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RequestMapping
@RestController
public class TestController {

    @PostMapping("/test")
    public String test(String userName, String password, HttpServletRequest request) {
        return userName + "-" + password+"-request:"+request.getParameter("userName");
    }
} 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值