Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Get attribute from the HttpSession!  RSS feed

 
magic zha
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This servlet will create an HttpSession.The user can enter an attribute name,and if he clicks "Bind",an object will be
bound to the attribute.And if he clicks "Unbind" next time,the will remove the object from the session.
But when i want to unbind the object,and i get the object from the session, it always return NULL!
Why? Following is the code:
import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;

public class TestSession extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession mySession = request.getSession(true);

String sessionName = (String) request.getParameter("Name");

if (sessionName == null) {
sessionName = "";
}

out.println("<HTML>");
out.println("<HEAD><TITLE>Session Binding</TITLE></HTML>");
out.println("<BODY>");
out.println("<FORM METHOD=\"POST\">");
out.println("Name of the session attribute:");
out.println("<INPUT TYPE=\"TEXT\" NAME=\"Name\" VALUE=\"" + sessionName
+ "\"><P>");
out.println("<INPUT TYPE=\"SUBMIT\" NAME=\"Bind\" VALUE=\"Bind\">");
out.println("<INPUT TYPE=\"SUBMIT\" NAME=\"Unbind\" VALUE=\"Unbind\">");
out.println("</FORM>");

if (!sessionName.equals("")) {
if (request.getParameter("Bind") != null) {
String str = new String("Bind");

mySession.setAttribute(sessionName, str);
} else if (request.getParameter("Unbind") != null) {
String str = (String) mySession.getAttribute(sessionName); // it always return NULL! Why?
if (str != null) {
mySession.removeAttribute(request.getParameter("Name"));
}

}
}

out.println("</BODY></HTML>");
}
}
 
Jeffrey Spaulding
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the purpose of sessionName in your code ?

To get the unique id of a session you have the [sessionInstance].getId() method.

But in this code you don't have to check for the existence of a session, since it will be created if there is none (if you have cookies on) or you will get a new session for each request (if you have cookies off).
[ April 18, 2005: Message edited by: Jeffrey Spaulding ]
 
magic zha
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get this sample from a book about Servlets,this servlet is used to bind or unbound an object ,which implements the HttpSessionBindingListener,to an attribute in the session.Now following is the whole code:


The object got from the is always null.why?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!