SpringMVC学习笔记(七)
1.使用@SessionAttribute 注解处理数据
@SessionAttributes用于在会话中存储Model的属性,一般作用在类的级别。@SessionAttribute是用于获取已经存储的session数据,并且作用在方法的层面上。
请求页面:
<a href="model/testSessionAttribute">超链接测试5:testSessionAttribute</a><br/>
控制器controller:
@SessionAttributes(value="student")
@Controller
@RequestMapping(value="/model")
public class ModelController {
@RequestMapping(value="/testSessionAttribute")
public String testSessionAttribute(Map<String,Object> map) {
Student student=new Student();
student.setsName("张小蟀6");
map.put("student", student);
return "modelSuccess";
}
}
响应页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>成功界面</title>
</head>
<body>
request作用域中:${requestScope.student.sName}<br/>
session作用域中:${sessionScope.student.sName}
</body>
</html>
结果:
**在类的上方加入@SessionAttribute(value=“student”),表示将request作用域中的student对象同时加入session作用域中。@SessionAttribute(value="student"还可以改成@SessionAttribute(type=Student.class),作用是将request作用域中Student类型的对象同时加入session作用域中。 **
2.使用@ModelAttribute注解处理数据
Controller的所有请求在调用前,先执行此@ModelAttribute方法,可用于注解和方法参数中,可以把这个@ModelAttribute特性,应用在BaseController当中,所有的Controller继承BaseController,即可实现在调用Controller时,先执行@ModelAttribute方法。
当我们只需要修改一个对象的属性时,其他信息不变,我们就可以在控制类中加入@ModelAttribute方法。
请求页面:
<center>
<form action="model/testModelAttribute" method="post">
<input type="hidden" value="18" name="so"/>
年龄:<input type="text" name="sAge" />
<input type="submit" value="修改"/>
</form>
</cente
控制器controller:
//使用@ModelAttribute注解处理数据
@ModelAttribute
public void update(Map<String,Object> map) {
//使用带数据的实体对象
Student student=new Student();
student.setsName("张小蟀7");
map.put("student",student);
}
@RequestMapping(value="/testModelAttribute")
public String testModelAttribute(Student student) {
System.out.println("更新后学生的信息:姓名:"+student.getsName()+" 年龄:"+student.getsAge());
return "modelSuccess";
}
响应页面: 同上
结果:
在SpringMVC的Controller中使用@ModelAttribute时:
1.应用在方法上。
2.应用在方法的参数上。
3.应用在方法上,并且方法也使用了@RequestMapping。