简体   繁体   中英

req.getAttribute returning null

In servlet i have written

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);

    }

and in javascript i have written

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

However, in total amount claimed textfield null is displayed. If req.setAttribute and getAttribute doesnt work can i write two jsonStrings? How should i retrieve it in js?

My js function which retrieves data is:

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();
    }

Your code doesn't put anything in request attribute 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"));

To make sure that everything is working right, first make your code simpler so there are fewer things that could be wrong:

req.setAttribute("total", 42);

Now check if the 42 shows up in your web page. If so, you can go back to your snippet:

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

You are trying to load the JSP file before going through the servlet, so the parameter is never received by the JSP page.

Remember that form page does not reload after the ajax call, so you need to use the RequestDispatcher to pass on the parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM