Bat
Bat

Reputation: 135

How session gets create in JSP?

I am learning JSP. I am not able to find out how sessions got created in JSP.

what I know till now is session is implicit object creates under _jspService method. So I manually created session. In below JSP code I created session same as it automatically creates in index_jsp but i am getting value as null. So any body can explain me why I am getting null?

<%@ page import ="java.util.*" session="false" %>
<%
javax.servlet.http.HttpSession session = null;
session = pageContext.getSession();
%>
<html>
<body>
<%=session  %> 
</body>

Upvotes: 0

Views: 3428

Answers (2)

Vasu
Vasu

Reputation: 22422

Can explain me why I am getting null for session ?

The session in the JSP file will be disabled if you set the session attribute to false i.e., session="false", you can look here for more details.

I am not able to find out how sessions got created in JSP.

httpsession object will be created (& maintained) by the servlet container when you invoke request.getSession(true); from JSP (because request is also an implicit object in JSP).

public HttpSession getSession(boolean create) : Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null.

You can refer the API here

So, to create the session from your code you change it as:

<%
javax.servlet.http.HttpSession session = request.getSession(true);
// you can session object from now add attributes,
// get attributes, remove attributes, etc..
%>

Also, once the session is created (as shown above using request.getSession(true)), you need to use request.getSession() to retrive the same session object.

In other words, in your whole application,

(1) Create the session ONLY ONCE during the user login time in LoginServlet or LoginController class using request.getSession(true)

(2) And then use request.getSession() in all other servlet/controller methods.

As a side note, I strongly suggest you to use Controller (like using Spring) or Servlet classes to write the Java code because JSP is meant only for the presentation layer (to display the html content).

Upvotes: 1

code_angel
code_angel

Reputation: 1537

As you said:

session is implicit object created under _jspService method

The JSP file is compiled by the Jasper Engine to a java class. Despite of the code you have writen in the JSP, in the created Java class there are some preparation of these implicit objects.
Therefore you don't need to do it again.

You can just use them. You can write in your JSP the code:

From EL:<br>
sessionScope.name: ${sessionScope.name}<br>
<br>
From Scriptlet. <br>
<%=session.getAttribute("name")%>

And you get the same output twice: the value of the session attribute "name".

In example of a JSP with content:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title</title>
</head>
<body>
From EL:<br>
sessionScope.name: ${sessionScope.name}<br>
<br>
From Scriptlet. <br>
<%=session.getAttribute("name")%>
</body>
</html>

Will result in a java class file:

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class testcompile_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List<String> _jspx_dependants;

  private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;

  public java.util.List<String> getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=UTF-8");
      response.setHeader("X-Powered-By", "JSP/2.3");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write("\r\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>Title</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("From EL:<br>\r\n");
      out.write("sessionScope.name: ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionScope.name}", java.lang.String.class, (PageContext)_jspx_page_context, null));
      out.write("<br>\r\n");
      out.write("<br>\r\n");
      out.write("From Scriptlet. <br>\r\n");
      out.print(session.getAttribute("name"));
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

As you can see in the _jspService method there are lines:

HttpSession session = null;
...
session = pageContext.getSession();

Basically this is the implicit session object. Your code follow after that and can use it.

EDIT:

With <%@ pagesession="false" %> you say "i don't need the session". So the session is not bond in the pageContext. Therefore you if you call pageContext.getSession() you receive null;

If you need it you have to use:

request.getSession();

Upvotes: 1

Related Questions