一、传值:
第一种:ModelAndvie
css
复制代码
//1.modelAndView
@RequestMapping({"/index"})
public ModelAndView index(){
//查询数据,获取所有的用户信息
List<User> userItems = UserData.userItems;
ModelAndView mav=new ModelAndView();//ModelAndView存值的情况下方法的返回值必须是ModelAndView
//设置数据(模型)
mav.addObject("userItems",userItems);
//设置视图名称
mav.setViewName("index");
return mav;
}
第二种、Model
go
复制代码
//2.model
@RequestMapping("/index")
public String index(Model model){
List<User> userItems = UserData.userItems;
model.addAttribute("userItems",userItems);
return "index";
}
第三种、ModelMap modelMap
dart
复制代码
@RequestMapping("index")
public String index(ModelMap modelMap){
List<User> userItems = UserData.userItems;
modelMap.addAttribute("userItems",userItems);
return "index";
}
第四种、Map
css
复制代码
//4.Map
@RequestMapping("index")
public String index(Map map){
List<User> userItems = UserData.userItems;
map.put("userItems",userItems);
map.put("a","xiaoxiong");
return "index";
}
第五种、request
csharp
复制代码
@RequestMapping("/test")
public String testRequestByServletAPI(HttpServletRequest request) {
User user= new User();
//想request作用域中共享数据(存数据)
request.setAttribute("user", "user");
return "succeed";//request作用域中存数据转发到相应的页面进行取值
}
二、取值
1、对象取值
clike
复制代码
@RequestMapping("/testpojo")
public String testpojo(User user){
//根据实体类获取表单提交的参数
System.out.println(user);
return "testpojo";
}
2、注解取值
clike
复制代码
@RequestMapping("/add")
//RequestParam 的三个参数 value表示name的字段名称required参数是否是必须的
public String add(Integer id,
@RequestParam(value = "userName",required = true,defaultValue = "小熊") String Name,
@RequestParam(value = "age",required = true,defaultValue = "22") Integer age,
@RequestParam(value = "email",required = true,defaultValue = "123@qq.com") String email,
@RequestParam(value = "address",required = true,defaultValue = "湖南长沙") String address){
User user =new User(id,Name,age,email,address);
UserData.userItems.add(user);
//重定向到index进行所有的查询
return "redirect:/index";
}
3、request
clike
复制代码
@RequestMapping("/servltecontrollerapl")
//方法中定义形参
public String ServletControllerApl(HttpServletRequest request) {
//根据页面传入的参数后台进行取值(前端页面传入的参数都全部后端进行取值)
String username = request.getParameter("username");
String pas = request.getParameter("password");
System.out.println(username+"\t"+pas);
return "test";//跳转到参数渲染的页面
}