@RequestParam的具体使用
-
作用:将请求体url里面的参数绑定到controller里对应名字的参数上
-
语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
-
具体代码:
package com.day01springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
/**
* @ Author :ShaoWei Sun.
* @ Date :Created in 20:58 2018/11/16
*/
@RestController
public class HelloController2 {
/**
* 接收普通请求参数
* http://localhost:8080/hello/show16?name=linuxsir
* url参数中的name必须要和@RequestParam("name")一致
* @return
*/
@RequestMapping("show16")
public String test16(@RequestParam("name")String name){
return name;
}
}

/**
* 接收普通请求参数
* http://localhost:8080/hello/show17
* url中没有name参数不会报错、有就显示出来
* @return
*/
@RequestMapping("show17")
public String test17(@RequestParam(value="name",required=false)String name){
return name;
}

/**
* 接收普通请求参数
* http://localhost:8080/hello/show18?name=998 显示为998
* http://localhost:8080/hello/show18?name 显示为hello
* @return
*/
@RequestMapping("show18")
public String test18(@RequestParam(value="name",required=true,defaultValue="hello")String name){
return name;
}
``

本文介绍了Spring MVC中@RequestParam注解的使用,包括如何将URL参数绑定到控制器方法参数,以及如何处理参数的必填性和默认值。示例代码展示了如何处理不同情况的请求参数,帮助理解@RequestParam的作用。
1570

被折叠的 条评论
为什么被折叠?



