传值类型
student.jsp
${requestScope.student}
可通过以下四种方式获得值
ModelAndView
@RequestMapping("test1.do")
public ModelAndView test1(){
ModelAndView modelAndView = new ModelAndView("student"); //view:success
Address address = new Address("bj", "gz");
Student student = new Student(1, "ls", address);
modelAndView.addObject("student",student);
return modelAndView;
ModelMap
@RequestMapping("test2.do")
public String test2(ModelMap modelMap){
Address address = new Address("bj", "gz");
Student student = new Student(2, "ls", address);
modelMap.put("student",student); //request域
return "student";
}
Map
@RequestMapping("test3.do")
public String test3(Map<String,Object> m){
Address address = new Address("bj", "gz");
Student student = new Student(3, "ls", address);
m.put("student",student);//request域
return "student";
}
Model
@RequestMapping("test4.do")
public String test4(Model model){
Address address = new Address("bj", "gz");
Student student = new Student(4, "ls", address);
model.addAttribute("student",student);//request域
return "student";
}
在session中存值
//写在类上
//在该类中所有名字为student的对象在添加进去request域同时加入session域
@SessionAttributes(value = "student")
//在该类中所有Student和Address的对象在添加进去request域同时加入session域
@SessionAttributes(types = {Student.class,Address.class})
ModelAttribute前置方法
@ModelAttribute//在任何一次请求前,都会先执行@ModelAttribute修饰的方法
public void queryStudentById(Map<String,Object> map){
Student student = new Student(10, "model", new Address("bj", "gz"));
// 约定:map的key 就是方法参数类型(Student)的首字母小写 会将map对象传到Student里
// map.put("student",student);
// 若不用上述方法,可在调用方法前加@ModelAttribute("key")
map.put("stu",student);
}
@RequestMapping("test5.do")
// public String test5(Student student) 第一种方式
public String test5(@ModelAttribute("stu")Student student){
//假设从前端也传回来一个student,只有name属性=zs
System.out.println(student.getName());//输出zs而不是,model
System.out.println(student);//除了name,其他属性同ModelAttribute
return "success";
}
JSON
Controller
@ResponseBody//返回的不是一个View页面,而是一个ajax调用的返回值(JSON)
@RequestMapping("test6.do")
public List<Student> testJson(@RequestBody Student student){//接收JSON并转换为Student
List<Student> students = new ArrayList<>();
return students;
}
jsp
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
$("#testJson").click(function (){
$.post(
"modelAndView/testJson",//服务器地址
function (result) {
for(var i =0;i<result.length ;i++)
alert(result[i].id+result[i].name)
}
)
}
);
function testAjax() {//方法二
$.ajax({
url:"${pageContext.request.contextPath}/modelAndView/testJson",
//data表示发送的数据
data:Json.stringify({name:"zs",age:22}),
//表示发送请求的数据为JSON字符串
contentType:"application/json;charset=utf-8",
//定义回调的格式为JSON字符串,可以省略
dataType:"json",
success:function (data) {
alert(data.name+data.age)
}
})
}
})
</script>