JSP - Java Server Pages


1) How do I mix JSP and SSI #include?

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

 

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

 
<%@ vinclude="data.inc" %>

The is used for including non-JSP files.

2) How do I access a database from my servlet or JSP?

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
 
public final class YourClass extends HttpServlet {
 
Connection con = null;
 
public void init() throws ServletException {
 
  String url = getServletContext().getInitParameter("url");
  String uid = getServletContext().getInitParameter("uid");
  String pwd = getServletContext().getInitParameter("pwd");
 
  try {
    //Register the JDBC driver
    Class.forName("oracle.jdbc.driver.OracleDriver");
  } catch( Exception e ) {
    e.printStackTrace();
  }//end catch
 
  //Get a connection to the database
  try {
    con = DriverManager.getConnection(url, uid, pwd);
  } catch( Exception e ) {
    e.printStackTrace();
  }//end catch
 
}//end init()
 
public void destroy() {
  try {
    //Close the connection to the database
    con.close();
  } catch( Exception e ) {
    e.printStackTrace();
  }
}
 
public void doGet(HttpServletRequest req,
                  HttpServletResponse res)
throws ServletException, IOException{
 
  try {
       [...]
       Statement st = con.createStatement();
       [ more JDBC code ]
  }
  catch (SQLException e) {
   [ ... ]
  }
}

3) How can I implement a thread-safe JSP page?

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.

4) Can a JSP page process HTML FORM data?

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

5) How does JSP handle run-time exceptions?

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.

6) What JSP lifecycle methods can I override?

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().

7) How can I override the jspInit() and jspDestroy() methods within a JSP page?

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() {
                   . . .          
   }
%>

8) How do I include static files within a JSP page?

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.

9) How do I use comments within a JSP page?

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:

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
**/
%>

10) How do I perform browser redirection from a JSP page?

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

11) How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

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-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

[Based on feedback (below), I have changed this scriptlet slightly. If the above fails, try changing the first line to

response.setHeader("Cache-Control","no-store"); //HTTP 1.1

12) Is there a way to reference the "this" variable within a JSP page?

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

13) Can a JSP page instantiate a serialized bean?

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

  type="shopping.CD" beanName="CD"  />

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.

14) How do I set a cookie within a JSP page?

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.

15) How can I delete a cookie from within a JSP page?

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

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

16) Can I stop JSP execution while in the midst of processing a request?

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;
      }
%>

17) How can I declare methods within my JSP page?

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

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

<%! 
      public String whereFrom(HttpServletRequest req) {
      HttpSession ses = req.getSession();
      ... 
      return req.getRemoteHost();
     }
%>
<%
     out.print("Hi there, I see that you are coming in from  ");
%>

<%= whereFrom(request) %>

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

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

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

Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

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


<%@ page isErrorPage="true" %>
<%
out.println("
");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println("
");
%>
 

20) How can my JSP page communicate with an EJB Session Bean?

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

21) 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?

You could make a simple wrapper function, like

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

then use it inside your JSP form, like

">

22) What is the difference between JSP and PHP?

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:

· Anything you can do with PHP, you can do with JSP; the reverse is not true

· JSP is much more powerful, since it has access to all the Java libraries. PHP only has access to PHP libraries

· JSP is Object-Oriented, so leads to cleaner code that's easier to debug, maintain, and improve. (PHP also allows objects, but the object model is more primitive, and most scripted pages ignore PHP objects and just use normal variables.)

· The equivalent syntax in JSP is just as simple to learn, so you can get up and running just as quickly -- that is, there's no extra startup cost in using Java, at least not a significant one

· Java programmers (as opposed to 15-year-old hackers or HTML monkeys) appreciate the importance of a clean language with complex OO data structures and strong typing

· With JSP, if the code inside a page gets too big, or if you want to use it elsewhere, you can cut it out, make it into a Java class, and invoke it from anywhere in your application (even not from a page). With PHP, you're stuck inside the HTML box.

· JSP's concept of state management and persistence is more explicit and powerful than PHP's. With JSP, you can specify whether a variable persists for the page, the request, the session, or the application (or if it's just local to the function). The JSP engine automatically does the right thing with cookies so you have access to the variable on later requests. With PHP, you just have "global" and "not global", you don't have automatic session management, and have to do your state thing manually with cookies or hidden variables.

23) Are there any IDE's which will help me debug JSPs?

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.

24) Can I call a JSP, then have it return control to the original JSP, like a subroutine or method call?

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

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 sense 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:

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.

25) What are the disadvantages of JSP?

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.

  1. There are numerous syntax related issues with JSP programming.

26) Can a JSP call itself recursively?

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.

27) How can I use JSP to make sure a user has logged in before I handle the request?

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

