一、传值:
第一种:ModelAndvie
//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
//2.model
@RequestMapping("/index")
public String index(Model model){
List<User> userItems = UserData.userItems;
model.addAttribute("userItems",userItems);
return "index";
}
第三种、ModelMap modelMap
("index")
public String index(ModelMap modelMap){
List<User> userItems = UserData.userItems;
modelMap.addAttribute("userItems",userItems);
return "index";
}
第四种、Map
//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
@RequestMapping("/test")
public String testRequestByServletAPI(HttpServletRequest request) {
User user= new User();
//想request作用域中共享数据(存数据)
request.setAttribute("user", "user");
return "succeed";//request作用域中存数据转发到相应的页面进行取值
}
二、取值
1、对象取值
@RequestMapping("/testpojo")
public String testpojo(User user){
//根据实体类获取表单提交的参数
System.out.println(user);
return "testpojo";
}
2、注解取值
@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
@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";//跳转到参数渲染的页面
}
文章来源地址https://www.toymoban.com/news/detail-783983.html
文章来源:https://www.toymoban.com/news/detail-783983.html
到了这里,关于SpringMVC传值与取值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!