当前位置:首页 > 通信资讯 > 正文

spring mvc教程(springmvc怎么使用)

使用@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教程(springmvc怎么使用)

spring mvc教程(springmvc怎么使用)

注意:如果参数被@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教程(springmvc怎么使用)

spring mvc教程(springmvc怎么使用)

@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

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。