1. How can I declare methods within my JSP page?

You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions.

Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:

<%!

      public String whereFrom(HttpServletRequest req) {

      HttpSession ses = req.getSession();

      ...

      return req.getRemoteHost();

     }

%>

<%

     out.print("Hi there, I see that you are coming in from  ");

%>

<%= whereFrom(request) %>

 

2. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?

 Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.

Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usuage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

 

3. How can I enable session tracking for JSP pages if the browser has disabled cookies?

 We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting.

URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response.

Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

 

Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object.

 

Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages.

Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.

hello1.jsp

<%@ page session="true" %>

<%

  Integer num = new Integer(100);

  session.putValue("num",num);

 String url =response.encodeURL("hello2.jsp");

%>

<a href='<%=url%>'>hello2.jsp</a>

hello2.jsp

<%@ page session="true" %>

<%

  Integer i= (Integer )session.getValue("num");

  out.println("Num value in session is "+i.intValue());

%>

 

4. Can you make use of a ServletOutputStream object from within a JSP page?

 No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:

<%@ page buffer="none" %>

 

5. How do I use a scriptlet to initialize a newly instantiated bean?

 jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

<jsp:useBean id="foo" class="com.Bar.Foo" >

  <jsp:setProperty name="foo" property="today" value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())

%>"/>

<%-- scriptlets calling bean setter methods go here --%>

</jsp:useBean >

 

6. Can I invoke a JSP error page from a servlet?

Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error: java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained

The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:

protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e)

   throws ServletException, IOException {

    request.setAttribute ("javax.servlet.jsp.jspException", e);

    getServletConfig().getServletContext().getRequestDispatcher(errorPageURL).forward(request, response);

}

 

public void doPost(HttpServletRequest request, HttpServletResponse response) {

 try {

 // do something

 } catch (Exception ex) {

  try {

   sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

}

 

7. How can I get to print the stacktrace for an exception occuring within my JSP page?

By printing out the exception's stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method.

However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:

<%@ page isErrorPage="true" %>

<%

out.println("<pre>");

PrintWriter pw = response.getWriter();

exception.printStackTrace(pw);

out.println("</pre>");

%>

 

 

8. Is there a way I can set the inactivity lease period on a per-session basis?

Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:

<%

    session.setMaxInactiveInterval(300);

%>

would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

 

9. How can I get to view any compilation/parsing errors at the client while developing JSP pages?

With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:

jsp.initparams=sendErrToClient=true

This will cause any compilation/parsing errors to be sent as part of the response to the client.

 

10. Is there a way to reference the "this" variable within a JSP page?

Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page.

 

11. Can JSPs and servlets share the same session?

Yes, of course. Remember, JSPs are always translated into their servlet equivalent before they are initialized and ready to process incoming requests. JSP pages are also provided with the session implicit object which allows them to completely manage the session, including its creation and invalidation.

 

12. How does the "application" scope work with the useBean tag?

 

Consider the following example:

<useBean id="counter" class="foo.Counter" scope="application" />

In this example, when the Counter bean is instantiated, it is placed within the servlet context, and can be accessed by any JSP or servlet that belong to the application (i.e. belongs to the same servlet context).

The servlet equivalent of the above useBean action is:

getServletContext().setAttribute("counter", new foo.Counter());

If the bean was previously created by another JSP or servlet and was placed within the application (servlet) context, the useBean action would then serve to retrieve the object.

The servlet equivalent of retrieving a bean from the application context is:

foo.Counter ctr = (foo.Counter) getServletContext().getAttribute("counter");

 




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)