SpringMVC如何使⽤@RequestParam注解获取参数⽬录
使⽤@RequestParam注解获取参数
@RequestParam⽆法获取参数
使⽤@RequestParam注解获取参数
创建Hello控制器类
ller;
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>
springmvc面试题常用注解<head>
<meta charset="utf-8">
<title>⾸页</title>
</head>
<body>
<h3>Spring MVC</h3>
</body>
</html>
启动Tomcat并访问
注意:如果参数被@RequestParam注解,那么默认情况下该参数不能为空,如果为空则系统会抛出异常。如果希望允许为空,那么要修改它的配置项required为 false。
ller;
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获取被序列化的参数
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论