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等用类似的方法