gpt4 book ai didi

java - req.getAttribute 返回 null

转载 作者:行者123 更新时间:2023-12-01 09:33:18 25 4
gpt4 key购买 nike

在servlet中我写了

Map<String, Integer> amounts = new HashMap<String, Integer>();
if(req.getParameter("from").equals("details")){


employeeInformation.put("employeeName", retrievedUserInfo.getName());

employeeInformation.put("employeeDepartment", retrievedUserInfo.getDepartment());
employeeInformation.put("employeeDesignation", retrievedUserInfo.getDesignation());
req.setAttribute("total", amounts.get("DayCareAmount"));

Gson gson = new Gson();
String jsonString = gson.toJson(employeeInformation);
System.out.println("Servlet json from user details" + jsonString);
PrintWriter writer = resp.getWriter();
writer.write(jsonString);

}

我用 JavaScript 编写了

<form action="./ssoServlet?from=amount" method="post">
<% String amount = (String) request.getAttribute("total");%>
Total amount claimed
<input type="text" name="total" id="total" value = <%=amount %> >
</form>

但是,在 claim 总额文本字段中显示空值。如果 req.setAttribute 和 getAttribute 不起作用,我可以写两个 jsonStrings 吗?我应该如何在js中检索它?

我检索数据的js函数是:

function fetchDetails(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// alert("s");
//alert(xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {

var JSONobj = JSON.parse(xhttp.responseText);
document.getElementById("name").value = JSONobj.employeeName ;
document.getElementById("department").value = JSONobj.employeeDepartment ;
document.getElementById("designation").value = JSONobj.employeeDesignation ;

}
};
xhttp.open("POST", "./ssoServlet?from=details", true);
xhttp.send();
}

最佳答案

您的代码未在请求属性中添加任何内容total:

Map<String, Integer> amounts = new HashMap<String, Integer>();
// amounts Map is empty, so amounts.get("DayCareAmount") will return null
req.setAttribute("total", amounts.get("DayCareAmount"));

为了确保一切正常,首先让您的代码更简单,这样可能出错的地方就会更少:

req.setAttribute("total", 42);

现在检查 42 是否出现在您的网页中。如果是这样,您可以返回到您的代码片段:

Map<String, Integer> amounts = new HashMap<String, Integer>();
amounts.put("DayCareAmount", 42);
req.setAttribute("total", amounts.get("DayCareAmount"));

关于java - req.getAttribute 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39218628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com