-1

In the following code i am trying to get the name from client and set in the session but there getAtrribute("unm") returning the null value...

    res.setContentType("text/html");
    PrintWriter op=res.getWriter();
    HttpSession ss=req.getSession(true);

    String sunm=(String)req.getAttribute("unm");

    System.out.println(sunm);
    ss.setAttribute("UserName", sunm);  
    op.println("<br><center>The user for this session is :"+sunm+"</center>");

please help me...

Shivaji More
  • 310
  • 1
  • 2
  • 9

2 Answers2

0

Use getParameter() method instead of getAttribute(), getAttribute() is for only server side.

res.setContentType("text/html");
PrintWriter op=res.getWriter();
HttpSession ss=req.getSession(true);

String sunm=(String)req.getParameter("unm");

System.out.println(sunm);
ss.setAttribute("UserName", sunm);  
op.println("<br><center>The user for this session is :"+sunm+"</center>");

For reference: Difference between getAttribute() and getParameter()

Community
  • 1
  • 1
Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90
0

The problem you are having is that you are getting a session attribute that hasn't been set.So you would have to get the parameter in which the name of the client is inputted,then you can set the session attribute based on the parameter that is being retrieved. In code terms,in order to get the parameter you use the getParameter() method.

 res.setContentType("text/html");
  PrintWriter op = res.getWriter();
  HttpSession ss= req.getSession(true);

  String sunm = (String)req.getParameter("unm");
  System.out.println(sunm);

and then set the session attribute based on the variable sunm

ss.setAttribute("Username",sunm);
op.println("<br><center>The user for this session is:"+sunm+"</center>");

You can read the reference that Ramesh K added to better understand the difference between getAttribute() and getParameter().

Omiye Jay Jay
  • 409
  • 5
  • 10
  • 19