req.getAttribute返回null

时间:2016-08-30 04:09:05

标签: java jsp

在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>

但是,在声明的总金额中显示textfield null。如果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();
    }

2 个答案:

答案 0 :(得分:1)

您的代码未在请求属性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"));

答案 1 :(得分:0)

您正在尝试在通过servlet之前加载JSP文件,因此JSP页面永远不会收到该参数。

请记住,在ajax调用之后,表单页面不会重新加载,因此您需要使用{{1}}来传递参数。