JavaServer Pages (JSP) FAQ From jGuru

How do I mix JSP and SSI #include?
Created:1999-09-03 00:00:00.0
Modified:2000-02-01 08:11:09.283
Primary contributor:Alex Chaffee

If you're just including raw HTML, use the #include directive as usual inside your .jsp file.


<!--#include file="data.inc"-->

But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. Ronel Sumibcay ([email protected]) says: If your data.inc file contains jsp code you will have to use


<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files.

How can I implement a thread-safe JSP page?
Created:1999-11-05 00:00:00.0
Modified:1999-11-11 16:04:51.478
Primary contributor:Govind Seshadri

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface.

This is done by adding the directive

<%@ page isThreadSafe="false" %>

within your JSP page.

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

Can a JSP page process HTML FORM data?
Created:1999-11-05 00:00:00.0
Modified:2000-06-23 09:30:16.942
Primary contributor:Govind Seshadri

Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:

<% 
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units"))
                                            .intValue();
%>

or

<%= request.getParameter("item") %>

See the Javaworld article "Advanced Form Processing using JSP" by Govind Seshadri for complete details.

How does JSP handle run-time exceptions?
Created:1999-11-05 00:00:00.0
Modified:1999-11-17 00:41:16.608
Primary contributor:Govind Seshadri

You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:

<%@ page errorPage="error.jsp" %>

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.

Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage="true" %>

the Throwable object describing the exception may be accessed within the error page via the exception implicit object.

Note: You must always use a relative URL as the value for the errorPage attribute.

What JSP lifecycle methods can I override?
Created:1999-11-05 00:00:00.0
Primary contributor:Govind Seshadri

You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

How can I override the jspInit() and jspDestroy() methods within a JSP page?
Created:1999-11-05 00:00:00.0
Modified:1999-11-17 00:42:06.146
Primary contributor:Govind Seshadri

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

<%! 
	public void jspInit() {
		. . .
	}
%>

<%! 	
public void jspDestroy() {
		. . .	
	}
%>

How do I include static files within a JSP page?
Created:1999-11-05 00:00:00.0
Modified:1999-11-17 00:42:35.121
Primary contributor:Govind Seshadri

Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:

<%@ include file="copyright.html" %>

Do note that you should always supply a relative URL for the file attribute.

Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

How do I use comments within a JSP page?
Created:1999-11-05 00:00:00.0
Modified:1999-12-10 20:21:00.47
Primary contributor:Govind Seshadri

You can use "JSP-style" comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client.

For example:

<%-- the scriptlet is now commented out
  <%
	out.println("Hello World");
  %>
--%>

You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

<!-- (c)1999 jGuru.com -->

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

<%
//some comment

/** 
yet another comment
**/
%>

How do I perform browser redirection from a JSP page?
Created:1999-11-05 00:00:00.0
Modified:1999-12-02 22:41:38.27
Primary contributor:Govind Seshadri

You can use the response implicit object to redirect the browser to a different resource, as:

response.sendRedirect("http://www.foo.com/path/error.html");

You can also physically alter the Location HTTP header attribute, as shown below:

<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>

How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
Created:1999-11-05 00:00:00.0
Modified:2000-05-24 17:45:43.886
Primary contributor:Govind Seshadri

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser.

Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

However, please note that there are some problems with disabling page caching under IE 5.0 due to the unique buffering requirements of the browser. Please see the Microsoft knowledge base for details:

http://support.microsoft.com/support/kb/articles/Q222/0/64.ASP
http://support.microsoft.com/support/kb/articles/Q234/2/47.ASP

My JSP file compiles just fine...but I always get a NoClassDefFoundError when I try to access a bean via the useBean tag. Why?
Created:1999-11-08 22:58:02.263
Modified:1999-11-08 23:02:10.261
Primary contributor:Govind Seshadri

Make sure your beans belong to a package, and that you are fully qualifying the bean when indicating the value for the class attribute. For example, if your bean abc.class belongs to the package foo, make sure you indicate the value for the class attribute as:

<useBean id="mybean" class="foo.abc" scope="session" />

and not as:

<useBean id="mybean" class="abc" scope="session" />

Are there any JSP engines which support JavaScript?
Created:1999-11-09 13:57:03.48
Modified:2000-05-29 12:23:56.753
Primary contributor:Govind Seshadri

Yes. Resin 1.0 from Caucho Technologies supports both Java and JavaScript for scripting and implements JSP 1.0.

PolyJSP from Plenix supports Java, JavaScript and WebL for scripting, and implements JSP 0.92.

Where can I find the complete list of commercial vendor support for JSP?
Created:1999-11-09 19:33:40.578
Modified:2000-05-29 09:50:08.647
Primary contributor:Govind Seshadri

Luc Saint-Elie maintains a regularly updated list of products which support the JSP API. You can access it at http://www.interpasnet.com/JSS/textes/jsp2.htm.

JSP 0.91 and 0.92 specifications are no longer available at java.sun.com. Is there somewhere else I can download them?
Created:1999-11-09 19:52:20.622
Modified:2000-05-29 09:52:00.471
Primary contributor:Govind Seshadri

Yes. You can download JSP 0.91 specification at http://www.kirkdorffer.com/jspspecs/jsp091.html.

JSP 0.92 specification can be downloaded from http://www.kirkdorffer.com/jspspecs/jsp092.html

How does a servlet communicate with a JSP page?
Created:1999-11-09 20:41:16.277
Modified:1999-12-02 22:23:59.416
Primary contributor:Govind Seshadri

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request,
		       HttpServletResponse response) {

	try {
	      govi.FormBean f = new govi.FormBean();
              String id = request.getParameter("id");
	      f.setName(request.getParameter("name"));
	      f.setAddr(request.getParameter("addr"));
	      f.setAge(request.getParameter("age"));
              //use the id to compute          
              //additional bean properties like info 
              //maybe perform a db query, etc.
              // . . .
              f.setPersonalizationInfo(info);
	      request.setAttribute("fBean",f);
	      getServletConfig().getServletContext().getRequestDispatcher
                           ("/jsp/Bean1.jsp").forward(request, response);
	} catch (Exception ex) {
                . . .
	}
 }

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
<jsp:getProperty name="fBean" property="name" />
<jsp:getProperty name="fBean" property="addr" />
<jsp:getProperty name="fBean" property="age" />
<jsp:getProperty name="fBean" property="personalizationInfo" />

Show me an example of POST request chaining using JSPs and servlets.
Created:1999-11-09 21:03:49.567
Modified:2000-06-28 14:25:36.303
Primary contributor:Govind Seshadri

The following code example demonstrates how request chaining can be implemented using a combination of JSPs and servlets.

Consider the following JSP page, say Bean1.jsp, which essentially instantiates the bean fBean, places it in the request, and forwards the call to the servlet JSP2Servlet. Observe the way the bean is instantiated - here we automatically call the bean's setter methods for properties which match the names of the posted form elements, while passing the corrosponding values to the methods.

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
<jsp:setProperty name="fBean" property="*" />
<jsp:forward page="/servlet/JSP2Servlet" />

The servlet JSP2Servlet now extracts the bean passed to it from the request, makes changes using the appropriate setters, and forwards the call to another JSP page Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller, can also place additional beans if necessary, within the request.

public void doPost (HttpServletRequest request,
       HttpServletResponse response) {

try {
    FormBean f = (FormBean) request.getAttribute ("fBean"); 
    f.setName("Mogambo"); 
    // do whatever else necessary
   getServletConfig().getServletContext().
         getRequestDispatcher("/jsp/Bean2.jsp").
             forward(request, response);
	} catch (Exception ex) {
		. . .
	}
}

The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that may have been passed by the controller servlet) from the request and extract its properties.

<html>
<body>
Within JSP2

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/> <jsp:getProperty name="fBean" property="name" /> </body> </html>

With Sun's JSWDK 1.0, I can access only the class file for the servlet generated from my JSP page. Is there a way to see the Java source for the generated servlets?
Created:1999-11-09 21:49:44.526
Primary contributor:Govind Seshadri

For Sun's JSWDK 1.0, set the initialization parameter:

jsp.initparams=keepgenerated=true

This can be found within the web-inf/servlets.properties file for your application.

When this is passed to your JSP servlet, it will preserve the Java source along with the class file in the work subdirectory for the engine.

Is there a way to reference the "this" variable within a JSP page?
Created:1999-11-09 22:04:11.708
Primary contributor:Govind Seshadri

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.

Can a JSP page instantiate a serialized bean?
Created:1999-11-09 23:40:38.843
Modified:2000-06-23 07:39:28.002
Primary contributor:Govind Seshadri

No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:

<jsp:useBean id="shop"  type="shopping.CD" beanName="CD"  />
<jsp:getProperty name="shop" property="album" />

A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute.

Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

For details, see the JSP 1.1 specification at http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html.

How do I set a cookie within a JSP page?
Created:1999-11-10 00:13:44.556
Modified:1999-11-17 00:43:56.132
Primary contributor:Govind Seshadri

Setting cookies from within a JSP page is similar to the way they are done within servlets. For example, the following scriptlet sets a cookie "mycookie" at the client:

<%
       Cookie mycookie = new Cookie("aName","aValue");
       response.addCookie(mycookie);
 %>

Typically, cookies are set at the beginning of a JSP page, as they are sent out as part of the HTTP headers.

How can I delete a cookie from within a JSP page?
Created:1999-11-10 00:26:44.489
Modified:1999-11-17 00:44:20.328
Primary contributor:Govind Seshadri

A cookie, mycookie, can be deleted using the following scriptlet:

<%
     Cookie killMyCookie = new Cookie("mycookie", null);
     killMyCookie.setMaxAge(0);
     killMyCookie.setPath("/");
     response.addCookie(killMyCookie);
%>

How can I get to view any compilation/parsing errors at the client while developing JSP pages?
Created:1999-11-10 09:45:03.28
Primary contributor:Govind Seshadri

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.

Is there a way I can set the inactivity lease period on a per-session basis?
Created:1999-11-10 10:41:41.069
Modified:1999-11-17 00:44:50.345
Primary contributor:Govind Seshadri

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.

Can I stop JSP execution while in the midst of processing a request?
Created:1999-11-10 13:09:40.698
Modified:1999-11-17 00:45:13.261
Primary contributor:Govind Seshadri

Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing.

For example, consider:

<% 
      if (request.getParameter("foo") != null) {
          // generate some html or update bean property 
      } else {

      /* output some error message or provide redirection 
          back to the input form after creating a memento 
          bean updated with the 'valid' form elements that were input.
          this bean can now be used by the previous form to initialize 
          the input elements that were valid
          then, return from the body of the _jspService() method to 
          terminate further processing   */
  
          return;
      }
%>

How can I declare methods within my JSP page?
Created:1999-11-14 20:28:07.066
Modified:1999-12-21 20:47:22.092
Primary contributor:Govind Seshadri

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) %>

What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Created:1999-11-15 10:33:33.753
Modified:2000-06-03 14:29:16.144
Primary contributor:Govind Seshadri

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.

How can I enable session tracking for JSP pages if the browser has disabled cookies?
Created:1999-11-15 20:59:08.974
Modified:1999-12-18 21:39:47.519
Primary contributor:Govind Seshadri

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());
%>

Can you make use of a ServletOutputStream object from within a JSP page?
Created:1999-11-17 17:52:37.677
Modified:1999-12-21 19:54:05.495
Primary contributor:Govind Seshadri

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" %>

How do I use a scriptlet to initialize a newly instantiated bean?
Created:1999-11-17 18:37:40.198
Primary contributor:Govind Seshadri

A 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 >

How can I send email from a JSP page?
Created:1999-11-19 12:48:49.419
Primary contributor:Govind Seshadri

You can send email from any JSP engine (like the JSWDK reference implementation) that supports the Sun specific sun.net.smtp package.

(Statutory warning: Using internal Sun-specific packages is not an approach jGuru recommends, as it will prevent your JSP pages from being truly portable.)

The following scriptlet makes use of the SmtpClient class to send an email from within a JSP page.

<%@ page import="sun.net.smtp.SmtpClient, java.io.*" %>
<%
 String from="[email protected]";
 String to="[email protected], [email protected]";
 try{
     SmtpClient client = new SmtpClient("mail.perspex.com");
     client.from(from);
     client.to(to);
     PrintStream message = client.startMessage();
     message.println("To: " + to);
     message.println("Subject:  Sending email from JSP!");
     message.println("This was sent from a JSP page!");
     message.println();
     message.println("Cool beans! :-)");
     message.println();
     message.println("Govind Seshadri");
     message.println("jGuru.com");
     message.println();
     client.closeServer();
  }
  catch (IOException e){	
     System.out.println("ERROR SENDING EMAIL:"+e);
  }
%>

Can I invoke a JSP error page from a servlet?
Created:1999-11-29 12:21:25.791
Modified:1999-11-29 18:51:04.078
Primary contributor:Govind Seshadri

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

How can I get to print the stacktrace for an exception occuring within my JSP page?
Created:1999-12-10 15:12:09.925
Modified:1999-12-21 20:27:59.817
Primary contributor:Govind Seshadri

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

What's the difference between the JSDK and the JSWDK? And what's the current version?
Created:1999-12-21 11:17:59.021
Modified:2000-06-03 15:15:11.954
Primary contributor:Alex Chaffee

The kit for developing servlets, containing the Servlet API classes and tools, used to be called the Java Servlet Development Kit (JSDK). Then Sun renamed the Java Development Kit (JDK) to the Java 2 Software Development Kit (J2SDK). Since J2SDK sounds a lot like JSDK, the Servlet team renamed JSDK to JavaServer Web Development Kit (JSWDK). (They also added support for JSPs.)

Here's where it gets confusing. When they renamed it, they also renumbered it. So the JSWDK 1.0 is actually more recent than the JSDK 2.1. It's also confusing that when people want to develop servlets, they have to download something called a JavaServer Web Development Kit, which sounds like it should be used to develop servers, not servlets.

A further confusion is that the Servlet spec is developed independently from the JSP spec, and they both have different version numbers than the JSDK and JSWDK.

In short: Make sure you look for the "W"!

Tomcat contains code based on JSWDK, as well as a lot of new stuff, and it will be the supported Servlet and JSP implementation from now on. No further work will be done on JSDK or JSWDK.

See What version of the Servlets or JSP specification is supported by my favorite servlet product? for a summary of the spec versions supported by each product.

How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts?
Created:1999-12-21 21:27:01.452
Modified:2000-06-13 08:25:34.837
Primary contributor:Govind Seshadri

The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP page is accessed for the very first time. This is because the JSP page undergoes a "translation phase" wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic - it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources.

Subsequent client requests to the JSP page do not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet's service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.)

There have been some recent studies contrasting the performance of servlets with Perl scripts running in a "real-life" environment. The results are favorable to servlets, especially when they are running in a clustered environment. For details, see:

http://www.objexcel.com/workingjava.htm#Web Server Benchmarks

How do I communicate with a JSP page from an applet?
Created:1999-12-23 08:56:33.47
Modified:2000-05-05 14:23:51.987
Primary contributor:John Mitchell

This is basically the same as talking to any web page.

Check out:
http://www.jguru.com/jguru/faq/view.jsp?EID=157
and
http://www.jguru.com/jguru/faq/view.jsp?EID=14163

Name some sites that make extensive use of JSP technology.
Created:1999-12-25 00:54:17.952
Modified:1999-12-27 17:49:11.719
Primary contributor:Danno Ferrin

I've installed the JSWDK and it says I've run out of environment space when I try to start the server. How do I increase the amount of environment space under Windows?
Created:2000-01-03 07:17:01.456
Modified:2000-06-03 14:35:40.648
Primary contributor:John Zukowski

The end of your CONFIG.SYS file should include a line like the following:

SHELL=C:\COMMAND.COM C:\ /E:4096 /P 

This assumes your COMMAND.COM file is in your root level C: directory and you wish your shells to start in that directory, too. The 4096 is the new environment size. You can increase this to a larger number if that is still a problem.

How do you pass an InitParameter to a JSP?
Created:2000-01-15 07:24:26.009
Modified:2000-01-15 11:37:37.149
Primary contributor:Sameer Tyagi

The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
----------------------------------------------------------------------------
<%@ page import="java.util.*" %>
<%! 
	ServletConfig cfg =null;
	public void jspInit(){
	  ServletConfig  cfg=getServletConfig();
        for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
           String name=(String)e.nextElement();
           String value = cfg.getInitParameter(name);
           System.out.println(name+"="+value); 
       }
     }
