SpringMVC-Controller控制器-RequestParam和RequestHeader注解详解

本文详细介绍了在SpringMVC中如何使用@RequestParam和@RequestHeader注解来获取请求参数和请求头信息。通过添加注解到方法参数,可以轻松地从HTTP请求中提取所需数据,无需像在Servlet中那样手动处理。同时,文章提到可以设置@RequestParam的require属性来指定参数是否为必需,并展示了如何直接使用HttpServletRequest、HttpServletResponse和HttpSession对象。

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

如何获取请求中的参数

我们只需要为方法添加一个形式参数,并在形式参数前面添加@RequestParam注解即可:

@RequestMapping(value = "/index")
public ModelAndView index(@RequestParam("username") String username){
    System.out.println("接受到请求参数:"+username);
    return new ModelAndView("index");
}

我们在html的地址栏中:index/username=123

则会在网页上正常显示index.html页面,并且在HTTP客户端显示:接收到请求参数:123

//spring比servlet方便在,servlet还要在方法中 输入以下代码获取参数

HttpServletRequest request;
request.getparameterMap().keySet()

一旦添加@RequestParam,那么此请求必须携带指定参数,我们也可以将require属性设定为false来将属性设定为非必须:

@RequestMapping(value = "/index")
public ModelAndView index(@RequestParam(value = "username", required = false) String username){
    System.out.println("接受到请求参数:"+username);
    return new ModelAndView("index");
}

如果需要使用Servlet原本的一些类,比如:

@RequestMapping(value = "/index")
public ModelAndView index(HttpServletRequest request){
    System.out.println("接受到请求参数:"+request.getParameterMap().keySet());
    return new ModelAndView("index");
}

直接添加HttpServletRequest为形式参数即可,SpringMVC会自动传递该请求原本的HttpServletRequest对象,同理,我们也可以添加HttpServletResponse作为形式参数,甚至可以直接将HttpSession也作为参数传递:

@RequestMapping(value = "/index")
public ModelAndView index(HttpSession session){
    System.out.println(session.getAttribute("test"));
    session.setAttribute("test", "鸡你太美");
    return new ModelAndView("index");
}

@RequestHeader与@RequestParam用法一致,不过它是用于获取请求头参数的,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值