Spring MVC如何使用@RequestParam注解获取参数
作者:云淡风轻58 时间:2021-05-28 14:20:19
使用@RequestParam注解获取参数
创建Hello控制器类
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
@RequestMapping("/show")
public String show(@RequestParam("name")String userName) {
System.out.println(userName);
return "index";
}
}
创建index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>首页</title>
</head>
<body>
<h3>Spring MVC</h3>
</body>
</html>
启动Tomcat并访问
注意:如果参数被@RequestParam注解,那么默认情况下该参数不能为空,如果为空则系统会抛出异常。如果希望允许为空,那么要修改它的配置项required为 false。
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
@RequestMapping("/show")
public String show(@RequestParam(value="name",required=false)String userName) {
System.out.println(userName);
return "index";
}
}
启动 Tomcat再次访问
@RequestParam无法获取参数
application/x-www-form-urlencoded是以表格的形式请求,而application/json则将数据序列化后才进行传递,如果使用了@RequestParam会在Content里面查找对应的数据。
结果因为传递的数据已经被序列化所以不能找到,所以当要使用@RequestParam注解时候应当使用application/x-www-form-urlencoded,而如果想要使用application/json则应当使用@RequestBody获取被序列化的参数
来源:https://blog.csdn.net/dwenxue/article/details/81354692
标签:Spring,MVC,@RequestParam,参数
0
投稿
猜你喜欢
Java+MySQL实现学生信息管理系统源码
2023-11-28 04:29:31
Java Cookie与Session实现会话跟踪详解
2022-12-22 08:59:13
java解析json数组方式
2023-08-10 17:22:14
使用itextpdf操作pdf的实例讲解
2022-11-16 00:22:43
java多线程详细总结
2023-01-10 14:16:04
java使用链表实现约瑟夫环
2022-03-21 18:59:35
IDEA使用SpringAssistant插件创建SpringCloud项目
2021-06-06 10:47:46
SpringBoot实现二维码扫码登录的原理及项目实践
2022-02-25 22:31:15
Java基于ArrayList实现群主发红包功能
2022-04-06 20:34:09
Java实现XML文件学生通讯录
2023-07-23 19:21:49
spring boot springMVC扩展配置实现解析
2023-11-25 10:32:53
Java中BorderLayout布局管理器的两种排列方式
2022-03-14 08:04:35
opencv配置的完整步骤(win10+VS2015+OpenCV3.1.0)
2023-06-28 14:55:19
Java设计模式之抽象工厂模式实例详解
2023-11-29 04:04:57
Winform让DataGridView左侧显示图片
2021-09-24 03:50:38
SQLite在C#中的安装与操作技巧
2023-04-19 08:31:12
c# socket编程udp客户端实现代码分享
2023-06-16 05:03:31
Java File类提供的方法与操作
2023-08-29 09:10:41
java实现双色球彩票游戏
2022-06-29 12:39:45
深入分析Java内存区域的使用详解
2023-09-25 23:21:29