%>
<html>
<body>
<h1>
See the console for the init params accessible by this JSP page
</h1>
</body>
</html>
----------------------------------------------------------------------------
The second part, where are these parameters defined ? The engine translates the JSP into source and uses a base servlet class that it extends. This base servlet class is engine dependant and so is the configuration.In other words, where these are defined depends on the engine that you are using. In the JSWDK 2 parameters,myparam1 and myparam2 for the JSP above are defined in the Web-inf/servlet.properties file
----------------------------------------------------------------------------

# $Id: servlets.properties,v 1.3.2.2 1999/07/27 00:52:13 mandar Exp $
# Define servlets here
# <servletname>.code=<servletclass>
# <servletname>.initparams=<name=value>,<name=value>
#snoop.code=SnoopServlet
#snoop.initparams=initarg1=foo,initarg2=bar
cookie.code=CookieExample
cookie.initparams=foo
jsp.code=com.sun.jsp.runtime.JspServlet
jsp.initparams=keepgenerated=true,myparam1=val1,myparam2=val2
jts.code=servletToJsp
jts.initparams=foo
----------------------------------------------------------------------------
Couple of points,init parameters defined will be available to all JSPs since they are bound to the same servlet ,unique names should be used across different JSPs. The whole approach should actually be avoided, because if the JSP depends on initiaization then chances are it should actually be coded as a servlet or the code needs to be moved to a bean. JSPs strive to seperate code from presentation, too much code in the JSP usually contradicts this.

How can my JSP page communicate with an EJB Session Bean?
Created:2000-01-17 15:19:51.724
Modified:2000-01-20 10:56:07.612
Primary contributor:Govind Seshadri

The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:

<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%! 
 //declare a "global" reference to an instance of the home interface of the session bean
 AccountHome accHome=null;

 public void jspInit() { 
   //obtain an instance of the home interface
   InitialContext cntxt = new InitialContext( );
   Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
   accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
 }
%>
<%
 //instantiate the session bean
 Account acct = accHome.create();
 //invoke the remote methods
 acct.doWhatever(...);
 // etc etc...
%>

How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
Created:2000-01-22 10:23:19.946
Modified:2000-01-23 12:33:14.901
Primary contributor:Alex Chaffee

You could make a simple wrapper function, like

<%!
String blanknull(String s) {
  return (s == null) ? "" : s;
}
%>

then use it inside your JSP form, like

<input type="text" name="shoesize" value="<%=blanknull(shoesize)%>">

What ISPs provide hosting services which include JSP support?
Created:2000-01-25 09:15:20.332
Modified:2000-05-29 11:45:30.995
Primary contributor:Govind Seshadri

What work is being done towards JSP API v1.2?
Created:2000-01-26 00:52:18.378
Modified:2000-01-26 08:31:25.694
Primary contributor:John Mitchell

Check out:

http://java.sun.com/aboutJava/communityprocess/jsr/jsr_053_jspservlet.html

Is there a standard set of tags for JSP?
Created:2000-01-26 00:54:18.397
Modified:2000-01-26 08:33:48.374
Primary contributor:John Mitchell

Nope, not yet. Check out:

http://java.sun.com/aboutJava/communityprocess/jsr/jsr_052_jsptaglib.html

What are some alternatives to JSP?
Created:2000-01-26 12:34:27.516
Modified:2000-03-28 16:30:10.017
Primary contributor:John Mitchell

Servlet frameworks like

There are also template systems that are part of various servers:

You can also make use of programmatic libraries like ECS.

How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
Created:2000-01-26 16:43:53.14
Modified:2000-01-27 09:08:53.006
Primary contributor:John Zukowski

One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:

Additionally, your servlet superclass also needs to do the following:

If any of the above conditions are not satisfied, the JSP engine may throw a translation error.

Once the superclass has been developed, you can have your JSP extend it as follows:

<%@ page extends="packageName.ServletName" %>

Are there any custom tag libraries available for JSP?
Created:2000-01-28 12:51:28.451
Modified:2000-05-29 11:48:46.55
Primary contributor:Hans Bergsten

Gefion Software has released a preview of their upcoming InstantOnline Basic for JSP product. It contains custom tags for database access, file manipulation, sending emails, and more.

See http://www.gefionsoftware.com/InstantOnline/ for details.

How can I integrate my JSP pages with OLE/COM objects?
Created:2000-01-31 18:23:26.039
Modified:2000-05-29 11:49:40.014
Primary contributor:Govind Seshadri

You can use OLEBridge from IBM Research to integrate with OLE/COM objects. This is a free software development kit that provides a mechanism for Java objects to communicate with OLE/COM objects either locally or over a network using RMI.

You can download OLEBridge from IBM Research.

What is the difference between JSP and PHP?
Created:2000-02-01 06:26:53.666
Modified:2000-02-01 08:36:58.263
Primary contributor:Alex Chaffee

PHP is an open-source page scripting/templating system that is very similar to JSP and ASP. It defines its own scripting language, which looks and feels a lot like Perl. JSP uses Java as its scripting language (although some implementations support JavaScript, such as Caucho). ASP uses VBScript.

PHP is very popular -- it is used on over a million web sites -- but its main advantage (IMHO) seems to be that the language, being more "scripty" and Perl-like, is less intimidating to the great unwashed mass of HTML monkeys and hackers. In the long run, JSP and Java provide a more powerful system.

Here is a list of reasons why JSP is better than PHP:

How do I download a (binary, text, executable) file from a servlet or JSP?
Created:2000-02-01 08:07:04.291
Modified:2000-06-03 14:42:58.132
Primary contributor:Alex Chaffee

Solution 1: Just use HTTP! This has nothing to do with servlets per se. Make sure the file is on your web server. Then you can either embed a link for your user to click, as

Click here to download the Runme app
or have your servlet or JSP send a redirect to the file, as
response.sendRedirect("http://myserver.com/files/runme.exe");
or get fancy with JavaScript (see this FAQ for inspiration).

The point is -- this is still the World Wide Web! HTTP is a file transfer protocol; downloading files what it's for!

Solution 2: Open the file from your servlet using java.io classes, and shove the bytes down the response stream. Make sure to set the content type to match the type of file, e.g. response.setContentType("image/gif") or response.setContentType("application/x-msword"). This technique is a little more expensive, but allows you to do things like security checks, or to access files that are on your web server host, but outside the HTTP directory structure.

For source code to a servlet that "downloads" (actually it's uploading, right?) a text file, see this FAQ answer.

How do I instantiate a bean whose constructor accepts parameters using the useBean tag?
Created:2000-02-02 17:05:50.149
Modified:2000-02-02 17:50:18.984
Primary contributor:Govind Seshadri

Consider the following bean:

package bar;
public class FooBean {
   public FooBean(SomeObj arg) {
     ...
   }
    //getters and setters here
}

The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:

%   SomeObj x = new SomeObj(...);
        bar.FooBean foobar = new FooBean(x);
        session.putValue("foobar",foobar);
%>

You can now access this bean within any other page that is part of the same session as:

%
      bar.FooBean foobar = session.getValue("foobar");
%>

To give the bean "application scope", you will have to place it within the ServletContext as:

% 
        application.setAttribute("foobar",foobar); 
%>

To give the bean "request scope", you will have to place it within the request object as:

% 
        request.setAttribute("foobar",foobar); 
%>

If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).

Once the bean is instantiated, it can be accessed in the usual way:

<jsp:getProperty name="foobar" property="someProperty"/>

<jsp:setProperty name="foobar" property="someProperty" value="someValue"/>

Is it possible to use visual JavaBeans with JSP?
Created:2000-02-03 18:43:15.658
Modified:2000-02-03 18:44:46.344
Primary contributor:Govind Seshadri

Yes, you should be able to use beans and applets at the presentation layer by making use of the <jsp:plugin> tag.

The plugin action causes the automatic generation of HTML containing either the OBJECT or EMBED tags (depending on the browser type), causing the browser to download and install the Java Plugin software, if it is not already installed on the client machine. The specified beans and applets are then executed within the JRE provided by the Java Plugin.

Consider the following example which executes a pie-chart applet within the JRE of the Java Plugin:

<jsp:plugin type="applet" code="PieChart.class" codebase="/html" >
  <jsp:params>
    <jsp:param name="piechartdata" value="sales/data.dat"/>
  </jsp:params>
 <jsp:fallback>
     unable to start plugin 
  </jsp:fallback>
</jsp:plugin>

If you want to use a bean instead, just specify type="bean" within the <jsp:plugin> tag.

The syntax of the <jsp:plugin> tag is shown below:

<jsp:plugin type="bean|applet"
code=" objectCode"
codebase=" objectCodebase"
{ align=" alignment" }
{ archive=" archiveList" }
{ height=" height" }
{ hspace=" hspace" }
{ jreversion=" jreversion" }
{ name=" componentName" }
{ vspace=" vspace" }
{ width=" width" }
{ nspluginurl=" url" }
{ iepluginurl=" url" } >
{ <jsp:params>
{  <jsp:param name=" paramName" value=" paramValue"  }+
  </jsp:params> }
{ <jsp:fallback> arbitrary_text </jsp:fallback> }
</jsp:plugin>

type Identifies the type of the component; a Bean, or an Applet. code As defined by HTML spec codebase As defined by HTML spec align As defined by HTML spec archive As defined by HTML spec height As defined by HTML spec hspace As defined by HTML spec jreversion Identifies the spec version number of the JRE the component requires in order to operate; the default is: "1.1" name As defined by HTML spec vspace As defined by HTML spec title As defined by the HTML spec width As defined by HTML spec nspluginurl URL where JRE plugin can be downloaded for Netscape Navigator, default is implementation defined iepluginurl URL where JRE plugin can be downloaded for IE, default is implementation defined.

Where can I find a jsp editor?
Created:2000-02-06 20:15:16.071
Modified:2000-05-29 11:56:39.765
Primary contributor:anil chakravarthy

There are three that I know of:

PS: None of the products are free.

How can my application get to know when a HttpSession is removed (when it time-outs)?
Created:2000-02-07 11:02:17.958
Modified:2000-06-03 14:45:15.689
Primary contributor:Kent Johnson

Define a class, say SessionTimeoutNotifier, that implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want.

[Source code example anyone? -Alex]

Are there any IDE's which will help me debug JSPs?
Created:2000-02-07 13:00:43.271
Modified:2000-05-29 11:57:18.685
Primary contributor:Govind Seshadri

IBM's Visual Age for Java (VAJ) IDE provides numerous features to aid in the debugging and incremental development of JSPs. VAJ Professional and Enterprise Editions come with the JSP Execution Monitor, which allows you to simultaneously view the JSP source, the generated servlet source as well as the dynamically generated HTML content.

A really cool feature is that you can enable VAJ to work with the freely available JSP 1.1 reference implementation Tomcat, available from the Apache Group. In fact, you can also use the freely available VAJ Entry Level Edition (which is limited to using 750 classes - more than sufficient for getting started) to debug JSPs which run under Tomcat. Read the excellent article published in the Visual Age Developers Domain titled "Apache Tomcat Servlet and JavaServer Pages Development with VisualAge for Java" by Sheldon Wosnick for the inside scoop.

Oracle recently announced JDeveloper 3.0, which features wizards to aid in JSP development and debugging.

How can I get information regarding the client browser using JSP?
Created:2000-02-07 20:33:37.399
Modified:2000-02-07 20:48:07.067
Primary contributor:Marco Hunsicker

Look at the following code. Should be fairly easy to modify in order to suit your needs.

You will be able to get the

according to the client settings.

Create a new JSP like this:

<%@ page language="java" import="de.hunsicker.http.util.*"%>
<%
Browser eins = new Browser(request, session);
out.println(eins.getVersion());
%>

Put the following class in your classpath (You will have to create the directory structure de.hunsicker.http.util or adjust the package name!):


package de.hunsicker.http.util;

import java.util.*;

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

public class Browser extends HttpServlet
  {
  protected HttpServletRequest request;
  protected HttpSession session;

  protected String userAgent;
  protected String company;          // Firmenname des Herstellers
  protected String name;             // Bezeichnung des Browsers
  protected String version;          // Version
  protected String mainVersion;      // Hauptversion
  protected String minorVersion;     // Unterversion
  protected String os;               // Betriebssystem
  protected String language = "de";  // Sprachcode Standard
  protected Locale locale;           // Locale-Objekt mit den aktuellen
                                     // Spracheinstellungen

  private Hashtable supportedLanguages; // Untersttzte Sprachen

  public Browser(HttpServletRequest request, HttpSession session)
    {
    this.initialize();
    this.request = request;
    this.session = session;

    this.setUserAgent(this.request.getHeader("User-Agent"));
    this.setCompany();
    this.setName();
    this.setVersion();
    this.setMainVersion();
    this.setMinorVersion();
    this.setOs();
    this.setLanguage();
    this.setLocale();
    }

  public void initialize()
    {
this.supportedLanguages = new Hashtable(2);

  this.supportedLanguages.put("en", "");
  this.supportedLanguages.put("de", "");
  }

  public void setUserAgent(String httpUserAgent)
    {
    this.userAgent = httpUserAgent.toLowerCase();
    }

  private void setCompany()
    {
    if (this.userAgent.indexOf("msie") > -1)
      {
      this.company = "Microsoft";
      }
    else if (this.userAgent.indexOf("opera") > -1)
      {
      this.company = "Opera Software";
      }
    else if (this.userAgent.indexOf("mozilla") > -1)
      {
      this.company = "Netscape Communications";
      }
    else
      {
      this.company = "unknown";
      }
    }

  /**
   * Liefert den Firmennamen des Herstellers des verwendeten Browsers.
   */
  public String getCompany()
    {
    return this.company;
    }

  private void setName()
    {
    if (this.company == "Microsoft")
      {
      this.name = "Microsoft Internet Explorer";
      }
    else if (this.company == "Netscape Communications")
      {
      this.name = "Netscape Navigator";
      }
    else if (this.company == "Operasoftware")
      {
      this.name = "Operasoftware Opera";
      }
    else
      {
      this.name = "unknown";
      }
    }

  /**
   * Liefert den Namen des verwendeten Browsers.
   */
  public String getName()
    {
    return this.name;
    }

  private void setVersion()
  {
    int tmpPos;
    String tmpString;

    if (this.company == "Microsoft")
    {
      String str = this.userAgent.substring(this.userAgent.indexOf("msie") + 5);
      this.version = str.substring(0, str.indexOf(";"));
    }
    else
    {
     tmpString = (this.userAgent.substring(tmpPos = (this.userAgent.indexOf("/")) + 1, tmpPos + this.userAgent.indexOf(" "))).trim();
     this.version = tmpString.substring(0, tmpString.indexOf(" "));
    }
  }

  /**
   * Liefert die Versionsnummer des verwendeten Browsers.
   */
  public String getVersion()
    {
    return this.version;
    }

  private void setMainVersion()
    {
    this.mainVersion = this.version.substring(0, this.version.indexOf("."));
    }

  /**
   * Liefert die Hauptversionsnummer des verwendeten Browsers.
   */
  public String getMainVersion()
    {
    return this.mainVersion;
    }

  private void setMinorVersion()
    {
    this.minorVersion = this.version.substring(this.version.indexOf(".") + 1).trim();
    }

  /**
   * Liefert die Unterversionsnummer des verwendeten Browsers.
   */
  public String getMinorVersion()
    {
    return this.minorVersion;
    }

  private void  setOs()
    {
    if (this.userAgent.indexOf("win") > -1)
      {
      if (this.userAgent.indexOf("windows 95") > -1 || this.userAgent.indexOf("win95") > -1)
        {
        this.os = "Windows 95";
        }
      if (this.userAgent.indexOf("windows 98") > -1 || this.userAgent.indexOf("win98") > -1)
        {
        this.os = "Windows 98";
        }
      if (this.userAgent.indexOf("windows nt") > -1 || this.userAgent.indexOf("winnt") > -1)
        {
        this.os = "Windows NT";
        }
      if (this.userAgent.indexOf("win16") > -1 || this.userAgent.indexOf("windows 3.") > -1)
        {
        this.os = "Windows 3.x";
        }
      }
    }

  /**
   * Liefert den Namen des Betriebssystems.
   */
  public String getOs()
    {
    return this.os;
    }

  private void setLanguage()
    {
    String prefLanguage = this.request.getHeader("Accept-Language");

    if (prefLanguage != null)
      {
      String language = null;
      StringTokenizer st = new StringTokenizer(prefLanguage, ",");

      int elements = st.countTokens();

      for (int idx = 0; idx  elements; idx++)
        {
  if (this.supportedLanguages.containsKey((language = st.nextToken())))
    {
    this.language = this.parseLocale(language);
  }
  }
  }
    }

  /*
   * Hilfsfunktion fr setLanguage().
   */
  private String parseLocale(String language)
    {
    StringTokenizer st = new StringTokenizer(language, "-");

    if (st.countTokens() == 2)
      {
      return st.nextToken();
  }
else
  {
  return language;
  }
    }

  /**
   * Liefert das Länderkürzel der vom Benutzer
   * bevorzugten Sprache.
   */
  public String getLanguage()
    {
    return this.language;
    }

  private void setLocale()
    {
    this.locale = new Locale(this.language, "");
    }

  /**
   * Liefert ein Locale-Objekt mit der Sprach-Prferenz des verwendeten Browsers
   */
  public Locale getLocale()
    {
    return this.locale;
    }
  }