28) How can I write to a text file from a JSP page?


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.

29) How can I customize the HTML generated by my JSP file based upon what browser the user is using?

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

30) How do I setup a cookie to expire after a certain time?

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

· A positive value is the maximum number of seconds the cookie will live, before it expires

· A negative value means the cookie will not be stored beyond this browser session (deleted on browser close)

· Zero means to delete the cookie

31) What are the advantages of using beanName in the jsp:useBean syntax?

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.

32) When we use , 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?

The only way you can cause the browser to update the new URL in its location area is to use

response.sendRedirect("newURL")
 

33) How can I convert my 0.9 JSP files to 1.1?

JSP 0.9

JSP 1.1

<%@ 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.*,
"%>

<%!
interface Verbosity {
        final int TERSE = 1;
        final int NORMAL = 2;
        final int VERBOSE = 3;
}
%>

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

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

35) What are all the implicit objects available within a JSP page?

The eight implicit variables available within JSP pages are:

· request: This represents the request triggering the service invocation and encapsulates the HttpRequest object; has request scope.

· response: Represents the response to the request and encapsulates the HttpResponse object. Not used often by page authors; has page scope.

· pagecontext: Encapsulates implementation-dependent features as a PageContext; has page scope.

· application: Represents the ServletContext obtained from servlet configuration object; has application scope.

· out: This is an instance of JspWriter that writes into the output stream; has page scope.

· config: Represents the ServletConfig object for the JSP; has page scope.

· page: This acts as a synonym for the “this” operator. Not used often by page authors and has page scope. exception: This represents the uncaught Throwable object that resulted in the error page being invoked. By default, has page scope.

36) How can I refresh the page my browser is showing with JSP?

<META HTTP-EQUIV="Refresh" CONTENT="3">
<% 
   int i=0;
   String ii = (String) session.getValue("count");
      if (ii!=null) { 
                   i = Integer.parseInt(ii);
                   out.println("

Counter is: "+i+"

" );

         i++;
   }
      session.putValue("count",new Integer(i).toString());
%>

37) Can a JSP be multi-threaded?

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.

38) How does the "session" scope work with the useBean tag? What is the difference between "session" and "application" for the useBean tag?

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.

39) How do I get a JSP page to implement a Java interface?

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.

40) What is the recommended, "best" architecture for JSP applications?

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

41) 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?

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.

<%             
for (x = 0;  x <>
%>
   " 
          value="<%= session.fooData.getValue(x) %>">
<% } %>

42) 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?

[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.

43) 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?

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.

44) What is the difference between ServletContext and PageContext?

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.

45) 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 ?

Yes...if you are using the 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.

46) How can I protect my JSP pages (or servlets) against the user's using the browser's back arrow and losing the session?

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

47) Is there any difference between the attributes class=com.myco.MyClass and the beanName=com.myco.MyClass attributes in the tag?

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.

48) What does the attribute flush=true in mean? Where is it essential to use?

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

49) What is the best way to do session and application initialization in a JSP page?

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.

50) How do I include a link to an external style sheet from JSP?

You would include the link the same way you would for a static HTML page:

where

/site_style.css

is located at the root of your web server.

51) Is there any way to convert "Post" request to "Get" request dynamically in case of JSP, as there is only service method?

According to the JSP 1.1 spec when a JSP gets compiled it will generate the _jspService() method to handle the request. There is no mechanism available to provide your own _jspService() method, although you can specify the class the generated servlet class needs to extend. When you specify a base class using the <% page extends %> directive you need to comply by some rules. One of them being, the service() method of your base class should call the _jspService() method.

Refer to section 3.2 of the JSP 1.1 specificaition for a detailed example.

Lastly, if you decide not to use your own base class, the generated _jspService() method will handle both GET and POST methods. What I mean is that if you have a JSP page, you can request it from the address bar(GET) or post to it from a FORM. As long as you use the HttpServletRequest.getParameter(s)() methods you can get access to the parameters.

52) How do I pass values from a list box (with multiple selects) to a Java Bean?

Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox:

 
What's your favorite movie?



  value="2001: A Space Odyssey">
  2001: A Space Odyssey



  value="The Waterboy">
  The Waterboy



  value="The Tin Drum">
  The Tin Drum



  value="Being John Malkovich">
  Being John Malkovich



 

To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies:

 
package foo;
public class MovieBean {
    private String[] movies;
    public MovieBean() {
     String movies[] = new String[0];
    }
    public String[] getMovies() {
       return movies;
    }
    public void setMovies(String[] m) {
     this.movies = m;
    }   
}
 

