欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring MVC如何使用@RequestParam注解获取参数

程序员文章站 2022-03-20 13:49:02
目录使用@requestparam注解获取参数@requestparam无法获取参数使用@requestparam注解获取参数创建hello控制器类package com.controller;imp...

使用@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并访问

Spring MVC如何使用@RequestParam注解获取参数

Spring MVC如何使用@RequestParam注解获取参数

注意:如果参数被@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再次访问

Spring MVC如何使用@RequestParam注解获取参数

Spring MVC如何使用@RequestParam注解获取参数

@requestparam无法获取参数

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

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

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