Why should I use JSP when there is already servlet technology available for serving dynamic content?
Created:2000-02-09 14:16:32.641
Modified:2000-06-03 14:45:58.232
Primary contributor:Govind Seshadri

While JSP may be great for serving up dynamic Web content and separating content from presentation, some may still wonder why servlets should be cast aside for JSP. The utility of servlets is not in question. They are excellent for server-side processing, and, with their significant installed base, are here to stay. In fact, architecturally speaking, you can view JSP as a high-level abstraction of servlets that is implemented as an extension of the Servlet 2.1 API. Still, you shouldn't use servlets indiscriminately; they may not be appropriate for everyone. For instance, while page designers can easily write a JSP page using conventional HTML or XML tools, servlets are more suited for back-end developers because they are often written using an IDE -- a process that generally requires a higher level of programming expertise.

When deploying servlets, even developers have to be careful and ensure that there is no tight coupling between presentation and content. You can usually do this by adding a third-party HTML wrapper package like htmlKona to the mix. But even this approach, though providing some flexibility with simple screen changes, still does not shield you from a change in the presentation format itself. For example, if your presentation changed from HTML to DHTML, you would still need to ensure that wrapper packages were compliant with the new format. In a worst-case scenario, if a wrapper package is not available, you may end up hardcoding the presentation within the dynamic content. So, what is the solution? One approach would be to use both JSP and servlet technologies for building application systems.

This answer is excerpted from my Javaworld article Understanding JavaServer Pages Model 2 Architecture

Can I call a JSP, then have it return control to the original JSP, like a subroutine or method call?
Created:2000-02-10 12:57:05.988
Modified:2000-06-03 14:46:37.613
Primary contributor:Govind Seshadri

Yes. That is exactly the purpose served by the <jsp:include> action. The syntax of the include action is:

<jsp:include page="relativeURL" flush="true" />

You can have the include action anywhere within your JSP page, and the relative URL specified for the page attribute may point to either a static (.html) or dynamic resource like a servlet or JSP. Since the include action is handled during the request processing phase, it makes since to include only resources which generate some dynamic content. The included resource is also automatically forwarded the request and response objects of the invoking JSP page. For example, the action:

<jsp:include page="/examples/jsp/copyright.jsp"flush="true"/>

results in the output of copyright.jsp being included inline within the response of invoking JSP page.

There is however a limitation. The included JSP or servlet resource cannot change the HTTP headers. For example, they cannot set cookies, since they are sent to the browser via the HTTP headers.

Where can I find more information on "Model1" and "Model2" JSP architectures?
Created:2000-02-10 13:53:15.54
Modified:2000-05-29 12:05:09.39
Primary contributor:Govind Seshadri

The December '99 issue of Javaworld contains an article by Govind Seshadri on "Understanding JavaServer Pages Model 2 architecture"

You can also find a detailed article by Lance Lavandowska comparing Model 1 and Model 2 architectures at his Brainopolis site.

When I recompile a class (such as a JavaBean) used by my JSP or Servlet, the JVM continues to use the old class that has already been loaded. (Sometimes it gives a ClassCastException.) How can I avoid this?
Created:2000-02-11 15:40:49.225
Modified:2000-02-18 17:15:34.151
Primary contributor:Kumar Allamraju

Here's what is happening...

When your JSP needs to be recompiled, the Server has to create and use a new class-loader to ensure that the older classes are dropped, and the newer classes are used instead. This is a workaround for a 'characteristic' of the Java class loader. If you define a custom class and that class is loaded from the servlet classpath, it is also loaded by the same class loader that loaded your generated JSP servlet. Of course, that class loader is destroyed when the JSP is reloaded, and the custom class must also be reloaded.

Now, when you attempt to retrieve the custom class from the HTTP session, you get a ClassCastException since it was loaded by a different class loader. Although the classes may be the same logically, they have been loaded by different class-loaders, and are regarded by the JVM as incompatible.

Workaround:

1. Do not place your class myClass in the servlet classpath. Instead, place it in the system classpath that are accessible by the Server; it won't be reloaded when the servlet is modified. This solution has the drawback that you can't prototype the myClass class, since you must restart the server in order to reload the class after it is modified.

2. Another workaround is to catch the ClassCastException, and replace the old class that is stored in the session with a newly instantiated class, or remove it from the session. Unfortunately, you will lose the session data that was previously stored in the class, so you should write your application to handle this scenario. This is the easiest solution to the problem -- remember that you should not be storing critical information in an HTTP session, but rather storing it in a database.

The above exception will generally occur whilst you are developing your servlets, and should not be an issue in a stable production system.

What is the difference between <%@ include file="abc.jsp" %> and <jsp:include page="abc.jsp" %> ?
Created:2000-02-11 22:03:22.27
Modified:2000-02-13 10:53:51.308
Primary contributor:Alex Chaffee

The <%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text).

The <jsp:include page="abc.jsp"> tag compiles the file as a separate JSP file, and embeds a call to it in the compiled JSP.

Some JSP engines support the non-standard tags <!--#include file="data.inc"--> (NCSA-, or .shtml-style) and <%@ vinclude="data.inc" %> (JRun-style), but these are not defined in the JSP spec and thus cannot be relied on.

See also this question in the JSP FAQ.

When I use the and then recompile "myclass", the JSP document doesn't seem to understand that there is now a new class. Instead, it continues to use the old object that has already been loaded within the servletcontext. How can I avoid this?
Created:2000-02-13 21:16:14.985
Modified:2000-02-14 11:26:27.528
Primary contributor:Mobushir Hingorjo

If you are creating the beans with session or application scope, JSWDK and its successor Tomcat, do not recognize if the bean class has changed in the background. This is true even if the JSP page gets recompiled and reloaded into memory. Ideally, with these servers, you would have to stop and start the engine for it to understand that you have a new class.

With J2SDKEE1.2, you must redeploy the web component that contains your bean. Unfortunately, this has to be done by using the deploytool, which is somewhat tedious. However, I suppose there must be an easier manual way of doing this as well.

It is a basic concept that JSPs compile into servlets. What happens to JSP scriptlets? How are they compiled and excuted?
Created:2000-02-14 10:46:28.207
Modified:2000-02-14 11:30:00.448
Primary contributor:Kumar Allamraju

Scriptlets are included within the body of your JSP servlet's service() method. JSP Scriptlets are thus executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is buffered in the out (JSPWriter's) object, which is then ultimately sent to the client.

I want to use url rewriting as the default mechanism for maintaining the session ID rather than make use of a cookie. How do I enable this when creating a new session with JSP or servlets?
Created:2000-02-16 21:55:15.652
Modified:2000-02-17 09:57:59.32
Primary contributor:Mobushir Hingorjo

This cannot be done automatically. There are no properties (in the web servers that I have used) or APIs that would make a servlet or JSP use url rewriting instead of cookies. URL rewriting needs to be done manually. That is, you need to create a session and then send that session id through URL rewriting in the servlet response. Subsequently, you need to retrieve the session id from the form field in the request and retrieve the session object using that id.

How can I include stock quotes in my JSP pages?
Created:2000-02-17 10:59:11.354
Modified:2000-02-17 11:28:55.17
Primary contributor:John Zukowski

Yahoo offers a resource that sends a response of one symbol per line (no HTML), with whatever options you want like price, volume, etc. You can then parse the response to display these settings. This is demonstrated in an article over at CNET (http://www.builder.com/Programming/JSP/ss05.html. The basic URL to ask for a price is of the form: http://quote.yahoo.com/download/javasoft.beans?SYMBOLS=" + symbol + "&format=nl", where symbol would be a comma delimeted list of symbols. You can try out the different letters of the alphabet to see the different stock information you can can back (n is name and l is last price).

How does JSP compare to ASP in terms of connecting to databases such as MS SQL Server from the web?
Created:2000-02-17 21:11:25.016
Modified:2000-05-30 09:20:11.692
Primary contributor:anil chakravarthy

ASP and MS SQL Server together is a great combination.I have used them in a production environment with little or no problems (except for one or two occassions when IIS just stopped and I never knew why...).

Connecting to SQl Server through ASP is pretty straight forward. ASP manages its connections to the database through a connection pool that IIS maintains.I wouldn't have to worry a thing about how to manage the pool, return the connection back to the pool, ans so on. Syntax wise, this is how a connection is made and a resultset is obtained:

<%
set conn = server.createobject("ADODB.connection")
dsnstr = "DSN=prdn;uid=prdn;pwd=prdn;"
conn.open dsnstr
sql = "select * from users_records"
set rs = dataconn.execute(sql)
do while not rs.eof
 response.write(rs("user_name") & "<br>") 
 rs.movenext
loop
%>

DSN or the data source name is configured using the ODBC mannager, which is available under settings in the control panel. This DSN can be configured to point to a machine on the LAN that hosts the IIS server.

On the other hand, JSP can also be used using the same DSN, but should be stricly avoided due to the fact that the JDBC-ODBC bridge leaks memory and shouldnt be used in a production environment. A disadvantage of using JSP is that you have to manage the connection pool all by yourself, typically by writing additional Java classes for the purpose. However, the good news is that all major application server vendors are coming out with connection pool packages that implement this for you.

I have used i-Net Software'sJDBC drivers for MS SQL Server. These drivers give you a choice of either connecting to the database through named pipes or socket based connections. SQL server by default listens on port number 1433. These are the kind of drivers that are supposed to be used in a production environment, and they are 100% Java and are robust. The syntax for connecting to a database using JSP would be something like:

<%@ page import='java.sql.*' %>
<%
 Class.forName("com.inet.tds.TdsDriver");
 Connection conn = DriverManager.getConnection
   ("jdbc:inetdae:199.199.199.199:1433?database=details","prdn","prdn");
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery("select * from abc");
 while(rs.next())
{ 
  out.println(rs.getString("def") + "<br>");
}
%>

If you chose to use named pipes the Connection statement would look like:

Connection conn = DriverManeger.getConnection
  ("jdbc:inetdae://199.199.199.199/pipe/sql/query","prdn","prdn");

To test your JSP pages you can also use the DSN. Two lines have to be modified in the above JSP code. First the jdbc-odbc bridge driver has to be loaded into memeory and the connection object should be created using the correct parameters:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:prdn","prdn","prdn");

Not to anger anybody or wage a war, but we've found that our jsp pages used with these jdbc drivers with pooled connections are way faster than ASP pages. :)

Should I use the SingleThreadModel interface or provide explicit synchronization to make my JSP pages and servlets thread safe?
Created:2000-02-18 13:58:25.497
Modified:2000-06-03 14:50:47.168
Primary contributor:Govind Seshadri

You can have a any servlet implement the SingleThreadModel interface. JSP pages implement this in the background when you specify

<%@ page isThreadSafe="false" %> 

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 synchronization for your variables. 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.

What are the disadvantages of JSP?
Created:2000-02-18 21:35:53.414
Modified:2000-05-29 12:13:34.873
Primary contributor:anil chakravarthy

1. As things stand, I believe that JSP can be effectively used only by someone with some degree of Java knowledge. Currently, Java programmers are a fairly expensive commodity.

2. Debugging JSP programs is still a major challenge.You have to remember that a jsp page will be first converted to a .java file and then compiled. Thus, any errors will be pointing to line numbers in the converted .java file and not the .jsp page.For example an error in the first line of .jsp page may be shown on the 20th line of the .java file. Tracing back can be somewhat tricky. (However, with the servlet engine Resin, the errors refer to the line within the .jsp page.) You can debug JSP pages using IDEs like VA Java and JDeveloper; but I think debugging JSP using an high-powered IDE would go against one of the basic tenets of JSP - simplicity.

3. Database connectivity is not as easy as it should be. Most of the servlet engine vendors do not support connection pooling natively, as of this day. Consequently, one has to write a lot of custom code to do the job.

4. It is not an easy task to choose the appropriate servlet engine. There isn't a single organization which conducts independent benchmark testing on servlet engines. Individual vendors do provide benchmarks for their own products, but the figures usually refer to numbers and does not provide any indication on the stability of the engine.

5. There are numerous syntax related issues with JSP programming. Jason Hunter, author of 'Java servlet programming' has written an interesting article comparing JSP with other scripting alternatives. You can read the article at http://www.servlets.com/soapbox/problems-jsp.html.

Can a JSP call itself recursively?
Created:2000-02-21 20:11:18.075
Modified:2000-02-21 20:38:29.393
Primary contributor:Mobushir Hingorjo

Yes, a JSP can call itself recursively. For example, I use a web based interactive SQL query tool. This consists of a single JSP in which I do a SQL call at the top, display results and then get the next SQL query in a form. In the form's action, I specify the same JSP. There could be many other similar uses.

What are some of the strategies for internationalising JSP pages, without duplicating the JSP page for each language?
Created:2000-02-22 09:12:16.616
Modified:2000-02-23 21:19:39.226
Primary contributor:Govind Seshadri

Internationalizing a JSP-based web application is a task best initiated at the design stage itself. The internationalization process involves identifying all locale-specific textual data (aka resources) that constitute the user interface of the application, such as page headers and trailers, user messages, form button labels, dates, currencies and so forth, and isolating them from the application within external property files known as resource bundles. Typically, you need to provide a version of the resource bundle for each locale your application serves, with the locale defined as a geographical region or political entity that shares a common language, culture and customs. The process of creating these locale-specific bundles themselves, along with the associated translation of text, is called localization.

The property files for bundles must follow some standard naming conventions. The suffix must always be “.properties”. Also, since a locale is typically defined in Java via a country code and/or a language code, the name of the bundle has to correlate with the locale it serves.

For example, the property file serving as the bundle for Germany may be named Message_de_DE.properties. Similarly, the bundle for France can be named Message_fr_FR.properties, and so on. Later, when your application needs to service a specific locale, it can do so using predefined constants like Locale.GERMANY, Locale.FRANCE, and so forth. Then, using the class java.util.PropertyResourceBundle, it should be able to load the corrosponding resource bundle serving the locale and access the values for the resources by name, just like you would with a Hashtable object.

How can I use JSP to make sure a user has logged in before I handle the request?
Created:2000-02-22 10:49:00.422
Modified:2000-03-09 19:34:16.055
Primary contributor:Kumar Allamraju

On every page that needs to be authenticated, check for a user ID in the session object - if it does not exit, redirect the user to a login page, passing the url the user was trying to access as a parameter.

On the login page, if the user successfully logs in, create a session for him/her, and add their user ID to the session. After this, redirect back to the original page they had tried to access. This way, even if the user bookmarks a page, he/she will be asked to login once the session has become invalid.

Some code: On every page add the following:

HttpSession session = request.getSession(true);
if (session.getValue("EID") == null) {
     response.sendRedirect (response.encodeRedirectUrl
     ("Login.jsp?Origin=janesonline.jsp"));
}
else {
     // the rest of the page ...
}

In Login.jsp once the user has provided the correct logon credentials:

session.putValue("EID", EID);
response.sendRedirect(response.encodeRedirectUrl(request.getParameter("Origin")));
...

How can I write to a text file from a JSP page?
Created:2000-02-27 21:13:13.581
Modified:2000-03-10 09:54:17.762
Primary contributor:anil chakravarthy

You can write to a text file using the PrintWriter object:

<%@ page import="java.io.*"  %>
<%
String str = "print me";
//always give the path from root. This way it almost always works.
String nameOfTextFile = "/usr/anil/imp.txt";
try {   
    PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
    pw.println(str);
    //clean up
    pw.close();
} catch(IOException e) {
   out.println(e.getMessage());
}
%>

Now, open up imp.txt and voila, the text "print me" should be there in it.

How can you define methods in a JSP file?
Created:2000-03-09 22:11:36.282
Modified:2000-03-10 05:59:58.605
Primary contributor:John Zukowski

You declare methods by using the JSP Declaration syntax, as specified at http://java.sun.com/products/jsp/tags/11/syntaxref11.fm3.html:
<%! declaration; [ declaration; ]+ ... %>
The declaration could be variables or methods, or both.

How can I include a non-relative page (an .html page which is situated on another server) within my JSP pages?
Created:2000-03-10 06:07:16.033
Modified:2000-03-10 06:10:32.241
Primary contributor:John Zukowski

Personally, I would NOT include the actual Java code within the JSP page, but instead use a JavaBean (or Servlet) for this. See http://www.jguru.com/jguru/faq/view.jsp?EID=13198 for the actual code to do this. I would use a Reader stream though, instead of an InputStream, as you will be working with text data, versus binary data.

How do you share session objects between servlets and JSP?
Created:2000-03-10 11:12:44.445
Modified:2000-06-03 14:54:39.221
Primary contributor:anil chakravarthy

Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a little easy by creating a session object and making it availabe already. In a servlet you would have to do it yourself. This is how:
HttpSession session = request.getSession(true); //create a session if one is not created already now 
session.putValue("variable","value");//assign the session variable to a value.
in the jsp page this is how you get the session value:
<%
session.getValue("varible");
%>

How can I customize the HTML generated by my JSP file based upon what browser the user is using?
Created:2000-03-10 12:13:01.326
Modified:2000-03-10 12:22:30.52
Primary contributor:Brett Hyde

<%@ page import="javax.servlet.*" %>

<%
  String browserType = request.getHeader("User-Agent");
  String browser = "";
  if ((browserType.indexOf("MSIE") != -1) ||  
      (browserType.indexOf("msie") != -1))
  {
    browser = "Explorer";
  }
  else
  {
    browser = "Navigator";
  }
%>

Your browser is <%= browser%><BR>

How can you copy a JavaScript variable to a JSP session variable without using cookies?
I am trying to store the value of a SELECT object in a session variable so it can be accessed in other JSP's for use in database lookups.

Created:2000-03-10 15:09:02.559
Modified:2000-05-29 12:25:32.206
Primary contributor:Peter Wang

There are three things you have to do in order to make it to work.

1. You need a servlet to store the selected value of SELECT in session in the first place. If the SELECT list is static , just store the selectedIndex in the session.

2. On the same JSP where SELECT resides, you need put a server side code close to this

%  
final HttpSession   curSession   = request.getSession( false );
  final String    selectedIndex  = (String)curSession.getValue(selectedIndexKeyName);
%>
to pull the selectedIndex out of the session you put in the first place.

3. write onLoad method for JSP where SELECT resides

where intiPage() is a JavaScript function that will set SELECT list 
  selectedIndex to previous value. 
document.frmCity.selCity.selectedIndex = %= selectedIndex %>

How can I include content from a URL, not from a local file?
Created:2000-03-12 13:43:27.407
Modified:2000-06-03 14:55:43.746
Primary contributor:John Zukowski

You would need to read in the content from the URL and place it in the file yourself. See http://www.jguru.com/jguru/faq/view.jsp?EID=13198 for an example of this, but use a Reader stream instead of an InputStream as you'll be working with character data.

How do I setup a cookie to expire after a certain time?
Created:2000-03-12 14:18:13.445
Modified:2000-06-03 14:56:22.605
Primary contributor:John Zukowski

You can set the maximum age of a cookie with the setMaxAge(int seconds) method:

Where can I find a DTD for JSP?
Created:2000-03-13 16:21:55.941
Modified:2000-04-24 19:49:55.495
Primary contributor:Maxim Senin

According to Sun, it's impossible to write a DTD for JSP because it's not XML-complient. It cannot even be called 100% derived from SGML. But, you may use a non-validating XML parser to parse JSP - just set DTD to null, or use non-validating parser that doesn't use DTD at all.

How can I find out the number of live sessions within my servlet engine using either JSP or servlets?
Created:2000-03-14 07:25:44.638
Modified:2000-03-15 18:57:25.4
Primary contributor:Volker Stolz

There is no easy way to this as all the required functions have been deprecated in JSP 1.1 for security reasons. [FAQ Manager NOTE - For earlier JSP users, scroll to end for a working answer for there.]

However, you can use HttpSessionBindingListeners to track live sessions, e.g.:

class SqlNotifier implements HttpSessionBindingListener {
  
  protected Connection con;
  
  public SqlNotifier(Connection con){
    this.con = con;
  }
  
  public void valueBound(HttpSessionBindingEvent e) {
    HttpSession session = e.getSession();
    // log creation to a database
    ....
    }
  }
  
  public void valueUnbound(HttpSessionBindingEvent e) {
    HttpSession session = e.getSession();
    // log destruction...
    ...
  }
}
and:
session.putValue("logon.sqlnotifier",new SqlNotifier(sql));
upon creation of a new session.

