首页 > 解决方案 > 从控制器到jsp页面的数据注入

问题描述

我想将数据从控制器方法传递到 jsp 页面。为此,使用 HttpServletRequest.setAttribute()。

现在,我可以将它传递给下一个 jsp 页面。但是,我想将这些数据保留几页。

在这种情况下,我该怎么办?

数据流:

控制器方法1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> 控制器方法2

我尝试在每个页面中设置属性,但它返回空值,如下

<% request.setAttribute("accId", request.getAttribute("accountId")); %>

标签: javaspringspring-mvcjsp

解决方案


session将数据从一页发送到另一页时,您必须在 jsp 中使用。

一个演示来展示这一点。

例如 :

创建一个DemoController类。

@Controller
public class DemoController {

    @RequestMapping(value = "/getid", method = RequestMethod.POST)
    public String getAccountID(Model model) {
        model.addAttribute("accountId", "ABC1234"); // example 
        return "account";
    }
}

假设,创建一个account.jsp.

<!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=UTF-8">
    </head>
    <body>
     <% 
       String accountId = request.getAttribute("accountId");
       out.println("account.jsp -> " + accountId);
       session.setAttribute("accId", accountId);
     %>
     <form action="account2.jsp" method="post">
       <input type="submit" name="Submit">
     </form>
    </body>
    </html>

使用名称创建另一个页面account2.jsp

<!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=UTF-8">
        </head>
        <body>
         <% 
           String accId = (String) session.getAttribute("accId");
           out.println("account2.jsp -> " + accountId);
           // now you want to sent it to the another controller
           // set the parameter in the session and retrieve it in the controller.
          session.setAttribute("accountId", accId); 
         %>
        </body>
        </html>

创建一个 DemoController2 类:

@Controller
public class DemoController2 {

    @RequestMapping(value = "/getid2", method = RequestMethod.POST)
    public String getAccountId2(HttpSession session) {
        String id = (String) session.getAttribute("accountId"); // example
        System.out.println(id); 
        return "some-page-name";
    }
}

推荐阅读