Radhika Kulkarni
Radhika Kulkarni

Reputation: 488

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

Upvotes: 0

Views: 1076

Answers (2)

Rishabh Agarwal jain
Rishabh Agarwal jain

Reputation: 117

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.

Upvotes: 0

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

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

Upvotes: 1

Related Questions