[FAQ Manager addition - The following was submitted by both Peter Wang and Roger Valade for earlier JSP versions. It does not run in the 3.1 version of Tomcat.]

<%@ page import="java.util.*" %>
<html>
<head>
  <meta http-equiv="Refresh" content=90>
  <title>Active Sessions</title>
</head>

<%!
    final String getActiveSessionData( final HttpServletRequest request )
    {
      final StringBuffer data = new StringBuffer();
      int counter = 0;
      final HttpSession        curSession   = request.getSession( true );
      final String             curSessionId = curSession.getId();
      final HttpSessionContext context      = curSession.getSessionContext();
      for ( final Enumeration sessionIds = context.getIds(); sessionIds.hasMoreElements(); )
      {
        final String sessionId = (String) sessionIds.nextElement().toString();
//        if ( curSessionId == sessionId )
//        {
//          continue;
//        }
        String userId     = sessionId;
        long   creation   = 0;
        long   lastAccess = 0;
       
          final HttpSession session = context.getSession( sessionId );
          userId     = (String)session.getValue("UserID");
          creation   = session.getCreationTime();
          lastAccess = session.getLastAccessedTime();
    Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("EST"));
          currentTime.setTime( new Date(creation));
    Date estCreatTime =currentTime.getTime();
    currentTime.setTime( new Date(lastAccess));
    Date estLastAccess   = currentTime.getTime();
        data.append( "\n\t<tr><td>" )
            .append( ++counter )
            .append( "</td><td>" )
            .append( userId )
            .append( "</td><td>" )
            .append( creation==0 ? "Not Available" : estCreatTime.toString() )
            .append( "</td><td>" )
            .append( lastAccess==0 ? "Not Available" :estLastAccess.toString())
   .append( "</td></tr>" );
      }
data.append("Hi");
      return data.toString();
    }
%>

<body>
  <div class="PageTitle">Active Sessions:</div>
  <hr color="#000000" noshade>
  <table class="DataTable" width="100%" cellspacing=0
cellpadding=0 border=1>
    <tr>
      <th>#</th>
      <th>User</th>
      <th>Creation Time</th>
      <th>Last Access</th>
    </tr>
    <% out.println( getActiveSessionData( request )
);%>
  </table>
  <form><input type="submit" value="Refresh"
onClick="location.reload();"></form>
</body>

How can I set things up such that some of my code is run upon starting of all of my JSPs? If possible, can I share what is started with the generated servlets?
Created:2000-03-14 14:25:26.299
Modified:2000-03-14 15:26:13.518
Primary contributor:Maxim Senin

You can create an alias for your JSPs so that a servlet will be called which later will forward/include your JSPs into its body after doing the pre-processing you need. For example, define an alias
/jsp/ = com.mycompany.myPreprocessingServlet
everything after /jsp/ prefix will be considered file name, so for
/jsp/myJspPage.jsp
servlet will get requestURI=myServletPage.jsp. Its servlet's job to forward request to right path and compute real path with servletContext.getRealPath().

How can I access the same JavaBean instance from different JSP files?
Created:2000-03-16 07:02:44.188
Modified:2000-03-16 11:24:07.633
Primary contributor:John Zukowski

Assuming the JSP files are on the same server and using the same ServletContext, just use application scope for the bean component.
<jsp:useBean id="localName" class="Counter" scope="application" />

I'm running JRun 2.3.3 on NT4 with IIS4, and I'd like my .shtml files to be handled by IIS, but JRun is handling them exclusively. Is it possible to turn off SSI in JRun? If not turn off, at least disable SSI for a particular file extension?
Created:2000-03-18 02:50:50.906
Modified:2000-03-19 22:45:05.467
Primary contributor:anil chakravarthy

A .shtml is picked up by jrunssi servlet thats loaded by default when IIS is run with JRun. Go to aliases in the admin control utility and turn off pre-load option and restart IIS. If this does not work, go to Mappings tab and change the extension for jrunssi to .fhtml or something and restart IIS.

For brand new JSP page, if several clients make request to the same page at the same time: is it possible that due to concurrent nature of request handling several requests handlers will compile same JSP more then once? How does the server resolve concurrent compiles (you ideas)? Does JSP specification say anything about it?
Created:2000-03-19 22:59:25.381
Modified:2000-03-19 23:03:59.381
Primary contributor:Govind Seshadri

No, the JSP spec does not say anything about this particular scenario. I believe the translation phase is synchronized by the JSP engine. Consequently, only one request thread gets to compile the JSP; all other pending requests are put into a wait queue until the resulting servlet is loaded by the JSP engine's class loader and its init method is executed. Then, all the waiting requests are allowed to execute the servlet's service method concurrently.

What are the advantages of using beanName in the jsp:useBean syntax?
Created:2000-03-21 03:52:54.593
Modified:2000-03-21 20:42:11.52
Primary contributor:Mobushir Hingorjo

The beanName tag uses Beans.instantiate() method to instantiate a bean. This method can instantiate a bean from either a class or a serialized template. The value of beanName can be either a fully qualified class name or an expression that evaluates to a fully qualified class name. This value is passed to Beans.instantiate() method which checks whether this is a class or a serialized template. In case of a serialized template, a class loader is called. The instantiated bean is then cast to the type specified by type attribute.

What happended to the LOOP Tag from JSP 0.92? How can I display the values for a bean with indexed properties?
Created:2000-03-21 04:18:18.214
Modified:2000-03-24 21:15:22.311
Primary contributor:Mobushir Hingorjo

The LOOP tag has been deprecated from JSP 1.0 and JSP 1.1, without any replacement. However, JSP 1.1 allows you to create your own custom tags and place them in a tag library. It should be fairly simple to create a custom tag which can be used to iterate over the indexed properties of a bean.

What exactly happens behind the scenes when a JSP page is compiled? Is it converted to a servlet? If it is, then does each request to a JSP page result in the creation of a new servlet?
Created:2000-03-22 06:03:52.842
Modified:2000-03-23 10:48:45.446
Primary contributor:Ashish Bhatia

The first time a request is made for a JSP file, either directly from a client browser or from a servlet, the JSP file is translated into a servlet by the "JSP engine" (which is itself a servlet -in the JSWDK, it is known as JspServlet). If there are any syntax errors within the JSP file, the translation phase fails, triggering an error message to the client.

If it was successful, the generated servlet code is compiled, the servlet is loaded into memory by the JSP engine. At this point, the JSP engine also invokes the jspInit() method, and initializes the servlet. The jspInit() method is invoked just once during the lifetime of the servlet. Then the jspService() method is invoked to process the request and reply to the client. For all subsequent requests to the JSP page, the server checks to see whether the .jsp file has changed since it was last accessed. If there is no change, the request is handled by the jspService() method of the servlet stored in memory in a concurrent manner. Note that since the servlet is always stored in memory, the response is very fast.

If the .jsp file has changed, the server automatically recompiles the page file, replaces the servlet in memory, and handles the request as described above.

Although JSPs are efficient, there is a slight delay on the first request for a .jsp page since the JSP file has to be compiled into a servlet. Also, the JSP engine may remove the servlet from memory in a non-deterministic way at any time owing to resource constraints. When this happpens, it first invokes the jspDestroy() method, before flagging the servlet instance for garbage collection.

When we use <jsp:forward>, the URL in the browser's location/address area doesn't change to the page that is forwarded to. Is there any way to update this upon forwarding to a new location?
Created:2000-03-23 16:14:38.885
Modified:2000-03-23 16:18:58.635
Primary contributor:Govind Seshadri

The only way you can cause the browser to update the new URL in its location area is to use
response.sendRedirect("newURL")
.

Does the mere act of accessing a JSP page with your browser create a session? If so, can this session then be accessed within the service method of a servlet that may be invoked later on?
Created:2000-03-29 13:31:40.072
Modified:2000-03-29 14:50:05.437
Primary contributor:John Quinn

In the page directive, one of the attributes is "session". It's default value is "true", meaning that a session will be created upon accessing the JSP page (if you do not want a JSP page to automatically participate in a session, you have to explicitly indicate the same, as <%@ page session="false" %> ).

To answer the second question, yes, you can access the session object later in servlets or other JSPs, provided of course, that the session is still active and has not been invalidated via a timeout or by calling session.invalidate().

What is the use of param tag in setProperty, include , forward commands?
Created:2000-03-30 11:32:51.84
Modified:2000-03-30 20:52:38.48
Primary contributor:Maxim Senin

In include and forward, params will be appended to query string, i.e.
newQueryString = requestURI+"?paramName1=paramValue1&paramName2=parmValue2"

In setProperty every param name corresponds to property name and every parameter value corresponds to property value, so that

<param name="user" value="Administrator" >
will set property user to value "Administrator"

For JSP 1.0, is there any way to use both standard Java scriptlets and JavaScript in the same JSP? (Motivation: Reuse of tool-generated JavaScript)
Created:2000-04-03 21:08:00.414
Modified:2000-05-29 12:23:32.742
Primary contributor:Scott Stirling

You can only use one server-side scripting language per JSP. You can use client-side JavaScript in a JSP as template text, with Java as the scripting language, but not both as the server-side scripting language at the same time.

Core JavaScript is similar enough to Java in syntax that you should be able to port your tool-generated script fairly easily to real Java. Not all JSP containers support JavaScript as a server-side scripting language, and none are required to. If you do use JavaScript as the scripting language in your JSP, remember that only the so-called "core" JavaScript will work. All client-side and server-side specific JavaScript requires either a web browser or a separate server extension to work, and that's not what's meant by supporting JavaScript as a JSP scripting language.

How can I convert my 0.9 JSP files to 1.1?
Created:2000-04-04 15:53:37.235
Modified:2000-04-04 23:16:42.549
Primary contributor:Terence Parr

Converting your JSP 0.9 to 1.1 is a straightforward syntax translation for the majority of your files--you won't have to change the semantics. I built a script, updatejsp, to take care of translating 95% of my files; the others, I converted by hand since it was easier/faster than making a perfect script.

Given the one-to-one nature of the translation, sed/awk (could've used perl) are sufficient--full parser generators, such as ANTLR are overkill. On the other hand sed/awk don't deal well with constructs that cross newline boundaries. Oh well.

What translations does updatejsp perform? The script translates includes, imports, <SCRIPT> tags, and <BEAN> tags:
JSP 0.9 JSP 1.1
<!--#INCLUDE FILE="include/stdhdr.inc"-->
<%@ include file="include/stdhdr.inc" %>
<%@ import="javax.servlet.http.*" %>
<%@ import="java.util.*" %>
<%@ import="java.net.*" %>
<%@ import="java.io.*" %>
<%@ page import="
        javax.servlet.http.*,
        java.util.*,
        java.net.*,
        java.io.*,
"%>
<SCRIPT runat="server">
interface Verbosity {
        final int TERSE = 1;
        final int NORMAL = 2;
        final int VERBOSE = 3;
}
</SCRIPT>
<%!
interface Verbosity {
        final int TERSE = 1;
        final int NORMAL = 2;
        final int VERBOSE = 3;
}
%>

Here is the start of an 0.9 JSP file with a <BEAN> tag I have broken the long line for formatting reasons here, but in "reality" the <BEAN> tag is on a single line:

<BEAN name="view" type="com.epicentric.portalbeans.PortalBeanView" introspect="no" create="no" \
 scope="request" >
</BEAN>

<%@ import="java.util.*" %>
<%@ import="java.net.*" %>
<%@ import="java.io.*" %>

<!--#INCLUDE FILE="include/PortalEntityClient.inc"-->


<SCRIPT runat="server">
static public int sloganIndex = 0;
</SCRIPT>

The updatejsp script translates it to the following:

<%@ page import="
        java.util.*,
        java.net.*,
        java.io.*,
"%>
<jsp:useBean id="view" type="com.epicentric.portalbeans.PortalBeanView" scope="request">
<jsp:useBean>

<%@ include file="include/PortalEntityClient.inc" %>

<%!
static public int sloganIndex = 0;
%>

What does updatejsp not do? The script doesn't deal with random whitespace (for example, it likes a space before the 0.9 import word) nor does it deal with tags broken across lines. If you have large whitespace variation in your JSP files, I would suggest fixing this script. If you have lots of tags broken across lines, I'd write a real parser with ANTLR that sees a stream of token objects not characters (making it not care about newlines and weird whitespace).

Here is the code you'll need. The updatejsp script is written in bash and you'll need awk for genimports.awk, which is presumed to live in the same dir as the updatejsp script. "Your mileage may vary." :)

