java - 从控制器到jsp页面的数据注入
问题描述
我想将数据从控制器方法传递到 jsp 页面。为此,使用 HttpServletRequest.setAttribute()。
现在,我可以将它传递给下一个 jsp 页面。但是,我想将这些数据保留几页。
在这种情况下,我该怎么办?
数据流:
控制器方法1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> 控制器方法2
我尝试在每个页面中设置属性,但它返回空值,如下
<% request.setAttribute("accId", request.getAttribute("accountId")); %>
解决方案
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";
}
}
推荐阅读
- windows - 尽管文件可以打开,但由于“文件名或编号错误”而无法删除
- c - 在C中初始化由枚举索引的字符串数组
- c# - S22.Imap 不适用于作为附件添加的 .msg(Outlook 邮件项目)文件
- c# - 如何将数据库值添加到包含类作为对象的字典中
- python - 我怎么知道用户输入中一个句子的长度 - 不是整个输入 - 只是句子
- sql - 如果有时不存在,Oracle SQL 如何选择(或包含数据)?
- vue.js - TypeError:_vm.moment 不是 Vuejs 中的函数
- groovy - 使用 groovy 集合设置 JMter 变量(JSR223 PostProcessor)
- excel - 从 Outlook 激活打开的 Excel 工作簿
- java - Java用命令行覆盖依赖