经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Spring MVC如何使用@RequestParam注解获取参数
来源:jb51  时间:2021/10/25 15:05:02  对本文有异议

使用@RequestParam注解获取参数

创建Hello控制器类

  1. package com.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. @Controller
  6. public class Hello {
  7. @RequestMapping("/show")
  8. public String show(@RequestParam("name")String userName) {
  9. System.out.println(userName);
  10. return "index";
  11. }
  12. }

创建index.jsp

  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="utf-8">
  7. <title>首页</title>
  8. </head>
  9. <body>
  10. <h3>Spring MVC</h3>
  11. </body>
  12. </html>

启动Tomcat并访问

注意:如果参数被@RequestParam注解,那么默认情况下该参数不能为空,如果为空则系统会抛出异常。如果希望允许为空,那么要修改它的配置项required为 false。

  1. package com.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. @Controller
  6. public class Hello {
  7. @RequestMapping("/show")
  8. public String show(@RequestParam(value="name",required=false)String userName) {
  9. System.out.println(userName);
  10. return "index";
  11. }
  12. }

启动 Tomcat再次访问

@RequestParam无法获取参数

application/x-www-form-urlencoded是以表格的形式请求,而application/json则将数据序列化后才进行传递,如果使用了@RequestParam会在Content里面查找对应的数据。

结果因为传递的数据已经被序列化所以不能找到,所以当要使用@RequestParam注解时候应当使用application/x-www-form-urlencoded,而如果想要使用application/json则应当使用@RequestBody获取被序列化的参数

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号