updatejsp:

#!/bin/bash
#
# Convert bean, include, SCRIPT, and import syntax to JSP 1.1
# Handles modules and regular JSP files. Does not do a good
# job with the <BEAN...> tag.  Assumes all on one list for example.
#
# Terence Parr, jGuru.com
#

# F is the file we're dealing with
F=$1

#
# compute location of genimport.awk; assume same dir as executable
# $0 is full pathname to this executable script
# I hack off the path (which assumes at least "./" as path) and
# then append "/genimport.awk" to get that script
#
UPDATEJSP=$0
GENIMPORT="`expr $UPDATEJSP : '\(.*\)/.*'`/genimport.awk"

# make sure a filename is specified
if !(test $1)
then
        echo "Usage: updatejsp filename"
        echo "Example: updatejsp view.jsp"
        exit
fi

# make sure a filename is writable
if !(test -w $1)
then
        echo "File $1 is not writable"
        exit
fi

# make sure the file is indeed an old style file
if !(grep -s -q '\%\@ import' $F || \
     grep -s -q '\#INCLUDE' $F || \
     grep -s -q '<SCRIPT' $F || \
     grep -s -q '<BEAN' $F)
then
        echo "Sorry, but $F doesn't look like an old-style JSP file to me"
	echo "I couldn't find '<%@ import', '<BEAN...>', "<SCRIPT", or '#INCLUDE'"
        exit
fi

# convert includes to new form and change "portal/" to "/portal/" and for jguru
sed 's/<\!\-\-\#INCLUDE FILE=\"\(.*\)\"\-\->/<%@ include file="\1" %>/g' < $F \
  > /tmp/updatejsp.tmp

# convert BEAN to jsp:useBean and /BEAN to /jsp:useBean
# this does NOT work when <BEAN...> is on more than one line
# The next line is broken up for formatting purposes
# but the \ should be removed and the associated newline
# when you try to run the script
sed 's/<BEAN.*>/<jsp:useBean id="view" type="com.epicentric.portalbeans.PortalBeanView" \
 scope="request">/' < /tmp/updatejsp.tmp | \
sed 's/<\/BEAN>/<\/jsp:useBean>/' > /tmp/updatejsp.tmp2

# print out the combined import as page directive
if ( grep -s -q '\%\@ import' $F )
then
    awk -f $GENIMPORT < /tmp/updatejsp.tmp2 > /tmp/updatejsp.tmpF
fi

# convert SCRIPT to <%! block
sed 's/<SCRIPT.*"server">/<%!/' < /tmp/updatejsp.tmp2 | \
sed 's/<\/SCRIPT>/%>/' > /tmp/updatejsp.tmp3

# print file minus old import lines
sed '/<%@ import=".*" %>/D' < /tmp/updatejsp.tmp3 >> /tmp/updatejsp.tmpF

# back up old file
mv $F $F.bak

# mv in the new file
mv /tmp/updatejsp.tmpF $F

genimports.awk:

			#
			# Walk an old jsp file, grabbing import names.
			# Then generate a new style import statement
			#
			# Terence Parr, jGuru.com
			#
BEGIN			{n=0;}
/<%@ import=".*" %>/	{a=index($0, "=\""); b=index($0, "\" "); #print substr($0, a+2, b-a-2);
			 files[n++] = substr($0, a+2, b-a-2);
			 next;
			}
END			{ print "<%@ page import=\"";
			  for (i=0; i<n; i++) {
			    if ( i<n-1 ) sep=",";
                            else sep="";
                            printf "\t%s%s\n", files[i], sep;
                          }
			  print "\"%>";
			}

Is there any equivalent to the "global.asa" file that's available for ASP developers in JSP?
Created:2000-04-04 20:30:04.151
Modified:2000-04-05 11:06:32.525
Primary contributor:Peter Kua

There isn't an equivalent global.asa file in JSP. I believe Sun has a reason for that. However there is a workaround you can perform. For example if you need to store and access variables with application scope, you can always create a javabean, and include it in pages that need these variables.

<jsp:useBean id="globals" scope="application" class="com.xxx.GlobalBean"/>

Is there any way in JSP to set focus on an input field in a HTML form using JSP code, and not JavaScript?
Created:2000-04-08 09:51:36.52
Modified:2000-05-29 12:36:09.162
Primary contributor:Govind Seshadri

No, there isn't. Remember, JSP is strictly a server-side technology, which is responsible for generating dynamic content in HTML, DHTML or XML format. Setting focus on specific input elements within an HTML form is strictly a client-side activity and consequently has to be performed using something like JavaScript.

How different is JSP architecture from ISAPI architecture?
Created:2000-04-10 07:35:25.787
Modified:2000-04-11 09:00:14.922
Primary contributor:Christopher Longo

JSP is not analogous to ISAPI. JSP to ASP would be a better comparison. JSP is an abstraction of Java Servlets. ISAPI is a low level API for creating web content under IIS.

You could compare ISAPI to Java Servlets, being they are both APIs and they are similar architecturally.

What is the best way to do database connection pooling using JSPs?
Created:2000-04-10 07:38:05.04
Modified:2000-04-11 09:05:26.503
Primary contributor:Christopher Longo

You have at least three choices:

A) Use the database pooling services built into JDBC 2.0-compliant drivers.

B) Use an application server such as WebLogic or WebSphere, which provides these services.

C) Write your own database pooling classes (it's really not that complicated).

Can I use a bean in a JSP that implements the Runnable interface or extends the Thread class?
Created:2000-04-10 15:58:39.968
Modified:2000-04-11 09:03:39.377
Primary contributor:Maxim Senin

Yes. According to JavaBeans specification, any Java clss can be a JavaBean as long as it has public scope, getter/setter methods for its properties and contains a public no-arg constructor.

Could you describe the architecture behind jGuru.com: JSP, Servlets, database, servers, transactions etc...?
Created:2000-04-11 14:30:57.127
Modified:2000-06-21 15:31:36.422
Primary contributor:Terence Parr

[here's a quick "core dump". TJP]

When confronted with a parallel computing problem such as jGuru, we looked for a solution that was simple, flexible, and fast. jGuru is designed to support a cloud of cheap web servers talking to an array of database servers using a trivial protocol called ENTP. We use lazy data replication to update the webserver cloud and the various database servers.

Our constraints are pretty relaxed. For example, it's ok if the FAQs are only updated every few hours since they don't change that much. Massive caches on the webservers reduce the load on the ENTP server and are refreshed lazily when they are stale. Cache coherency among multiple servers is not really a problem since we don't have multiple servers trying to collaborate on the same piece of data simultaneously.

We use JSP for every page of the portal. There are lots of support ".java" files, but any page that is part of the portal has to have dynamic content.

Why do we use JSP? The site required dynamic content. That meant either CGI-BIN, servlets, or JSP. CGI-BIN is not nearly as integrated or convenient as servlets or JSP files and cannot maintain connection state efficiently; pretty important when somebody has to be "logged in" to your site. JSP files are essentially servlets that you don't have to register and you can treat just like HTML files in terms of URLs. JSP files are also more convenient because they are automatically recompiled for you when you change them. JSP files rule!

We use Epicentric's portalserver infrastructure to handle lots of the site personalization functionality, but naturally we've extended that significantly to make jGuru. Beyond JSP, we use only the simplest of APIs: JDBC, sockets, and IO. No EJB, no RMI, no transactions (minus JDBC database transactions, of course).

Network protocols seem to be the only thing that have staying power on the net; for example, mail/SMTP, news/NNTP, ftp/FTP, web/HTTP, etc... Heck, not even the implementations of these protocols hang around. ENTP or, ENtity Transfer Protocol, acts like an HTTP server that serves entities (objects) not files. ENTP has about 8 commands and pushes/pulls entities and query results in XML form. You can make an ENTP client in Java, PERL, Python, VB, anything. We built an ENTP server that implements an extremely flexible entity-to-relational DB mapping. We have a Java-like entity description language and can change the schema while all the servers are running!

We have 3 databases running: one for portalserver user stuff, one for the ENTP server, and one for the API search engine. All or any of these can be put on their own machine. The webservers talk to the databases directly via JDBC except for the ENTP database, for which they speak the ENTP protocol.

One of our goals was to make jGuru as "data-driven" as possible. Consequently, we have about 5 custom languages that describe everything from our schema to our entity data (XML serialization for that one). We have custom html validation parsers and so on as well. We can run simulations through our server to test efficiency upgrades and so on using files with various custom data formats. We also make heavy use of Java property files.

We use Blackdown JDK 1.1.8 but are expecting to move to IBM's JDK. We develop and deploy jGuru on Linux. We were using JServ/GNUJSP, but are moving to Resin almost certainly at the end of April 2000.

Let's assume I use a JavaBean as a go-between a JSP and an EJB, and have, say, 50 concurrent clients that need to access the EJB functionality. Will the JSP container actually instantiate 50 instances of the bean, or can it reuse a single instance to access the EJB?
Created:2000-04-11 20:24:29.823
Modified:2000-04-11 20:26:17.762
Primary contributor:Govind Seshadri

It depends on the scope you associate with the JavaBean. If you assign the bean with page (which is the default) scope or request scope, a new bean will be instantiated for each incoming request.

If you assign the bean with session scope, you will still have 50 instances loaded in memory (assuming each incoming request is triggered by a distinct client), although some may have been instantiated from an earlier request from the same client. However, you may not want to use the session scope for a high-volume site as these beans will continue to reside in memory, long after the request has been serviced, consuming valuable resources until they are invalidated either explicitly or due to a session timeout.

You can also assign the bean with application scope, in which case it is instantiated just once before being placed into the servlet context of the container. It can then be accessed at a later time, as long as the server is up and running. Although this may sound like an attractive proposition, do note that you will have to contend with significant multithreading issues. For instance, you'll have to ensure that the bean is accessed in a thread-safe manner from each of the JSP files. While you can do this using explicit synchronization from within the JSP file, do note that your application may take a significant performance hit because of this - especially if you expect tens or hundreds of concurrent clients accessing your pages.

So, in short, your best bet may be to assign the bean with request scope.

How can I determine the name and version number of the servlet or JSP engine that I am using?
Created:2000-04-11 21:15:24.268
Modified:2000-06-21 15:58:37.148
Primary contributor:Govind Seshadri

From within a servlet, you can invoke the ServletContext.getServerInfo() method as follows:

String thisServer= getServletConfig().getServletContext().getServerInfo();

If you are using JSP, you can use this expression:

<%= application.getServerInfo() %>

What are all the implicit objects available within a JSP page?
Created:2000-04-11 22:52:16.364
Modified:2000-06-09 09:17:39.039
Primary contributor:Govind Seshadri

The eight implicit variables available within JSP pages are:

How can I get the absolute URL of a servlet/JSP page at runtime ?
Created:2000-04-12 01:13:51.67
Modified:2000-06-16 15:23:39.132
Primary contributor:Frank Steidinger

You can get all the necessary information to determine the URL from the request object. To reconstruct the absolute URL from the scheme, server name, port, URI and query string you can use the URL class from java.net. The following code fragment will determine your page's absolute URL:

String file = request.getRequestURI();
if (request.getQueryString() != null) {
   file += '?' + request.getQueryString();
}
URL reconstructedURL = new URL(request.getScheme(),
                               request.getServerName(),
                               request.getServerPort(),
                               file);
out.println(URL.toString());

Are there any good books out on JavaServer Pages?
Created:2000-04-13 15:30:08.991
Modified:2000-05-24 10:33:37.118
Primary contributor:John Zukowski

While most of the older Servlet books include a chapter on the subject, several new books on the subject are recently out that include information on JSP 1.1, including tag extensions:

Can I use WML (wireless markup language) from a Java Server Page?
Created:2000-04-13 15:32:57.116
Modified:2000-05-12 08:13:30.136
Primary contributor:Shaun Childers

Follow these steps for using WML instead of HTML from within JSP.

1) Make sure that the following is added to your MIME types file of your web server and restart it: File Extension = .wml MIME Type = text/vnd.wap.wml

2) (From this point forward, you would do the following inside your servlets just as you would inside your JSP files.) In your JSP file set your response type to text/wml (normally it's text/html or text/plain for HTML).

3) Instead of outputting HTML code inside your JSP file, you just output WML code. You can do this different ways: you can just use the

out.println("<wml>");
...
out.println("<card>");
...
or you could create WML classes in Java and just have a class for each WML tag (WML is a small set of HTML, so you will have around 30 classes). Each WML class would appropriately handle the syntax specific to itself and handle you placing data into this syntax. Each class would also have a toString() method. From here, in your JSP file, wherever you want your WML code, just write Java (you have the WML classes), then to output the WML code, you would write out.println(wml.toString()); The wml.toString() method would call all of the other classes' (Card, Select, etc.) toString() method to output all of the WML syntax. This design works well because if the WML syntax changes and you have 100 JSP files with WML syntax inside, you would have to change every one on them; using the WML classes, if the WML syntax changes, you just have to change that particular class associated to whatever tag changed, and then recompile your class.

Now, keep in mind that there is one problem with outputting WML through JSP - if your web phone is trying to call a JSP file (not through a servlet), and there is a problem in which the JSP file outputs an error, whatever is handling your JSP files will probably output an error in HTML format, not WML, and therefore your phone browser will not be able to interpret this and will give you an error page built into the phone browser. For example, if you are using JRun to run your JSP files and it is not up and running, you will receive an error in HTML. You could develop an error handling system for capturing JSP errors and if you are expecting WML, you could return an error page in WML.

It seems to me that a JSP page forward always ends up in the frame where the original JSP page was in. How can I replace the entire frame with a new page?
Created:2000-04-14 12:38:52.597
Modified:2000-05-29 13:28:44.483
Primary contributor:Michael McElligott

Unfortunately, your JSP application has no way of knowing that it's being loaded into a frameset - your forward will always be loaded into the browser in the place that the original request would have gone. One solution I'm aware of is to write a small snippet of javascript changing the document location to your new location. So that, instead of doing a response.forward(String f) you would instead place something like:

out.println("<script language='javascript'>");
out.println(" top.document.location = " + f + ";");
out.println("</script>");

Actually, "top" might be the wrong keyword, but you get the idea (obviously, if you want the change to a peer frame, you have to navigate up to it in your Javascript - parent.peer.document.location = "foo.jsp").

Can I write a JSP program which can act an an FTP client?
Created:2000-04-20 11:29:48.368
Modified:2000-04-20 11:59:02.829
Primary contributor:Shaun Childers

Sure. Just put in "ftp://ftp.xxxxxxxx" instead of "http://www.xxxxxxxx" and it should work fine. Just make sure that the target of the ftp link has an FTP server. The JSP is not really the ftp "program" you are asking about, but JSP is used to dynamically create static pages, therefore the JSP file could create the ftp links (client links) to the ftp server. You could just as easily make your JSP file access an ftp search engine, all the while the user thinks you are the search engine.

How can I refresh the page my browser is showing with JSP?
Created:2000-04-23 21:34:07.495
Modified:2000-04-23 22:38:26.613
Primary contributor:Govind Seshadri

You can use a META tag with an HTTP-EQUIV attribute to control the action of browsers, by setting the HTTP headers. The "Refresh" value can be used to specify a delay in seconds before the browser automatically reloads the document. Optionally, you can also specify an alternative URL to load.

For example, the following tag loads the page foo.html after 5 seconds.

<META HTTP-EQUIV="Refresh" CONTENT="5;URL=http://www.somehost.org/foo.html">

To cause a reload on the same resource, don't specify the alternative URL. The following program demonstrates a running counter where the reload is controlled by the client:

<html>
<META HTTP-EQUIV="Refresh" CONTENT="3">
<body>
<% 
	int i=0;
	String ii = (String) session.getValue("count");
      if (ii!=null) { 
		i = Integer.parseInt(ii);
		out.println("<h1>Counter is: "+i+"<h1>" );
	      i++;
	}
      session.putValue("count",new Integer(i).toString());
%>
</body>
</html>

Can a JSP be multi-threaded?
Created:2000-04-23 22:48:49.908
Modified:2000-04-23 22:53:11.557
Primary contributor:Govind Seshadri

