SpringMvc(2)--参数的传递

1.第一种方式:

@Controller
public class HelloController {
	@RequestMapping(value={"/","/hello"})
	public String hello(@RequestParam int id){
		System.out.println("id:"+id);
		System.out.println("hello");
		return "hello";
	}
}

在浏览器中输入http://localhost:8080/springmvc-01/hello?id=123  后台将打印信息,当然@RequestParam也可能指定参数的名字 @RequestParam("userId")

在浏览器中输入:http://localhost:8080/springmvc-01/hello?userId=123  将打印信息


2.在Controller中返回参数给视图:只需要定义一个Map即可

public String hello(int id,Map<String,Object> map){
		System.out.println("id:"+id);
		System.out.println("hello");
		map.put("hello", "my world");
		return "hello";
	}

hello.jsp:

<body>
    <h1>hello:${hello }</h1>
  </body>

在浏览器中输入:http://localhost:8080/springmvc-01/hello?id=123

显示:

hello:my world


使用Model来传递值:
@RequestMapping(value = "/say")
	public String say(Model model) {
		model.addAttribute("hello", "a new world");
		// 这种方式使用Object作为key "suhao"为String类型的,那么key就是string
		model.addAttribute("suhao");
		return "hello";
	}

hello.jsp:
<body>
    <h1>hello:${hello },${string }</h1>
  </body>

在浏览器中输入:http://localhost:8080/springmvc-01/say
显示:

hello:a new world,suhao


取得request:

@RequestMapping(value={"/req"})
	public String req(HttpServletRequest request){
		System.out.println(request.getParameter("username"));
		return "hello";
	}
在浏览器中输入:http://localhost:8080/springmvc-01/req?username=suhao

后台将打印数suhao

其他response 和session等用类似的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值