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