By default, the service() methods of all JSP pages execute in a multithreaded fashion. Each client request is dispatched in a concurrent manner within a separate thread by the servlet engine. Thus, it is important to synchronize access to any page shared state in the default scenario.

You can make a page "thread-safe" and have it serve client requests in a single-threaded fashion by setting the page tag's isThreadSafe attribute to false:

<%@ page isThreadSafe="false" %>

This causes the generated servlet to implement the SingleThreadModel interface.

Can a JSP page access data in a Hashtable instead of a bean? If so, what is the syntax? For example, I want to put simple values into the Hashtable as well as more complex values such as other Hashtables or Vectors and retrieve them by key.
Created:2000-04-23 22:53:45.734
Modified:2000-04-24 19:00:00.848
Primary contributor:Govind Seshadri

You can use just about any Java class within a JSP page. If the class does not subscribe to JavaBean design patterns (i.e. has no getter/setter methods for properties) it cannot be used within the <jsp:getProperty> and <jsp:setProperty> tags, and has to be accessed only within scriptlets.

The following source code demonstrates the usage of Vector and Hashtable objects within JSP scriptlets:

Page1.jsp creates a Hashtable and initializes it with some data before placing it into the session:

<%@ page import="java.util.*"%>
<html>
<body>
<jsp:useBean id="myHash" class="java.util.Hashtable" scope="session">
<%
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));

Vector cities = new Vector();
cities.addElement("Paris");
cities.addElement("Venice");
cities.addElement("San Francisco");

myHash.put("numbers",numbers);
myHash.put("cities",cities);
%>
</jsp:useBean>
Placed hashtable within the session...
</body>
</html>

Page2.jsp extracts the previously instantiated Hashtable instance from the session and displays its contents:

<%@ page import="java.util.*"%>
<html>
<body>

<jsp:useBean id="myHash" class="java.util.Hashtable" scope="session" />

