【Spring MVC】获取请求的参数
本文最后更新于 1551 天前,其中的信息可能已经有所发展或是发生改变。

[successbox title=”介绍”]
在Spring MVC框架中,获得请求参数的方式有好几种,Controller类的方法的参数也是由Spring容器负责注入的。自动按反射的方式进行注入的。这里都是修改Controller类实现案例。
[/successbox]

1.直接使用方法参数。
[sourcecode language=”java” title=”com.controller.DemoController.java”]
@RequestMapping("demo01")
public String demo01(String goodsName){
System.out.println("demo01 is ran…"+goodsName);
return "index";
}
[/sourcecode]
访问:http://localhost:8080/mvc01/demo/demo01.xhtml?goodsName=傻子

2.使用对象来接收方法参数。
[sourcecode language=”java” title=”com.controller.DemoController.java”]
@RequestMapping("demo02")
public String demo02(Goods goods){
System.out.println("demo02 is ran…");
System.out.println("demo02:goods.getGoodsId()="+goods.getGoodsId());
System.out.println("demo02:goods.getGoodsName()="+goods.getGoodsName());
return "index";
}
[/sourcecode]
访问:http://localhost:8080/mvc01/demo/demo02.xhtml?goodsId=1&goodsName=傻子

3.直接使用ServletAPI。
[sourcecode language=”java” title=”com.controller.DemoController.java”]
@RequestMapping("demo03")
public String demo03(HttpServletRequest request){
System.out.println("demo03 is ran…");
System.out.println("demo03:goodsName="+request.getParameter("goodsName"));
System.out.println("demo03:goodsId="+request.getParameter("goodsId"));
return "index";
}
[/sourcecode]
访问:http://localhost:8080/mvc01/demo/demo02.xhtml?goodsId=1&goodsName=傻子

4.当请求参数的名称与方法名称的参数不一致。
[sourcecode language=”java” title=”com.controller.DemoController.java”]
@RequestMapping("demo04")
public String demo04(@RequestParam("goodsName") String name){
System.out.println("demo04 is ran…");
System.out.println("demo04:goodsName="+name);
return "index";
}
[/sourcecode]
访问:http://localhost:8080/mvc01/demo/demo04.xhtml?goodsName=傻子

5.直接从URL地址上获取请求参数。
[sourcecode language=”java” title=”com.controller.DemoController.java”]
@RequestMapping("demo05/{goodsId}/{goodsName}.xhtml")
public String demo05(@PathVariable int goodsId, @PathVariable String goodsName){
System.out.println("demo05 is ran…");
System.out.println("demo05:goodsId="+goodsId);
System.out.println("demo05:goodsName="+goodsName);
return "index";
}
[/sourcecode]
访问:http://localhost:8080/mvc01/demo/demo05/1/傻子.xhtml

项目源代码:[bdbtn]https://pan.benzhu.xyz/代码/源代码/Spring/源代码/mvc02.rar[/bdbtn]

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