Although a good design pattern would be to have the names of the bean properties match those of the HTML input form elements, it need not always be the case, as indicated within this example. The JSP code to process the posted form data is as follows:

 
 
 
<%! String[] movies; %>
 
  
    property="movies" 
    param="faveMovies" />
 
<%   movies = movieBean.getMovies();
   if (movies != null) {
      out.println("You selected: 
");
      out.println("
    ");
      for (int i = 0; i <>
        out.println ("
  • "+movies[i]+"
  • ");
          }
          out.println("");
        } else 
          out.println ("Don't you watch any movies?!");
    %>
     

    53) What is the best way to send parameters to servlets when using the jsp:include statement to embed the servlet output inside of a JSP page?

    The best way to send parameters using the action is with the tag. This would look something like:

        

    Now, the included servlet can access these parameters the same way it accesses all other parameters: getParameter(String name).

    54) Can I create an inner class within my JSP file? If yes, can it be dynamically reloaded when changed like the rest of the JSP?

    Yes, you can declare inner classes within your JSP pages using declarations. The inner classes are also dynamically reloaded by your servlet engine's classloader if they change.

    Consider the following example:

    <%!
      class Herge {
       private String haddockSays="";
       public Herge() {
           haddockSays="Billions of blistering Bashi-bazouks!";
       }
       public String getHaddockSays() {
          return haddockSays;
       }
      }
    %>

    <%

    Herge captain = new Herge();

    %>

    <%= captain.getHaddockSays() %>

    After the page has been compiled, if you decide to have Cap'n Haddock swear something else, the inner class Herge will be reloaded, and the JSP page will be recompiled.

    54) What are custom tags useful for ?

    Lots of things :)

    One of the interesting uses for custom tags is empowering web site designers who don't know Java (poor things). A simple custom tag can be used to change 'complex' code like:

    Current Date is: <%=new Date()%>
    to
    Current Date is:

    Even though the reduction in complexity is small (some might say none) the use of a tag encapsulates the code, so more sophisticated stuff can be implemented later without changes in the JSP. Internationalised dates, graphical animating dates, etc.

    More complex code can include iteration over collections:

      

    database access:

      
     
    (With some coding effort the tags can be made similar)

    One can say that just about any Java code can be put into a custom tag although this soon hits a brick wall as custom tags require more coding than simple 'script like' Java.

    See: Which is better, Custom tags or JavaBeans ?

    There are some applications of custom tags that have no alternative in JSP. One such application is post-processing of JSP generated output. Say we had an page that needed to contain a word count, this couldn't be implemented in JSP because once some text has been put into the JSPWriter you can't access it anymore. It is possible when using custom tags in the following way:

        Blah blah blah ($WordCount$ Words)

    then in the code for getwordcount:

    public class WordCountTag extends BodyTagSupport
    {
      private String m_placeholder;
     
      public int doStartTag() throws JspTagException
      {
        return EVAL_BODY_TAG;
      }
     
      public int doAfterBody() throws JspTagException
      {
        try {
          if (bodyContent != null) {
            String text = bodyContent.getString();
            int wordCount = calculateWordCount(text);
            String newText = replacePlaceholder(text, wordCount);
            bodyContent.getEnclosingWriter().print(newText);
          }
        } catch (IOException ie) {}
     
        return EVAL_PAGE;
      }
     
      public int doEndTag() throws JspTagException
      {
        return EVAL_PAGE;
      }
     
      private int calculateWordCount(String text)
      {
        //...
      }
     
      private String replacePlaceholder(String input,
          int wordCount)
      {
        //...
      }
    }

    The great thing about using custom tags for post processing is that it requires minimal or no changes to the JSP, if you were implementing last minute changes to Wahoo! to ensure that the text 'Cost = 0$' never appears it would be trivial to do so:

      rest of web page

    Or even better:

      rest of web page
     
    ...
     
    someExternalResource:
    com.wahoo.jsp.processing.NoSwearing
    com.wahoo.jsp.processing.NoFreebies
     

    A bad thing about custom tags is that they don't seem to have an equal footing to standard jsp tags, so you can't have a tag within a custom tag (custom tags cannot call out.flush, and jsp:include requires flush="true"), but hopefully this will change with JSP 1.2

    55) What is the exact difference between request.getRequestURI() and request.getServletPath()?

    request.getRequestURI() contains the context path defined in your server.xml, on the other hand, request.getServletPath() does not contain this path.

    For example, in your server.xml, you define:

    ;

    under the directory d:\work\mywebapp, you have sub directory WEB-INF and jsps, under the directory d:\work\mywebapp\jsps, you save your jsp file, say mytest.jsp. So when you use request.getRequestURI(), the result will be: /mywebapp/jsps/mytest.jsp, the other result using request.getServletPath() will be /jsps/mytest.jsp.

    56) Is there a way to set up the unlimited buffering for a JSP page?

    No. You can either disable the buffer mode or set the maximum size of the buffer. But you cannot set the size to unlimited.
    To disable the buffer use
    <%@ page buffer="none"%>
    To set the size to a specified size say 20kb use
    <%@page buffer="20kb"%>

    The default size is 8kb, which is sufficient in most cases.

    57) What is the difference between response.sendRedirect(), RequestDispatcher.forward(), and PageContext.forward()?

    In a nutshell, RequestDispatcher.forward() works on the server and response.sendRedirect() works on the browser. When you invoke RequestDispatcher.forward(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file. When you invoke response.sendRedirect(), this sends an HTTP response to the browser to make another request at a different URL.

    RequestDispatcher.forward() and PageContext.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method.

    58) Is there any way to get the Last Modified date of a JSP source file from that file? I want my JSP to have a display of the last modification automatically.

    There's nothing in the JSP spec (unfortunately) to get the last modified date, but you can use the servlet context object and the File API to get it.

    <%@ page import="java.io.*,java.util.*" %>
    <%
    String filename = application.getRealPath(request.getRequestURI());
    File file = new File(filename);
    %>
    <%=new Date(file.lastModified())%>

    59) What is the most elegant approach to inform a user that his session has timed out?

    I think best way is to tell them just that - your session has expired. Maybe not in that technical of a manner, but let them know that because of the dynamic nature of your application, information expires over an extended period of time. Then, recover as much state as you can and redirect them to a page where they can start their process over again.

    60) What's the difference between the class and type attributes in the tag.

    The "class" attribute specifies the actual implementaion class for this bean.

    "type" (if specified), specifies the superClass or the interface this class implements. If this is not defined, by default the type is same as the implementation class itself. This could be useful for typecasting of the object in the jsp page.

    61) Why am I getting the error "Attempt to clear a buffer that is already been flushed"?

    This is related to the buffer overflow error. To solve this error, you can just set the page directive parameter autoflush to true or increase the buffer size by setting the buffer parameter.

    By default the buffer size is 8K, and all the HTML output is stored in this buffer before JSPWriter flushes it to the output. If the content size exceeds this default size, then there will be an exception, like the one you are getting.

    If the value of "autoflush" parameter is true, then whenever the buffer is full then the contents of this buffer will be automatically flushed.

    62) What are the multithreading and clustering issues when it comes to using beans with jsp's in differrent scopes?

    With respective to multithreading, beans that are created with a request or page scope are new instances for each JSP call so these beans need not be thread safe. Beans that are created with a session or application scope must be thread safe as multiple pages could be accessing the same bean at once. In either case, if beans are accessing shared resources (like pooling connections behind the scene), you must make sure this sharing is thread-safe

    Clustering has similar issues as multithreading. Again, request and page scope beans are generally fine as they're created with each page request, but session and application will be shared instances. The clustering package you are using will often give you the ability to use the same session or application object across clustered servers, and this is either handled by keeping the objects in a shared ATOMic location (like a database) or each clustered server accessing the single instance of the objects via RMI.

    63) How can I pass parameters dynamically to an applet from within a JSP page?

    You can pass parameters to applets by using tags in between your tag. Here is some sample code:

    " >

    64) Can a JSP page be "spidered" and indexed by a search engine?

    It can, usually. Anything that can be called and is not excluded is available for spiders. Whether the results of the call are usefull is something else. If the JSP needs information that is passed as parameters or in a cookie, the spider will usually have no clue about what to do with it (and thus might well get an HTTP 500 error as the only output).

    65) How does session management work internally within the servlet engine?

    This very much depends on the servlet engine. Sometimes sessions are stored only in memory, in a HashSet of session IDs and the HttpSession. Some servlet engines support serializing session information to a file system or database, which allows the servlet engine to restart without losing session information, and to allow a cluster of web servers to use the same pool of sessions. Each servlet engine should provide details of the features of their session management. If you want to look at actual implementations, there are numerous open source projects including Tomcat (http://jakarta.apache.org/), Apache JServ (http://java.apache.org/), and others.

    66) Is it possible to publish the output of a JSP page to a static HTML file?

    1. You can access the JSP page programatically using a URLConnection, by simulating a browser connection.

    URL url = new URL("http://www.jguru.com/");
    URLConnection con = url.openConnection();
    InputStream in = con.getInputStream();
    OutputStream out = new FileOutputStream("mypage.html");
     
    int c = -1;
    while((c = in.read()) != -1) {
        out.write(c);
    }


    2. A much more involved approach is to use a wrapper around ServletResponse, similar to the class
    javax.servlet.ServletResponseWrapper in the Servlet 2.3 API (Tomcat 4.0). Then you can override the getOutputStream() and getWriter() methods to provide your own stream.

    MyServletResponseWrapper wrapper = new MyServletResponseWrapper(servletResponse);
    RequestDispatcher disp = getServletContext().getRequestDispatcher("/pages/mypage.jsp");
    disp.forward(servletRequest, wrapper);


    By extending the wrapper concept to provide your own ServletOutputStream, you could simultaneously provide the JSP output to both the client (browser) and to your own stream.

    67) I would like to learn a technique to keep track the number of login attempts by a user using session variables. If the user exceed the maximum login attempts, then the account is suspended.

    This is pretty easy to accomplish by simply storing an Integer object in the HttpSession object. Here's some sample code for the login processing code...

    <%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    if (loginValid(username, password)) {
      //Continue with a successful login
     
      return;
    } else {
      //Check whether we've exceed the count and possibly update
      Integer counter = (Integer)session.getAttribute("invalid_login_counter");
      if (counter == null) {
        counter = new Integer(1);
      } else if (counter.intValue() > 3) {
        //Block the account
        return;
      } else {
        counter = new Integer(counter.intValue() + 1);
      }
      session.setAttribute("invalid_login_counter", counter);
    }
    %>

    68) Can I remove a bean from a session in JSP when the bean was set up using the tag?

    Yes. basically translates into:

    <%
    MyBean bean = (MyBean)session.getAttribute("bean");
    if (bean == null) {
    bean = new MyBean();
    session.setAttribute("bean",bean); }
    %>

    So, you can remove it using the same sort of semantics:

    <%
    session.removeAttribute("bean");
    %>

    69) Is there anything which a servlet can perform but a JSP cannot and vice versa ?

    A JSP is generated into a servlet, so there is very little that one can do, but not the other. JSPs are generally considered a "convenient" way to write servlets. However, there are the following differences:

    • JSP cannot return binary data. This is because a JSP always calls response.getWriter(), and returns a JspWriter.
    • Servlets cannot readily use JSP Tags. This is somewhat obviously, but custom tags can sometime include business logic or other functionality that a page developer would want to call. It technically is possible for a servlet to call a custom tag, but it is lengthy process.

    70) Are there any standards for developing JSP pages? All I can find are Java coding standards, which does not help me much when it comes to JSP programming.
    JSP Architectures:

    Model I: This kind of architecture is useful when everybody on your team are able to write Java code as well as HTML code.You can have Java code generate/fetch the dynamic content and have HTML display them from within the same JSP page. This is a simple technique, but you may lose code readability and these pages may also be difficult to debug.

    Model II: Here, you have a servlet or JSP to generate/fetch the dynamic content and a separate JSP to display it. This way, the controller Servlet/JSP can forward the contents to the appropriate display JSP. This technique, commonly known as the Model/View/Controller (MVC) pattern, allows an effective separation of presentation from content.

    71) How do I eliminate the spaces in the query string in a servlet /jsp combo like I would replace them with %20 ?

    Use the java.net.URLEncoder.encode() method as follows:

    String temp1 = request.getParameter("something");
    temp1=java.net.URLEncoder.encode(temp1);

    The temp1 string will have it's spaces replaced with %20.

    Please note that all other special characters will be URLEncoded as well.

    72) In a web application is Hashtable access faster or better than database access? Some developers I work with are arguing that the hashtables are faster when compared to getting data directly from the database. The size of the database is 3mb right now. If the hashtables do give a faster access time, is there any reason we should or shouldn't use them?

    Hashtable (or Maps) is faster than a database access. Sometimes it's better to use hastable instead of db, sometimes not: it depends on what you have to do with the data.

    Hashtable (and Maps) is faster than a database because the data are already loaded in memory, and generally in a way to get it as faster as possible (hash functions etc.). When getting data from the db, commonly you are passing thru a network connection, then to a file system, and at last to (flat)memory.

    Disadvantages of maps are that them charge lot of memory (more than just data size): you cannot use map with huge structures if you don't want to keep it all in memory.
    Databases let you to keep in memory only a subset of the entire application data. Furthermore, Hashtables (and Maps) don't provide a persistent storage: when you turn off the machine all the data are lost!

    Hashtable are not transactional, Hashtable are not relational, don't provide any data-constraints... in short, Hashtables and Maps are different from databases.
    For keeping temporary data in an application and for keeping fast access data, Maps (and Hashtables) are the right choice.
    For keeping businness/persistent/structured data, databases are right!

    Maps are right for keep application configuration (Properties), for keeping little tables (like a subset cities, states, etc.) that are used very frequently and changed rarely. And so on...

    73) What is the difference between the server side include (SSI) and JSP include?

    Theoretically they are very similar. The purpose of both is to include a page or a document inside the actual page, before sending the page back to the client. Both works on the server. Said so, the obvious difference is the technology behind the two different solutions.
    The basic SSI implementation (that is normally part of a web server) it's definitely less powerful of a jsp include. The SSI has only access to the same request object of the page that contains it, while with jsp include you can use the same request or even add more information.

    74) Assume that the web server creates a new session for a user, and later, the user does not "log out", but rather just closes the browser. How can the web server determine that this session is no longer active and prevent it from consuming valuable server resources?


    There is no "standard" way to have a count of all the "active" sessions in a servet container. You have top maintain your own, maybe using a map that stores the session when the user logs in and remove it when the user logs out.

    If the user doesn't log out properly, you can check if the session is still valid based on computing the time difference between the default timeout interval (HttpSession.getMaxInactiveInterval()) and the last activity performed by the user (HttpSession.getLastAccessedTime()).

    75) How can I access JSP variables from a JavaScript function in a JSP page?


    Essentially, you can't. The JSP variable doesn't exist when the JavaScript is running as JSP runs in the server and JavaScript runs in the browser. Some servers though support server-side JavaScript. Read the FAQ for pointers on those.

    Perhaps there is some way to do this.
    1. If you only want to use the variable value once , you can embed the jsp tag inside your JavaScript segment such as:


    76) I have a field defined as a Text field. The field contains line breaks in it. I am printing this field to the screen and would like to replace the line breaks with HTML BR tags. Could someone help me with the code for this?

    public String replaceString(String str, String sep, String rep) {
    StringBuffer retVal = new StringBuffer();
    int idx = 0;
    int jdx = str.indexOf(sep);
    while (jdx >= 0) {
    retVal.append(str.substring(idx, jdx));
    retVal.append(rep);
    idx = jdx + sep.length();
    jdx = str.indexOf(sep, idx);
    }
    retVal.append(str.substring(idx));
    return retVal.toString();
    }

    When you call it you can do something like:

    String changed = replaceString(original, "original_string", "replace_string");

    77) Can you tell me how to validate credit card numbers using JSP?

    Two points:

    • A JSP should not do this sort of validation. The JSP should handle presentation only; business logic (such as credit card validation) should be in separate classes, for example, in EJB. While no one can stop you from mixing presentation and business logic, doing so will give you confusing and difficult-to-maintain code.
    • Validation of credit cards involves multiple steps. The first is checking to see that the credit card number is allowed under card numbering rules (e.g., MasterCard numbers start with the numeral "5"); the second step requires connecting to a processor (e.g., CyberCash) who will connect to cardholder banks to determine that (a) the card exists and is active, and (b) that there are sufficient funds available for the purchase. The processor may also perform some fraud checks. Given the complexity of card processing and your limited experience in this area, I would suggest that you look for a commercial service to connect with.

    78) How can I get details regarding a browser (make, version, platform, etc.) from within a JSP page?

    You can retrieve any HTTP header information (including User-Agent) through the request object. The following scriptlet should return browser information:

    <%=request.getHeader("User-Agent") %>

    79) How do I restrict an user from exceeding data of a particular length in a TEXTAREA like we do with a text box using the maxlength attribute?

    The text area doesn't have an attribute like maxlength, so there are two ways to check this: a client side and a server side.

    The first one (client side check) has to be written with a language like JavaScript. It's a simple check that doesn't allow to submit the form if the size of the field is greater than your max.

    The second solution (server side) is written in the language you're using (probably java) and it does the same thing, but after the form has been submitted.

    Good programming practice should suggest you to do both. This will avoid an invalid submission (save time and resources) and because if the client doesn't have JavaScript (rare situation) or has Javascript disabled (it happens often), it will work anyway.

    80) Inside a JSP, how to represent private methods and call them?


    Use a declaration scriptlet:

     
    <%!
        private void foo() {
            System.out.println("foo");
        }
    %>
     
    <%
      foo();
    %>

    81) What is Struts? What is Struts?

    Struts is an open source framework from Apache for developing JSP-based web applications using the Model-View-Controller (MVC) [Model 2] architecture.

    82) What is Ant? Do I need it to run Tomcat?

    ANT is a Java build tool. As they say in the website it is kind of like make without make's wrinkles. I strongly suggest you to take a look at the site if you're interested in knowing more about it.

    The short answer is no, you don't need to download ANT in order to run Tomcat Servlet COntainer.

    The long answer is "depends". If you download the binary version of Tomcat, than you don't need ANT. But if you prefer to download the source code, and you want to compile it by yourself, you need ANT.

    83) Can I submit multiple forms, say form1 and form2, to a JSP page by clicking a single submit button?

    The simple answer is, combine the forms. This is the simplest solution to your problem. Basically, it is not possible to do what you are trying to do. By submitting form1 you are sending a request to the server. By submitting form2 you are also sending a request to the server. Both request need a response, but how is the server to know that it should combine responses? You could use frames and simultaneously post multiple forms from different framesets, with each response going into the appropriate frame using some Javascript magic. However, I highly recommend that if your forms need to work together (as is obviously the case here, since you are sending them at the same time) combine them into a single one.

    84) How can I prevent user from viewing a page that he already passed. i.e I have a form that contains some textboxes to fill some info..after submited the form it will redirect to another page. I need to prevent user to view the page again by pressing back botton.

    We can accomplish this with using both jsp and JavaScript.
    form.jsp:
    <%response.setHeader("Cache-Control","no-cache");%>
    <%response.setHeader("expires","0");%>
    <%response.setHeader("Pragma","no-cache");%>


    <% session.putValue("prevpage","confirm");//reset the variable %>

    result.jsp:
    Set the prevpage variable in this page.
    <% session.putValue("prevpage","result.jsp"); %>

    When first time form.jsp loads, it will check for the prevpage variable. Since the prevpage is not set it displays the form.jsp page. Then we submit this page to result.jsp
    If we hit back button from result.jsp, we will be redirected to redirectpage.jsp.

    85) Why do I get the error "IllegalStateException" when using the RequestDispatcher?
    When you use RequestDispatcher.forward or RequestDispatcher.include to call another servlet, you must pay very close attention to a fairly tricky detail of the servlet "chain of command."

    When a servlet is first called, the response object is fresh and new: its headers have not been set, its buffers are empty, and no data has been written to the client.

    However, as soon as either the status code or any of the headers have been written -- or potentially written -- to the client, or when data has been -- or may have been -- written to the body stream, then you may be susceptible to the IllegalStateException error. The problem that this exception is signalling is the new data that you are (or may be) writing is inconsistent with the data that's already been set and then irretrivably sent ("committed") to the client.

    Two common variants of this exception are "java.lang.IllegalStateException: Header already sent" and "java.lang.IllegalStateException: Cannot forward as Output Stream or Writer has already been obtained".

    "Header already sent" means that one or more headers have been committed to the client, so you can't set that header again.

    "Output Stream or Writer has already been obtained" means that since the calling servlet has already called response.getWriter() or response.getOutputStream(), that contaminates the data stream, since the response has been (or may have been) written to already, making it unsuitable for forwarding.

    (Some would argue that the exception is overkill; that the Servlet API should just silently log the problem, then continue as best it can, e.g. by simply not writing the new headers or status code or body text. However, the API as it stands is less forgiving, and it throws a hard exception.)

    A further complication is "side effects", where methods set the "committed" flag unnecessarily, or at least unexpectedly. For instance, calling response.flushBuffer() sets the "committed" flag (even if the buffer is empty). Furthermore, calling RequestDispatcher.include() calls response.flushBuffer() (even if the "included" servlet doesn't actually write any data to the response). That means that you shouldn't ever call include() before calling forward().

    This is due to the semantics of RequestDispatcher.forward() -- it's intended to be called only by servlets that do literally nothing to the response before forwarding (since the "forwardee" is supposed to be the master servlet). Unfortunately, this means that you can't do things that you might naturally expect, like forwarding from one servlet or JSP to another, where each one adds a little bit of data to the response. Also unfortunately, there are some scenarios where you *can* do exactly that, so when you encounter a scenario where the exception is thrown, it seems to come from out of the blue.

    What this all means is that the Servlet API is inadequate as a general framework for sending messages among active objects to form a data pipeline. Fortunately, you have an API that is perfectly adequate for that task: Java itself. Structure your application to use JavaBeans and Java method calls. Restrict your Servlets to two types: one type is all data-processing, and the other type is all response-writing.

    If you want your response-writers to be modular (one object to build the nav bar, one object to build the banner ad, one object to build the body, one object to build the page footer, etc.), you have two choices:

    1. use JavaBeans or Java method calls to build up the HTML in the response, or
    2. use RequestDispatcher.include() to bring in content from many little servlets from inside a master response-builder servlet.

    RequestDispatcher.include() is probably a safer method than RequestDispatcher.forward() for other reasons, since it leaves the request parameters alone (forward() changes the path etc. to be relative to the target servlet, not the original servlet).

    You may also look into Servlet 2.3 Filters as an alternative way to string page content together from multiple resources (though it too is quite complicated and ambiguous at times).

    86) From a JSP page or servlet, how may I know the root context of the current web application ? I need to know this to specify the correct href even if the context may change when my app is deployed in the production environment.


    /index.jsp">

    87) What is the difference between using getSession(true) and getSession(false) methods?

    The difference is as follows:

    When you say getSession(true), this method will check whether already a session is existing for the user. If a session is existing, it will return that session object, OTHERWISE WILL CREATE A SESSION OBJECT EXPLICITLY AND RETURN TO THE CLIENT.

    When you say getSession(false), this method will check whether a session is existing. If yes, then it returns the reference of that session object, OTHERWISE IT WILL RETURN 'null'.

    88) What are the differences between JSP 1.1 and JSP 1.2?

    Released September 17th 2001, the JSP 1.2 specification is now ready for public consumption. It contains everything from brand new features to corrections and clarifications of areas that were not quite right in the previous version. The most important changes:

     * JSP 1.2 is based on Servlet 2.3 and Java 2. 
     * The include action can now be used without flushing. 
     * The XML syntax for a JSP page has been finalized. 
     * Tag libraries can make use of Servlet 2.3 event listeners. 
     * A new type of page validator has been added. 
     * New options for tag library distribution and deployment have been added. 
     * Two new tag interfaces have been added. 
     * The conversion rules for String literal tag attribute values now include conversion to the Object type. 
     * A PropertyEditor can be used for custom attribute value conversion. 
     * The tag handler lifecycle has been clarified. 
     * The Tag Library Descriptor has been aligned with other J2EE descriptors and extended with new elements. 

    89) How can I distinguish b/w 2 buttons which are submitting the same form from within my JSP page? I'd like to solve this problem without using JavaScript.

    You can give the buttons names:

    .
    .
    .
     

    Now, when the form submits, you can check to see if "ok".equals(request.getParameter("ok")). I think you can also give the buttons the same name, and just check the value to see which one was clicked.

    If you want to use images for your submit buttons, you'll have to check the ok.x and ok.y variables, since a submit for an image button doesn't return a value for ok, but the X and Y coordinates that you clicked when submitting.

    90) How can I make a JSP page implement the SingleThreadedModel interface?

    You have to add isThreadSafe="false" to your page directive as following:

     
    <%@ page isThreadSafe="false" %> 
     

    By default isThreadSafe is set to true, that means that there is no problem accessing to the JSP concurrently.

    91) How can I find out the name of the machine on which the JSP is executing?

    You can use request.getServerName() for this purpose.

    92) I am aware of the technical differences between response.sendRedirect() and i.e. that the first one sends an instruction to the browser to request the specified page, and the second simply sends the specified page.

    Generally I use forward when I'm sending a page that is within the same site i am sending from, ie you are on index.jsp and sending them to the signup.jsp or whatever.

    I use sendRedirect() when I'm pushing them out to an outside link, ie you are you yoursite.com/index.jsp and are sending them to yahoo.com.

    93) Is it possible to press a button in one frame and caused a form in another frame to be submitted?

    I have a scrollable jsp in one frame and another frame with just buttons. I want to be able to press a button and sumbit a form from the jsp page. Thanks for any replies.

    in frame 2 use

    function frame2()
    {
    parent.frames.frame1.document.form1.submit();
    }

    94) Is the HTTP Session maintained even when the network connection goes down? Can the same browser instance resume a previous session after re-establishing the network connection?

    In the Servlets API, HttpSessions are implemented as objects in memory on the web app server. Therefore, the session will be maintained on ther server as long as the server is running (or until it "times out" after the max inactive interval has passed). Even if the server "goes offline" and then "goes online," the session will be maintained if the web app server process is still running (and the session has not timed out).

    Session cookies are sent to the browser to allow the browser to identify itself to the server, thereby allowing the server to "look up" the user's session. The session cookies are deleted when the browser process exits, so if the user "goes offline" and then "goes online" and makes a request, the session cookie will still be available--assuming the same browser process. However, even if the cookie is available and sent to the server, if the session has timed out, the session is not available (the user would get a new session with a call to request.getSession()).

    Note that different browsers maintain session cookies across multiple browser windows in different ways. See

    95) How can I optimize my JSP pages for better search engine placement?

    Google will spider and index JSP(read dynamic page). However, because their web crawler can easily overwhelm and crash sites serving dynamic content, they limit the amount of dynamic pages they index. And not all search engines will index the dynamic urls. The more parameter you have in your query string the less like you will get spidered. Make sure that your URLs are not too long and they do not contain special characters (?,&,@). Many search engines will ignore and URLs that contain ? and &. If you are generating content from a database, code so that the database produces static .html pages, perhaps every 24 hours or so. Don't rely on JavaScript for navigation. It helps to keep the parameters short and the number of them small. Also the change the way the URL is generated. Make sure that your keywords, metatags, title and alt tags are descriptive and accurate. Hope it follows right track

    No comments: