【问题标题】:Data Injection from controller to jsp page从控制器到jsp页面的数据注入
【发布时间】:2020-04-11 13:43:09
【问题描述】:

我想将数据从控制器方法传递到 jsp 页面。在这样做时,使用 HttpServletRequest.setAttribute()。

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

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

数据流:

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

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

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

【问题讨论】:

  • 您必须使用session 将数据从一个页面发送到另一个页面。

标签: java spring spring-mvc jsp


【解决方案1】:

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

演示这个的演示。

例如:

创建一个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";
    }
}

【讨论】:

  • 我按照您的建议尝试了演示代码。每当我从 jsp2 页面将数据发送回 DemoController2 时,它都会返回一个空值。
  • @SatyamPisal 我已经更新了 account2.jsp 和 DemoController2。现在检查。
  • 我试图同时 GET 和 POST。
  • 是的,它现在正在工作。谢谢您的帮助。我也学到了新东西。 :)
猜你喜欢
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 2016-02-12
  • 2015-10-08
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多