Printing out the contents of Hashtable instance extracted from the session:
<p>
<%
Hashtable newNumbers = (Hashtable)myHash.get("numbers");
if (newNumbers != null) {
	Enumeration e = newNumbers.keys();
	Collection c = newNumbers.values();
	Iterator i = c.iterator();
	while (i.hasNext()) {
		Integer intValue = (Integer)i.next();
		out.println(e.nextElement()+"="+intValue.toString()+"
"); } } Vector newCities = (Vector)myHash.get("cities"); if (newCities != null) { out.println("

"); for (int i=0; i newCities.size();i++) out.println("newCities["+i+"]="+newCities.elementAt(i)+"
"); } %> </body> </html>

How do you stop all futher processing in a JSP page?
Created:2000-04-24 12:36:16.713
Modified:2000-04-30 23:32:40.947
Primary contributor:Christopher Longo

You could always just stuff a return in a scriptlet.


...
<%   String action = (String)request.getParameter("action");
     if(s.equals("stop!"))
        return;
%>
...

This should work with all JSP implementations.

Keep in mind that what you are doing in essence is returning from the middle of a Servlet service() method.

I always recommend use of "if" and "else" statements control the flow of the JSP page, rather than bluntly returning.

What is the difference between Java Servlets and Java Server Pages (JSP)?
Created:2000-04-24 17:19:30.328
Modified:2000-04-24 20:29:21.325
Primary contributor:Alex Chaffee

Short answer: a JSP is a Servlet that thinks it's a Web page.

Medium answer: Both use server-side Java to dynamically generate web pages. The source code to a JSP looks like HTML, with Java embedded inside funny tags; the source code to a servlet looks like Java, with HTML embedded in out.print(...) statements. Both use the Servlet API to communicate with the web server and the client. In fact, a JSP gets compiled into a servlet, so they're almost identical in terms of expressive power. The choice is, whether you're more comfortable coding your pages in Java or in JSP-style HTML; and since you can call a JSP from a Servlet and vice versa, you don't have to make an either-or decision.

Long answer: See the Servlet FAQ and the JSP FAQ for all the information you need about both technologies.

Can you give an example of how I can use JSP 1.1 TagLib feature to create custom and portable actions for my JSP pages?
Created:2000-04-25 14:03:02.688
Modified:2000-04-27 06:55:39.135
Primary contributor:Meena Guna

http://www.orionserver.com/tutorials/tagtut/lesson1/lesson1.html contains a getting started tutorial on tag extensions.

Can we maintain an XML data structure on the client side using JavaScript? Is there any parser to parse the xml data on the client side? The xml data will be passed as an string.
Created:2000-04-25 14:28:40.893
Modified:2000-06-01 06:26:23.758
Primary contributor:Nicola Ken Barozzi

Yes, refer to the XML data islands on the Microsoft web site.
You can have the XML in a web page (which can be generated dynamically) or embedded in the HTML. You can use Microsoft XML data islands that get XML data from a servlet.
CODE:
<HTML>

  <SCRIPT>
    function display()
    {
      data.transformNodeToObject(ss.XMLDocument, resultTree.XMLDocument);
      document.write(resultTree.xml);
    }
       </SCRIPT>
  
  <SCRIPT FOR="window" EVENT="onload">
    data.async = false;
    data.load("../servlet/SQLResult");
    ss.async = false;
    ss.load("MyStyleSheet.xsl");
    display();
  </SCRIPT>
  
  <XML id="data"></XML>
  <XML id="ss"></XML>
  <XML id="resultTree"></XML>


</HTML>

Here "../servlet/SQLResult" is a servlet URL.

If you prefer you can embed the XML directly in the page.
CODE:
<HTML>

  <SCRIPT>
    function display()
    {
      data.transformNodeToObject(ss.XMLDocument, resultTree.XMLDocument);
      document.write(resultTree.xml);
    }
       </SCRIPT>
  
  <SCRIPT FOR="window" EVENT="onload">
    data.async = false;
    ss.async = false;
    ss.load("MyStyleSheet.xsl");
    display();
  </SCRIPT>
  
  <XML id="data"></XML>
  <XML id="ss"></XML>
  <XML id="resultTree">

  YOUR XML GOES HERE
 
  </XML>


</HTML>

Also refer to jGuru FAQ Entry 39154.

Can I pass GET parameters specified within the ACTION clause of a FORM in a JSP page as:
ACTION="xyz.jsp?userid=<%=userid%>"
to another JSP page?:

Are there any other ways to pass GET parameters from a FORM to a JSP page?
Created:2000-04-26 01:27:24.782
Modified:2000-05-02 18:38:59.252
Primary contributor:Frank Steidinger

You can do this if the FORM itself is submitted using POST. So the example would be:

<FORM ACTION="xyz.jsp?userid=<%=userid%>" METHOD="POST">

This way you can read the userid from xyz.jsp along with the fields from the form you are submitting. An alternative would be to use a hidden field as in:

<input type="hidden" name="userid" value="<%=userid%>">

If you include a hidden field like this in your form you can use GET or POST to submit it and the userid is passed to the xyz.jsp just like any other field.

When I reference 'session' or 'request' from within a method contained in a declaration, I get an 'Undefined variable' compile error. Why?
Created:2000-04-26 11:41:23.88
Modified:2000-04-26 11:41:58.468
Primary contributor:John Zukowski

The implicit objects session, request, etc. are defined in the JSP service method _jspService(). The are not instance level variables of the created JSP class. Hence, they are not immediately available to methods outside the service method. You would need to pass them in as parameters.

What is the diference between a front component and a presentation component?
Created:2000-04-27 23:33:52.576
Modified:2000-04-27 23:35:34.597
Primary contributor:John Zukowski

According to the JSP specification, front JSP pages or front components are those that accept the HTTP request from the client and use information in the request to access some server-side data source. Pure front components are not responsible for presentation. It is the presentation JSP page or presentation component that takes said data from the front component and displays it in some template.

How can I precompile all my JSP files when I place them on my web site? I don't want to wait until they are hit the first time.
Created:2000-04-28 05:45:34.351
Modified:2000-05-05 05:54:19.233
Primary contributor:Pete Lyons

Release 3.1 of the Jakarata Tomcat JSP server (found at jakarta.apache.org) includes a JSP compiler (JSPC) that does exactly this. You can specify either a web application directory or a specific jsp file to compile.

How does the "session" scope work with the useBean tag? What is the difference between "session" and "application" for the useBean tag?
Created:2000-04-28 12:27:30.353
Modified:2000-05-07 21:33:38.595
Primary contributor:Kellan Elliott-McCrea

When you request a bean from the session scope or the application scope, and such a bean already exists, the reference to the existing bean is returned, and a new bean is not instantiated; otherwise, the bean is newly instantiated, placed into the specified scope, and the reference is returned.

The session scope is different then the application scope in that an application bean is kept around until the servlet/jsp container is restarted, while session beans time out after a specified amount of inactivity or if the session is invalidated for any reason. Also, beans with session scope are available only to a single client which participates in the session; beans with application scope have "global" visibility and are available to all JSPs and servlets which are part of the application.

How can I incorporate mail facilities into JSP pages?
Created:2000-04-28 20:18:43.998
Modified:2000-04-28 20:22:58.827
Primary contributor:John Zukowski

Why, by using the JavaMail API of course... Your best bet is to create some JavaBeans that do all the work and access the beans from the JSP pages. You'll need to include the appropriate mail classes in the CLASSPATH of your server. If you don't want to create the beans yourself, you can always buy them. ImMailBean is one such product.

What is the most efficient approach for integrating EJB with JSP? Should the EJBs be invoked directly from within JSP scriptlets? Should the access take place from within Java beans? Or is it best to use custom tags for this purpose?
Created:2000-05-01 10:38:21.366
Modified:2000-05-02 23:22:15.212
Primary contributor:Christopher Longo

JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page results in many lines of code on your JSP page, including try...catch blocks to catch naming and finding exceptions.

Using a standard JavaBean as an intermediary between the JSP page and EJB server cuts down on the amount of code needed to add to a JSP page, and promotes reuse. The JavaBean should be a simple wrapper around the EJB you are accessing.

If you use a standard JavaBean you could also use the jsp:useBean tag to setup EJB parameters, such as the server URL and server security parameters.

Custom tags are also an option. However, they require a lot more coding than a simple JavaBean wrapper. The point should be to rewrite as little code as possible while at the same time keeping the JSP scriptlet content as light as possible.

How do I get a JSP page to implement a Java interface?
Created:2000-05-02 02:36:07.259
Modified:2000-05-07 21:38:50.085
Primary contributor:Frank Steidinger

A JSP page can't directly implement an interface. If you really need to do this you'll have to define a superclass for your page which implements the interface. If you declare this superclass to be abstract you can defer the implementation of the interface to the JSP page. This superclass will have to implement the interfaces HttpJspPage and Servlet too, otherwise you will get a compilation error from the JSP compiler.

If the interface you want to implement were named MyInterface, you could define a class Intermediate:


public abstract class Intermediate implements MyInterface, HttpJspPage, Servlet {&lt;BR&gt;
  protected ServletConfig  config;
  public String  getServletInfo() { return &quot;JSP Page&quot;; }
  public ServletConfig  getServletConfig () { 
    return  this.config; }
  public void  init(ServletConfig config) throws ServletException
  {
    this.config = config;
    jspInit();
  }
  public void destroy () { jspDestroy(); }
  public void  service(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException
  {
    _jspService ((HttpServletRequest) request, (HttpServletResponse) response);
  }

}

Then you can subclass this Intermediate in your JSP page using the page directive:

<%@ page language="java" extends="Intermediate"%>

How can I get the version of the Servlet API that is being used by a servlet/JSP engine?
Created:2000-05-02 19:32:22.725
Modified:2000-06-21 16:01:18.957
Primary contributor:John Zukowski

The ServletContext interface includes methods getMajorVersion() and getMinorVersion() to tell you what version of the Servlet API is in use.

[Alex Chaffee adds:]

So, for example, JSWDK 1.0.1, which supports the Servlets spec 2.1, would return "2" for getMajorVersion() and "1" for getMinorVersion().

From a JSP, you can use the implicit application object to access the ServletContext. For example:

Major: <%=application.getMajorVersion()%>
Minor: <%=application.getMinorVersion()%>

Jason Hunter's com.oreilly.servlet package has some code for determining this in an allegedly more robust manner.

See also How can I determine the name and version number of the servlet or JSP engine that I am using?

What is the recommended, "best" architecture for JSP applications?
Created:2000-05-03 15:12:39.196
Modified:2000-05-03 22:41:14.02
Primary contributor:Christopher Longo

There really is no "best" architecture. It depends on:

  1. The size and scope of the application.
  2. The amount of resources (human and monetary) available to develop the application.
  3. Time available to develop the application.

For a relatively small application which requires simple database access, a three-tier model using JSP, JavaBeans, and JDBC is all that you need. The JavaBeans would contain methods to access the data via JDBC. The JSP pages would embed the JavaBeans in the page using the <jsp:useBean> tag.

If the use of the application grows, you can always add database pooling and other optimizations to scale the architecture without redesigning everything.

If your application is going to going to be large scale - an online e-commerce site for instance, you would want to invest in a more scalable solution. I would recommend a "n-tier" solution using JSP, (standard) JavaBeans, and Enterprise JavaBeans.

JSP would provide the client interface. One or more JavaBeans would sit between the JSP pages and the EJB container. The JavaBeans would be embedded in your JSP pages using the <jsp:useBean> tag. The JavaBeans would utilize session beans to perform transactions and access data on entity beans.

This architecture is both distributed and scaleable. It supports transactions and all the benefits an application server has to offer (database pooling, clustering, etc).

Never throw JDBC code or EJB code directly on your JSP page. This leads to clutter which most web designers (the people who have to work with on the page) would probably not understand and would rather not look at. Not to mention it quickly becomes a maintenance nightmare.

How do I include a file in my JSP file where I don't know the filename to include until runtime?
Created:2000-05-05 06:56:09.93
Modified:2000-05-05 07:05:35.938
Primary contributor:John Zukowski

This question describes the basic difference between the <%@include file="abc.jsp"%> directive and the <jsp:include page="abc.jsp"> tag. Basically, the first is done at compile time and the latter is done at runtime.

If the filename itself isn't known until runtime, you need to include another directive in the use of <jsp:include> like:


<% String filename = "foo.jsp"; %>
<jsp:include page="<%= filename %>" flush="true"/>

How do I pass session information from a JSP to a Applet. Can I pass them as parameters or can I talk back from an Applet to the JSP page?
Created:2000-05-07 11:34:13.636
Modified:2000-05-07 22:03:30.1
Primary contributor:Pete Lyons

The easiest way to pass session info is through the applet parameters. The following example code uses some scriptlet tags to set the parameters of the applet.

<applet code="foo.class" width="100" height="100">
<% 	
for (x = 0;  x < session.fooData.getCount(); x++) {
%>
	<param name="<%= session.fooData.getName(x) %>" value="<%= session.fooData.getValue(x) %>">
<% } %>
</applet>

If you want to have the applet be able to talk back to the server as it runs you can do that too. In this case the applet should not communicate with the JSP that hosted it but rather with a servlet running in the same web application. Both the JSP and the servlet would share the same session info so you have access to the same data. The following example uses serialized object to pass the information back and forth but you could form the requests and responses with plain text or xml or whatever. The applet needs to open a connection to the web application, post a request and listen for the response.

public MyResponse	postRequest(MyRequest myRequest) {
	
	try {
		// Open the connection
		URL url = new URL(getCodeBase(), "myServlet");
		URLConnection uc =  url.openConnection();

		// Post the request
		uc.setDoOutput(true);
		uc.setDoInput(true);
		uc.setUseCaches(false);
		uc.setRequestProperty("Content-type", "java-internal/" + myRequest.getClass().getName());
		ObjectOutputStream out = new ObjectOutputStream(uc.getOutputStream());
		out.writeObject(myRequest);
		out.flush();

		// Read the response
		ObjectInputStream in =	new ObjectInputStream(uc.getInputStream());
		return (MyResponse) in.readObject();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

The servlet that handles the post would be pretty simple too. It just needs to read the request, figure out what the request was and return the correct data.

public void doPost(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException {

	try {
		// Read the resquest
		ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
		MyRequest  myRequest = (MyRequest) ois.readObject();

		// Format the response from the session data
		HttpSession session = req.getSession(true);
		MyResponse myResponse = new MyResponse(session.fooData);

		// Send the response
		ObjectOutputStream	oos = new ObjectOutputStream(res.getOutputStream());
		oos.writeObject(myResponse);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Where do I place the JAR files so that I can use JavaMail from JSP?
Created:2000-05-08 06:21:18.757
Modified:2000-05-08 10:08:08.318
Primary contributor:John Zukowski

Using the JavaMail API from JSP pages requires the JavaMail and JavaBeans Activation Framework JAR files (mail.jar and activation.jar respectively) to be in the CLASSPATH for the Java runtime of your JSP-enabled web server. While most servers allow you to configure their CLASSPATH, either through mucking with batch files or through some configuration program, the easiest way to configure the server is to take advantage of the standard Java Extensions Mechanism. Just copy the JAR files into the ext under your Java runtime directory. For instance, Windows users of Java 1.2.2 who installed to the default location would copy the JAR files to C:\JDK1.2.2\JRE\LIB\EXT.

How can I display content in the form of a Tree using JSP?
Created:2000-05-09 09:08:52.942
Modified:2000-05-29 13:36:30.339
Primary contributor:Simon Brown

There are a few ways that you could try, although it all depends on any restrictions you have on deployment.

First off, you could use Swing's JTree in a small applet. This would require the use of the Java plug-in on the user's browser so may not be viable for you.

Secondly, you could use one of the Javascript/DHTML "tree controls" that are out there. Take a look on jars.com and I'm sure you'll find one.

Finally, you could write a "tree" using HTML, images and hyperlinks to open up nodes in your tree. This will ensure that you reach the maximum number of target browsers but could be tricky to get right - depending on your experience of HTML.

Which is faster -ASP or JSP? Why?
Created:2000-05-10 14:32:18.794
Modified:2000-05-13 20:55:29.744
Primary contributor:Robert McIntosh

Orion Server has posted some excellent benchmarks comparing the relative performance of JSP and ASP pages at:

http://www.orionserver.com/benchmarks/benchmark.html

What is the best way of implementing a web application that uses JSP, servlet and EJB technologies all together following a Model View Controller (MVC) architecture?
Created:2000-05-11 15:24:17.199
Modified:2000-06-21 11:05:30.729
Primary contributor:Dan Christopherson

[See the Sun J2EE Blueprints for "an integrated set of documentation and examples that describe and illustrate 'best practices' for developing and deploying component-based enterprise applications using the J2EE platform" including some good architecture whitepapers and source code. -Alex]

Hmm, 'Best Way' is a bit rough - there are several 'good' ways, and the usual set of trade-offs between them. (I'm a consultant - I have to start any answer with "It depends...", otherwise they revoke my whiteboard privileges)

The main thing you need to keep in mind as you design this sort of a system is that you want the interface into the EJB's to be rather narrow: in any flow, the ideal is to call one EJB method (hopefully on a stateless session bean), and let it make calls to entities on your behalf, then hand back the data you need to display.

How you display it depends: you can either embed beans on your JSPs and let the beans make that hopefully-one EJB call, or you can post to a servlet, let that make the call, then forward to the JSP for display. The second of these is more flexible and gives you more leverage to hide, change, and enforce your site's structure. The first, however, will be easier for developers new to this web thing to follow.

Essentially, I'm saying that Entity beans are your model, your controller is Session beans (maybe with a bit of help from servlets or beans), and your JSPs, beans and servlets are your View.

One thing to note here: this discussion strongly implies that your EJBs are capable of externalizing their state as some number of very simple 'value objects' (not EJBs themselves, just something we can pass back and forth). These value objects are probably tuned tightly to a workflow, and will be produced by that session bean. This way the traffic between the EJB (server) and the JSP/Servlet (client) is tuned to what the client needs, while the transaction load on the server is minimized.

Why should I use the <jsp:useBean> tag, instead of just instantiating beans directly inside scriptlets?
Created:2000-05-12 08:41:29.703
Modified:2000-05-13 21:05:37.701
Primary contributor:Alex Chaffee

The arguments in favor of using the useBean tag are:

The above is excerpted from my article at JavaWorld, Using XML and JSP together (March 2000).

How do I use XML and JSP together?
Created:2000-05-12 08:42:26.87
Modified:2000-05-13 21:24:03.054
Primary contributor:Alex Chaffee

See my article at JavaWorld, Using XML and JSP together (March 2000).

Can JavaScript be used to access JavaBean properties within a JSP page?
Created:2000-05-16 01:57:10.661
Modified:2000-05-29 12:22:07.915
Primary contributor:Mobushir Hingorjo

JavaScript is code nested between SCRIPT tags within an html page. This code is interpreted and executed by the browser on the client PC. There is no way to directly access a JavaBean property within a JSP through JavaScript. One indirect way could be for the JSP to generate JavaScript that contains variables or constants containing values representing JavaBean properties that the JavaScript code could interpret. JavaScript code would, however, not be able to modify these properties.

Is it an acceptable practice to use response.sendRedirect() in a JSP page? Or should you just throw an exception and use the error page directive?
Created:2000-05-16 07:56:04.98
Modified:2000-05-28 19:20:26.748
Primary contributor:Lee Meador

The response.sendRedirect() will direct the browser to go to a new page/url. The new url will appear in the 'location' at the top of the browser page. You must specifiy a full URL like http://www.bob.com/start.html. Using this requires a round trip to the server with all the attendant delays.

A pageContext.forward() will "jump" to the url specified which may be a relative url like "other.jsp" to indicate it is in the same base location as the current page. The browser location box will show the URL of the original page, not the one you redirected to. There is no additional trip back to the browser and then back to the server so time is kept to a minimum.

When using pageContext.forward(), this forwards the original request and response objects. If you need to change one of the attributes in the original request object, there is no function to do this but this can be reset by passing new querystrings in the URL given to forward.

An errorpage directive just puts a big "try {.. } catch (Throwable x) {..}" around the Java for the whole jsp page (including each of the out.print() lines that handle the HTML portion of the jsp page) If an exception is "caught", things are redirected (as in pageContext.redirect() above) to the error page. If you put the "isError" directive on the error page you get a few predefined jsp variables that tell you what the exception is that triggered the jump to the page.

So the answer to your question, in no uncertain terms, is "maybe". It just depends on what you want to do.

How do I use the taglib directive to add custom tags to JSP?
Created:2000-05-17 01:50:01.838
Modified:2000-05-18 18:01:23.357
Primary contributor:Simon Brown

Custom tags are pretty straightforward to build, and a useful tutorial can be found at orionserver.com.

However, this is (of course) geared up to using their own server, so here's an example of how to build a custom tag using the reference implementation of the Servlet/JSP specifications - Tomcat. For simplicity, this example will make use of the example web application that comes with Tomcat (TOMCAT_HOME/webapps/examples).

Step 1 : Build a class that implements the javax.servlet.jsp.tagext.Tag interface as follows. Compile it and place it under the web-inf/classes directory (in the appropriate package structure).
package examples;

import java.io.*;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class ShowDateTag implements Tag {
	
	private PageContext pageContext;
	private Tag parent;
	
	public int doStartTag() throws JspException {
		return SKIP_BODY;
	}
	
	public int doEndTag() throws JspException {
		try {
			pageContext.getOut().write("" + new java.util.Date());
		} catch (IOException ioe) {
			throw new JspException(ioe.getMessage());
		}
		
		return EVAL_PAGE;
	}
	
	public void release() {
	}
	
	public void setPageContext(PageContext page) {
		this.pageContext = page;
	}
	
	public void setParent(Tag tag) {
		this.parent = tag;
	}
	
	public Tag getParent() {
		return this.parent;
	}
	
}
Step 2 : Now we need to describe the tag, so create a file called taglib.tld and place it under the web-inf directory.
<?xml version="1.0" encoding="ISO-8859-1" ?>
&lt!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>myTag</shortname>
  <uri>http://www.mycompany.com/taglib</uri>
  <info>My own tag library</info>

  <tag>
    <name>showDate</name>
    <tagclass>examples.ShowDateTag</tagclass>
    <info>Show the current date</info>
   </tag>       

</taglib>
Step 3 : Now we need to tell the web application where to find the custom tags, and how they will be referenced from JSP pages. Edit the web.xml file under the web-inf directory and insert the following XML fragement.
    <taglib>
        <taglib-uri>
	   http://www.mycompany.com/taglib
        <taglib-uri>
        <taglib-location>
           /WEB-INF/taglib.tld
        <taglib-location>
    </taglib>
Step 4 : And finally, create a JSP page that uses the custom tag.
<html>

<head><title>Date tag example</title></head>

<body> 
<%@ taglib uri="http://www.mycompany.com/taglib" prefix="myTag" %>

<myTag:showDate/>
</body>
</html>
Now restart the server and call up the JSP page! You should notice that every time the page is requested, the current date is displayed in the browser.

Whilst this doesn't explain what all the various parts of the tag are for (e.g. the tag description, page context, etc) it should get you going. If you use the tutorial (above) and this example, you should be able to grasp what's going on!

While generating a dynamic XML stream from within the JSP page, how do you reference XSL file to be used for processing this XML ?
Created:2000-05-17 10:42:14.475
Modified:2000-05-20 02:38:56.92
Primary contributor:Ike Kotlyarsky

You will have to use the following tag:

<?xml-stylesheet href="fileName.xsl" type="text/xsl"?>

How can I use the '<%@include file="filename" %>' directive, within an 'if' clause using JSP?
Created:2000-05-18 18:29:29.905
Modified:2000-05-18 18:40:31.997
Primary contributor:John Zukowski

There is nothing special that needs to be done here to include the file, just be sure to close the if scriptlet piece:

<% if (condition) { %>

<%@ include file="foo.jsp" %>

<% } %>

What servlet code corresponds to the various "scope" values for the tag?
Created:2000-05-21 15:42:15.56
Modified:2000-05-22 14:05:26.581
Primary contributor:Alex Chaffee

The jsp:useBean tag is very powerful. It allows you to declare a variable using a single syntax, but produces code that (a) either initializes the variable, or locates it if it's already been initialized, and (b) stores it in one of a number of locations, depending on its scope.

In order to share variables between JSPs and Servlets, you need to know how to create and to access variables from inside your servlet code. Following are examples which should help you understand how to do this.


<jsp:useBean 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 belongs to the application (i.e. belongs to the same servlet context).

The servlet equivalent of the above useBean action is:

foo.Counter counter = (foo.Counter)getServletContext().getAttribute("counter");
if (counter == null) {
  counter = new foo.Counter();
  getServletContext().setAttribute("counter", counter);  
}


<jsp:useBean id="counter" class="foo.Counter" scope="session" />

In this example, when the Counter bean is instantiated, it is placed within the current session, and can be accessed by any JSP or servlet during a subsequent request by the current user.

The servlet equivalent of the above useBean action is:

HttpSession session = request.getSession(true);
foo.Counter counter = (foo.Counter)session.getValue("counter");
if (counter == null) {
  counter = new foo.Counter();
  session.putValue("counter", counter);
}


<jsp:useBean id="counter" class="foo.Counter" scope="request" />

In this example, when the Counter bean is instantiated, it is placed within the current request object, and can be accessed by any JSP or servlet during a the same request; e.g., if a RequestDispatcher is used, or if or sends the request to another servlet or JSP.

The servlet equivalent of the above useBean action is:

foo.Counter counter = (foo.Counter)request.getAttribute("counter");
if (counter == null) {
  counter = new foo.Counter();
  request.setAttribute("counter", counter);
}


<jsp:useBean id="counter" class="foo.Counter" scope="page" />

In this example the Counter bean is instantiated as a local variable inside the JSP method. It is impossible to share a page scope variable with another JSP or Servlet.

The servlet equivalent of the above useBean action is:

foo.Counter counter = new foo.Counter();

I want to throw an exception that I wrote, from within a JSP page. How do I do it? Do I have to declare a throws MyOwnException somewhere?
Created:2000-05-22 05:32:39.116
Modified:2000-05-24 10:48:04.782
Primary contributor:Frank Steidinger

You can throw any exception you like from within your JSP page without the need to declare a throws clause. In fact you can't declare a throws clause for a JSP -- any exception thrown by code within your JSP that you don't catch within that page is handled by the JSP Container and sent to the error page, which can be indicated via the page tag.

What are the differences between the JSP 1.0 and JSP 1.1 specifications?
Created:2000-05-22 06:01:36.339
Modified:2000-05-24 11:01:36.212
Primary contributor:Peter Mayringer

Besides the Servlet API specifications they run again, the biggest difference is the implementation of Custom Tag Libraries in JSP 1.1.

How can I communicate between a JSP and an included JSP, included via the <jsp:include> syntax?
Created:2000-05-23 09:59:07.891
Modified:2000-05-24 10:59:07.815
Primary contributor:Simon Brown

You can't really "communicate" with an included JSP, but there are a couple of other mechanisms that may help you.

Firstly, you could pass parameters to your included JSP using the <jsp:param> tags. The included JSP can then use these parameters to perform specific processing, etc.

Alternatively, you could use an instance of a JavaBean for the lifetime of that "request" (or session), and let the included JSP ask the bean for any information it requires.

What is the difference between ServletContext and PageContext?
Created:2000-05-25 02:19:13.691
Modified:2000-05-25 15:09:25.213
Primary contributor:Simon Brown

The ServletContext gives information about the container in which the servlet (or JSP) is running in. Parameters for this can be setup in the web application deployment descriptor and there is one ServletContext per web application.

The PageContext gives the servlet (or JSP) information about the request that it is currently handling and contains information about the request and any parameters, the session, the response object, a reference to the output stream and also a reference to the web application's ServletContext.

If "yy.jsp" includes "xx.jsp" and then I modify "xx.jsp" and try to execute "yy.jsp", does the JSP engine recognize "xx.jsp" as being modified? If it detects modification, does it automatically recompile xx.jsp ?
Created:2000-05-25 02:37:53.082
Modified:2000-05-25 17:19:41.681
Primary contributor:Simon Brown

Yes...if you are using the <jsp:include> tag and not the include directive <%@ include %>, xx.jsp will be recompiled automatically if it changes.

You may also want to generate the appropriate META tags within yy.jsp so that it is not cached by either your browser or the proxy server.

What version of the Servlets or JSP specification is supported by my favorite servlet product? (JSDK, JSWDK, Tomcat, J2EE, etc.)
Created:2000-06-03 15:22:24.247
Modified:2000-06-21 15:56:27.871
Primary contributor:Alex Chaffee

Related FAQs:

The following table summarizes the confusion.

Product Product Version Servlet spec JSP spec
Tomcat 3.1 2.2 1.1
Tomcat 3.0 2.2 1.1
Sun J2EE Reference Implementation beta 2.2 ?
Sun JSWDK 1.0.1 2.1 1.0.1
Sun JSDK 2.1 2.1 none
Sun JSDK 2.0 2.0 none
Allaire JRun 3.0 2.2 1.1

Please add information for other servlet engines as feedback to this FAQ; I'll incorporate it into the table.

How can I protect my JSP pages (or servlets) against the user's using the browser's back arrow and losing the session?
Created:2000-06-05 17:26:57.531
Modified:2000-06-05 17:18:10.304
Primary contributor:Volker Stolz

This question is rather puzzling. Unless you're using URL-rewriting, you can't "lose" a session as it is maintained by cookies. If you think about displaying content which might already have become invalid, you can use HTTP-headers for manipulating content life-time. (See FAQs on preventing caching.)

Is there any difference between the attributes class=com.myco.MyClass and the beanName=com.myco.MyClass attributes in the <jsp:useBean> tag?
Created:2000-06-07 11:55:55.783
Modified:2000-06-07 11:47:08.017
Primary contributor:Peter Mayringer

Yes, there is some difference.

class=com.myco.MyClass

instantaites a bean from a class using the new keyword, thus invoking the class' public no-arg constructor as:
new com.myco.MyClass()

beanName=com.myco.MyClass

When you use beanName, the bean is instantiated via the java.beans.Beans.instantiate method. This method can also instatiate serialized forms of a class which may or may not have a public no-arg constructor.

What does the attribute flush=true in <jsp:include page="abc.jsp" flush="true"/> mean? Where is it essential to use?


Created:2000-06-07 11:57:52.122
Modified:2000-06-07 11:49:04.144
Primary contributor:Volker Stolz

From the JSP 1.1 Specs:

"flush: Mandatory boolean attribute. If the value is 'true', the buffer is flushed. A 'false' value is not valid in JSP 1.1." [Emphasis added]

Unluckily there's no statement about the "why".

What happens to the compiled servlet class files when we shutdown the JSP engine? Will they will be erased from memory as well as from disk?
Created:2000-06-08 02:38:43.383
Modified:2000-06-08 02:29:55.445
Primary contributor:Edwin van der Elst

This depends on the JSP engine implementation. Under normal circumstances, the server will leave .class files on the disk until the .jsp file changes, ignoring server restarts. Some engines can be configured to recompile after each restart of the engine, never recompile, or recompile only if the .jsp is newer then the .class file.

What is the equivalent in JSP to FileSystemObject in ASP?
Created:2000-06-09 17:54:02.912
Modified:2000-06-09 17:45:15.077
Primary contributor:Prasad Thammineni

The JSP specification does not support an equivalent of FileSystemObject. Since you use Java as the scripting language, you can use the File I/O classes in the java.io package to perform all file operations.
In order to be able to access files from the JSP independent of its deployed location you can use one or more the following functions:

What are the differences between JSP and ASP?
Created:2000-06-09 19:07:54.217
Modified:2000-06-09 18:59:06.374
Primary contributor:Vibhu Srinivasan

There is a good article on this at http://java.sun.com/products/jsp/jsp-asp.html that answers your question.

Are there any tools to help convert an ASP-based application to a JSP-based application?
Created:2000-06-10 01:13:53.684
Modified:2000-06-10 01:05:06.424
Primary contributor:Prasad Thammineni

There are no tools to convert ASP applications to JSP applications at this time. You have to manually migrate ASP applications to JSP. A recent presentation at WebSphere 2000 talks about the issues that need to be considered while converting ASP applications to JSP. You can get it from ftp://ftp.software.ibm.com/software/websphere/info/ws2k/3-2d.zip.
Also, products are available to execute ASP pages in a Servlet environment from Halycon Software and ChiliSoft - http://www.halcyonsoftware.com/ and http://www.chilisoft.com/.

What JSP engines support clustering?
Created:2000-06-10 21:42:05.597
Modified:2000-06-10 21:33:17.792
Primary contributor:Prasad Thammineni

I know of at least two that support: IBM's WebSphere Application Server Advanced Edition and BEA's WebLogic Application Server

Custom tag libraries and Java Beans are both ways to seperate logic from the content in JSP pages. Can you illustrate particular scenarios where it may be beneficial to use one over the other?
Created:2000-06-10 21:53:12.259
Modified:2000-06-10 21:44:25.86
Primary contributor:Simon Brown

I like to think of using JavaBeans for maintaining state in server side business objects or accessing other resources (EJB's, JavaMail, etc). I use JavaBeans as non-visual components and they do not contain any HTML rendering code.

I use custom tags to hide common functionality that generates dynamic HTML. These tags can gain access to the session information and thus make use of the JavaBeans.

So anything that contains HTML required in the delivered document is encapsulated into a custom tag, otherwise it's a JavaBean.

Is there an example showing introspection or reflection being used in a JSP? I'd like to populate a form w/ data from a bean, then populate that bean automatically with the modified/unmodified data when the page gets/posts to my servlet w/o parsing the parameters.
Created:2000-06-10 21:56:21.832
Modified:2000-06-10 21:47:34.117
Primary contributor:Prasad Thammineni

The following article would probably answer your question completely. It is written by one of the jGuru's - Govind Seshadri:

Advanced form processing using JSP
http://www.javaworld.com/javaworld/jw-03-2000/jw-0331-ssj-forms_p.html

What is the best way to do session and application initialization in a JSP page?
Created:2000-06-10 21:58:24.822
Modified:2000-06-10 21:49:37.686
Primary contributor:Prasad Thammineni

You can initialize the session and application using the HttpSession.putValue() and ServletContext.setAttribute() methods in a JSP page. The current HttpSession (session) and ServletContext (application) objects are made available implicitely to a JSP page as "session" and "application" objects.

As a best practise you should initialize these objects as part of post-processing in your JSP page or Servlet.

How do I use the <jsp:plugin> tag to embed an applet and have multiple parameters?
Created:2000-06-10 22:05:26.183
Modified:2000-06-10 21:56:38.487
Primary contributor:Prasad Thammineni

For details on the <jsp:plugin> syntax refer to http://java.sun.com/products/jsp/tags/11/syntaxref11.fm12.html

Multiple parameters are specified using the <PARAM> tag as shown in the example below:

<jsp:plugin type="applet" code="HelloWorld"
  codebase="/samples/" height="800" width="500" jreversion="1.1"
  nspluginurl="http://java.sun.com/products/plugin/1.1.3/plugin-install.html"
  iepluginurl="http://java.sun.com/products/plugin/1.1.3/jinstall-113-win32.cab#Version=1,1,3,0">
    <params>
      <param name="author" value="prasad">
      <param name="date" value="06/10/2000">
    </params>
    <fallback>
     Sorry, cannot run java applet!!
    </fallback>
</jsp:plugin>

Where can I find an example showing a JSP taglib attribute that takes a scriptlet expression(i.e. value is not a quoted string, but a variable evaluated at run-time)?
Created:2000-06-11 17:43:52.588
Modified:2000-06-11 17:35:05.423
Primary contributor:John Millaway

In your TLD, you must set "<font color="green" >rtexprvalue</font>" to true.
  <<font color="brown" >tag</font>>
    <<font color="brown" >tagclass</font>>mypackage.EchoTag<<font color="brown" >/tagclass</font>>
    <<font color="brown" >name</font>>echo<<font color="brown" >/name</font>>
    <<font color="brown" >attribute</font>>
       <<font color="brown" >name</font>>text<<font color="brown" >/name</font>>
       <<font color="brown" >required</font>>true<<font color="brown" >/required</font>>
       <<font color="brown" >rtexprvalue</font>>true<<font color="brown" >/rtexprvalue</font>>
    <<font color="brown" >/attribute</font>>
  <<font color="brown" >/tag</font>>
I have found that the rt attribute must be a static string, or a scriptlet, not a combination of both. In other words:
<<font color="brown" >b</font>>Good morning,<<font color="brown" >b</font>>
   <<font color="brown" >echo</font> <font color="green" >text</font>="Tom" /> Good.
   <<font color="brown" >echo</font> <font color="green" >text</font>="<font color="blue" ><%= $name %></font>" />     Good.
   <<font color="brown" >echo</font> <font color="green" >text</font>="Mr. <font color="blue" ><%= $name %></font>" /> Bad.

What are some strategies for developing 24x7 applications using JSP?
Created:2000-06-11 21:10:14.328
Modified:2000-06-11 21:01:35.11
Primary contributor:Prasad Thammineni

One of the basic requirements for developing 24x7 applications is high-availability or reduced single-point of failure. The other attribute which is also considered along with high-avaliablity is scalabilty. Only high-availability will be addressed here.

Both application design and deployment architecture dictate whether an application is 24x7 or not.

Application Deployment:
All tiers of the application - web server, application server and database server, should be sized and configured appropriately in order to guarantee 24x7. The deployment architecture at each tier should feature at least 2 nodes or machines in a cluster.

Your JSP application should be deployed on a Servlet engine which supports clustering like say, IBM's WebSphere Application Server Advanced Edition. Your database server should also support deployment within a cluster - like Oracle, DB2 UDB or SQL Server. All popular Web Servers support deployment within a cluster - Apache, IIS, Netscape Enterprise Server etc.

Application Design:
The JSP features that one selects during implementation of a web application have a direct influence on the 24x7 nature of a site. Especially, HTTP session management. If Servlet sessions are being used to manage user state (like a shopping cart), the state should be made persistent in order for the state to be reconstructed in the event of a node failure. Selecting a servlet engine which supports persistent sessions would make persistent session implementation easier.

This is just the tip of the iceberg when it comes to addressing 24x7 applications. We have not yet discussed scalabilty, redundant Internet connections etc.

For an illustrated explanation of how high-availability can be implemented refer to the IBM redbook - "Servlet/JSP/EJB Design and Implementation Guide , SG24-5754-00" at http://www.redbooks.ibm.com/redpieces/abstracts/sg245754.html

Also, check out the white paper - "Achieving Scalability and High Availability for E-Commerce and Other Web Applications - Clustering the BEA WebLogic Application Server " at http://www.bea.com/products/weblogic/server/clustering.pdf

Is there any document about migrating from JSP 0.92 to 1.0?
Created:2000-06-11 21:23:10.217
Modified:2000-06-11 21:14:22.548
Primary contributor:Prasad Thammineni

Refer to the article "Migrating JSP files" at http://www.as400.ibm.com/products/websphere/docs/as400v302/docs/jspmig.html

How can I pass data retrieved from a database by a servlet to a JSP page?
Created:2000-06-12 21:50:23.09
Modified:2000-06-12 21:41:36.848
Primary contributor:Govind Seshadri

One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture as shown below:

Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:

  com.foo.dbBean bean = new com.foo.dbBean();
  //call setters to initialize bean
  req.setAttribute("dbBean", bean);
  url="..."; //relative url for display jsp page
  ServletContext sc = getServletContext();
  RequestDispatcher rd = sc.getRequestDispatcher(url);
  rd.forward(req, res);

The bean can then be accessed within the JSP page via the useBean tag as:

<jsp:useBean id="dbBean" class="com.foo.dbBean" scope="request"/>
...
<%
  //iterate through the rows within dbBean and
  //access the values using a scriptlet
%>

Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine. Of course, there may be additional design considerations to take care of - especially if your servlets are running under a clustered or fault-tolerant architecture.

How do I force JSP page references to use the HTTPS rather than HTTP protocol? It seems that using <jsp:forward .../>, for instance, prohibits me from specifying the https:// protocol explicitly in the reference (e.g., <jsp:forward page="https://..."/> is not allowed).
Created:2000-06-13 22:34:44.721
Modified:2000-06-13 22:25:57.087
Primary contributor:Edward Chaltry

This question may have two answers. Regarding the <jsp:forward.../> tag, this does not really involve HTTP at all. It simply passes control from one JSP (servlet) to another, never leaving the server. (Behind the scenes I think it is calling the RequestDispatcher.forward() method.)

As far as using HTTPS rather than HTTP for JSP references, this it typically handled by the web server being used in "front" of the servlet container your JSP is running in. If the http server has encryption enabled, all JSP (as well as HTML, images, etc) requests made to that server will be encrypted to/from the user's browser. There doesn't really need to be anything done by the JSP. The exception to this would be any absolute HTML links in the JSP file (note that relative and server-relative links are ok).

Where should my property files be placed under Windows using Tomcat 3.1 such that they can be located by my beans?
Created:2000-06-13 22:39:50.366
Modified:2000-06-13 22:31:02.721
Primary contributor:Vic Timmons

I've been having this problem a lot lately too. If you look inside of the tomcat.properties file in the /path/to/tomcat/conf/ directory,there will be a section devoted to assigning the variables wrapper.path and wrapper.classpath

I placed my properties files into a directory and then added the directory to the classpath variable. You do add directories differently depending on whether you are using UNIX or Windows. So, read the comments before those variables and you are good to go. Make sure you restart Tomcat in order for the changes to take.

How can I create a new web "application" using the JSWDK?
Created:2000-06-23 07:25:50.62
Modified:2000-06-23 07:17:03.698
Primary contributor:Prasad Thammineni

The current version of JSWDK is 2.1. This complies with JSP 1.0 and Java Servlet API 2.1 specifications.

Since the concept of a "Web Application" was introduced for the first time in Java Servlet API 2.2 specification, JSWDK 2.1 does not support creation of "Web Applications".

How do I deliver a JSP-based web app as just the precompiled .class files?
Created:2000-06-23 07:34:59.77
Modified:2000-06-23 07:26:12.425
Primary contributor:Prasad Thammineni

The Servlet Specification 2.2 introduced Web Application archive files for deploying web applications. A web application archive file or WAR file is a single file which contains all the components of a web application. For more information about WAR files refer to Servlet Specification 2.2

JSPs can be distributed as part of the WAR file, in either source or binary form. For more information on how this can be accomplished, refer to "Appendix C - Packaging JSP files" in the JSP 1.1 Specification document.

Note that the application server you select should not only comply with these specifications but should also support distribution of WAR files for web application distribution.

Currently, Tomcat and BEA's Weblogic provide compilers which can be used to precompile JSP pages into class files before deployment.

What are all my options for running JSP under Linux?
Created:2000-06-23 07:36:26.468
Modified:2000-06-23 07:27:39.12
Primary contributor:John Mitchell

Check out Resin. It's a fast, well-supported, open source servlet and JSP engine. Another open source solution is the Apache project's Tomcat server. Tomcat is the official, reference implementation for both the Java Servlets and JavaServer Pages specifications.

For commercial solutions, check out Allaire's JRun, BEA/Weblogic's Weblogic Application Server, and IBM's WebSphere Application Server.

What effect on variables does the keyword 'static' have when used in the declaration section of a JSP Page?
Created:2000-06-24 13:45:42.863
Modified:2000-06-24 13:36:55.598
Primary contributor:Prasad Thammineni

The use of 'static' keyword in the declaration section of a JSP page has the same effect as that of declaring a static variable in a Java Class. Its value is shared by all instances of the class. In this case all instances of the servlet equivalent of the JSP. Since servlets have only one instance (when not implementing the SingleThreadModel interface) that is shared among multiple web users, it is similar to declaring a non-static variable in the declaration section.

Are there any sites that maintain libraries of useful JSP taglibs?
Created:2000-06-25 07:10:48.878
Modified:2000-06-25 07:02:01.644
Primary contributor:Govind Seshadri

jsptags.com maintains an updated list of available tag libraries at http://jsptags.com/tags/

Where should I place my beans and servlets under Tomcat?
Created:2000-06-25 08:38:36.099
Modified:2000-06-25 09:27:39.047
Primary contributor:Govind Seshadri

Where you place the beans and servlets depends on which "application" it belongs to. Assuming that you are running your JSP pages under the default "examples" application, you should place your servlets under the path

/tomcat/examples/WEB-INF/classes

Your beans should be placed under

/tomcat/examples/WEB-INF/jsp/beans

Both these paths are placed within CLASSPATH by Tomcat's startup script file.

Is there a way for JavaBeans (not EJB) to communicate directly with each other, or to know what other beans are currently in scope? Is it necessary for me to use a JSP to tie two beans together?
Created:2000-06-25 08:41:34.492
Modified:2000-06-25 08:32:47.195
Primary contributor:John Zukowski

As long as the beans know about each other, they can communicate directly, without going through the JSP to tie them together. This is usually done by setting one bean to being a property of another. There isn't really a way for the bean to find out what beans are in scope. They are stored in the context of the servlet/JSP.

How can I take advantage of introspection and have a servlet process the entire form like I can using the JSP directive
<jsp:setProperty name="formHandler" property="*"/> ?

Created:2000-06-25 14:39:11.16
Modified:2000-06-25 14:30:23.972
Primary contributor:Govind Seshadri

You can make use of the HttpUtils class to gain similar introspective functionality within servlets. It may not be as elegant as the introspection feature provided by the servlet engine when using JSPs, but still, it works fine.

For example, let's assume that you've created your form as:

<form method=post action=/servlet/FooServlet>
      Value1 <input name="one">
      Value2 <input name="two">
      Value3 <input name="three">
      <input type=submit> 
</form> 

You can automagically create a Hashtable object from the parsed key-value pairs of the POSTed data within doPost() of the servlet via the following snippet:

                        
Hashtable h = HttpUtils.parsePostData(request.getContentLength(),request.getInputStream()); 
String[] one = (String[])h.get("one"); 
String[] two = (String[])h.get("two"); 
String[] three = (String[])h.get("three"); 
//print out the value of 1st input element 
pw.println("<h2>One: "+one[0]+"</h2>

"); //print out the value of 2nd input element pw.println("<h2>Two: "+two[0]+"</h2>

"); //print out the value of 3rd input element pw.println("<h2>Three: "+three[0]+"</h2>

");

Is it possible to have two JSPs with the same name, in two different directories on the server?
Created:2000-06-27 13:41:46.413
Modified:2000-06-27 13:32:59.226
Primary contributor:John Zukowski

Yes it is possible. The JSP engine names the actual servlet classes based upon the entire directory tree. Imagine something in http://www.jguru.com/jspfiles/foo/bar/one.jsp being in a package of jspfiles.foo.bar and something in http://www.jguru.com/jspfiles/foo/baz/one.jsp in a package of jspfiles.foo.baz. The entire directory path determines the internal name of the JSP-generated servlet, not just the final filename.

How do I parse custom tags in an HTML file? eg:<mytag name="aaa">xxx</mytag>
Created:2000-06-29 21:42:41.777
Modified:2000-06-29 21:33:54.709
Primary contributor:Simon Brown

Custom tags that are placed within JSP pages are parsed by the JSP container automatically, provided of course that they are setup and defined correctly.

If you have a static piece of HTML containing some common information and custom tags (e.g. a HTML header), this can be statically included in a JSP using the include directive.

For more information about custom tags, take a look at another question explaining how to create custom tags and get them working in Tomcat.