springmvc教程-Controller向jsp传递数据(Model)

介绍

Controller 向 jsp传递数据,有两种方式:

  • 通过 request 对象传递
  • 在方法中加上 Model 形参,然后将参数封装进该对象中,jsp就可以从 request 对象取值
    好处:完全隐藏 servlet api,降低耦合,本文介绍这种

例子

Controller

@RequestMapping("/query")
public String query(Model model){
    model.addAttribute("username","李雷");
    return "result";
}

说明:

model.addAttribute("username","李雷"); 相当于调用了 request.setAttribute("username","李雷");

在jsp中,可以通过 request对象 或 EL表达式 取值

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${username}
<%=request.getAttribute("username")%>
</body>
</html>

原文出处:/show_1IX5DxVSuyU.html