java请求。getAttribute返回null
我在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>
但是,在总索赔金额中,显示文本字段null。如果需要。setAttribute和getAttribute不起作用我可以写两个JSONString吗?我应该如何在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();
}
# 1 楼答案
您试图在通过servlet之前加载JSP文件,因此JSP页面永远不会收到该参数
记住,表单页面不会在ajax调用后重新加载,因此需要使用
RequestDispatcher
来传递参数# 2 楼答案
您的代码没有在请求属性
total
中放入任何内容:为了确保一切正常,首先要简化代码,这样可能出错的事情就更少了:
现在检查42是否出现在你的网页上。如果是这样,您可以回到您的代码片段: