该方法和ModelAndView方法相似,只是Model和View分开来了,通过返回一个String来找到View,Model是注入到Controller的一个参数,通过对它添加属性,在jsp端读取值。代码如下:
@Controller
public class HelloWorldController {
String message = "Welcome to Spring MVC!";
@RequestMapping("/hello")
public String showMessage(Model model) {
model.addAttribute("userList", GetUserList());
return "helloworld";
}
public List<User> GetUserList()
{
List<User> lst=new ArrayList<User>();
User user1=new User();
user1.setName("zhangsan");
user1.setAge(10);
lst.add(user1);
User user2=new User();
user2.setName("lisi");
user2.setAge(33);
lst.add(user2);
return lst;
}
}
JSP页面中:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Spring 4 MVC -HelloWorld</title>
</head>
<body>
<c:forEach items="${userList}" var="user">
${user.name} ${user.age}
<br />
</c:forEach>
</body>
</html>
Spring MVC整合Freemarker基于注解方式