如果不知道如何初始一个springMvc的项目请点击这里
第一种:ModelAndView
第一步:
Pojo类写对应的方法:
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String view="success";//这里的success是我配置的转换的下一个页面
ModelAndView modelAndView=new ModelAndView(view);
modelAndView.addObject("name","我是Code-zyc");
return modelAndView;
}
第二步:
在index 写对应的链接:
<!-- 我的目录前面有个hi-->
<a href="/hi/testModelAndView"> testModelAndView</a>
第三步:
在对应的 success.jsp页面接收数据:
name:${requestScope.name}
第四步:
跑起来得结果:
第二种:Map
第一步:
Pojo类写对应的方法:
@RequestMapping("/textMap")
public String textMap(Map<String,Object> map){
map.put("name","我是Code-zyc");
return "success";
}
第二步:
在index.jsp里面写对应的链接:
<a href="/hi/textMap"> textMap</a>
第三步:
在success.jsp 写接应的代码:
Map.name:${requestScope.name}
第四步:
run:
注:前面两种都是储存在request域中!
第三种:SessionAttributes
第一步Pojo:注意要在类的上面写上注解@SessionAttributes
@Controller
@RequestMapping("/hi")
@SessionAttributes(value = {"username"})
public class HelloWorld {
@RequestMapping("/textSessionAttributes")
public String textSessionAttributes(Map<String,Object> map){
map.put("name","我是Code-zyc");
map.put("username","Code-zyc");
return "success";
}
}
这里注解里面的username 写上代表 在map里面的key为username的数据都储存到session域之中 而name则不会。结果说话
第二步:
index.jsp 加入链接:
<a href="/hi/textSessionAttributes">textSessionAttributes </a>
第三步:
sucess.jsp加入代码:
Request.name=${requestScope.name}
<br>
Seesion.name=${sessionScope.name}
<br>
Request.username=${requestScope.username}
<br>
Seesion.username=${sessionScope.username}
<br>
第四步:
run:
注意:SessionAttribute 除了value 属性还有一个type属性 效果就是这样:
只改注释里面的内容:
得到的结果如下:
所以 只要map 里面value是 string的就可以被存进session域里面
第四种:ModelAttribute
原理被他注释的方法在其他方法调用之前必须经过他
第一步Pojo:
@ModelAttribute
public void getUser(@RequestParam(value = "id",required = false) Integer id,
Map<String,Object> map){
if(id!=null){
System.out.println("从数据库之中调数据了");
User user=new User(1,"zyc","123456",null);
map.put("user",user);
}
}
@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user2){
System.out.println(" 修改改后:"+user2.toString());
return SUCCESS;
}
第二步:
index.jsp:
<form action="/hi/testModelAttribute" method="post">
id:<input type="text" name="id">
<br>
name:<input type="text" name="name">
<br>
<input type="submit"value="Submit">
</form>
第三步:run:
这是填写表单的内容 我没填写密码!
ideal的输出内容:
这就是 其储存方式,大致原理如下:
上述是默认下,当然你也可以使用自己的如下: