World class data recovery software and renowned raid recovery services

WestNIC provides reliable web hosting services

Ahosting.biz reseller hosting, managed dedicated server with 24/7 support

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Use the help request form below if your question is not answered here, but make sure you are asking the right question first.

Subscribe to this FAQ: RSS news feed

FAQ search

JSP concepts

Q: What's the difference between JSP and servlets?

A: Ultimately, servlets and JSP are the same thing. When you deploy JSP documents, the servlet container generates Java source code from the text and tags, then compiles the source to create servlet classes. The JSP servlet classes are then used to service requests the same way as standard servlets.

The key difference is the way the way the servlet source is created; as a standard Java source file, or a template that is essentially an HTML document with JSP tags.

Q: Which is best, servlets or JSP?

A: Servlets tend to be better at providing validation for HTTP requests, interpreting the request parameters and directing the outcome of the interaction. JSP are a good way of providing fairly static, template-style character output for Web applications that include some programming logic.

Premium Content: Follow this link for subscription information More details available to subscribers:
Which is best, servlets or JSP?

Q: Which is faster, servlets or JSP?

A: JSP documents are compiled into servlets before the servlet container uses them to respond to a request. Once JSP has been compiled, they should be equally fast as standard servlets. The JSP compilation phase introduces a small delay for the first request, but all following requests are handled by the same pre-compiled servlet.

Q: Does JSP support multi-threading?

A: JSP documents are ultimately compiled to servlets, which are multi-threaded by default and are assumed to be thread-safe. If the code in your JSP is not thread-safe, you can request the container uses a single threaded execution of the resulting servlet using the page directive <%@ page isThreadSafe="false" %>.

In this case the container may create multiple instances of the JSP servlet to handle concurrent requests or use synchronization to control access to a single instance. Both approaches are likely to reduce the performance of the page because of the overheads of instantiation and locking respectively, so this directive should be used with caution.

Q: How many objects exist when a JSP has concurrent requests?

A: JSP documents are compiled to servlets when they are placed in service and operate like standard servlets. Usually a single JSP servlet instance is used to serve any number of virtually simultaneous requests, so only one servlet object exists. Where your servlet is composed of several other objects, the single servlet instantiates a single set of supporting objects.

If your JSP servlet declares the page directive isThreadSafe="false", the servlet container may create a pool of instances to handle concurrent requests independently. In this case, the number of supporting objects would be multiplied accordingly.

JSP techniques

Q: How can I display an image in a JSP document?

A: There is no special Java coding required to display an image in a JSP document, you only need to use standard HTML markup for the image and place the image in a suitable place in the Web application directory. The servlet container should serve static content, such as images, HTML documents, Cascading Style Sheets and Javascript files, without any special configuration.

Q: How can I get the system date in JSP?

A: The technique for displaying the current date in JSP is similar to the way it is done in a standard Java application. First you must import the relevant classes and prepare a date syntax to use for the display. The example below shows how to import and use Date and SimpleDateFormat classes to format the current date by setting a couple of page variables, then outputs the text through a simple JSP script element.

Premium Content: Follow this link for subscription information More details available to subscribers:
How can I get the system date in JSP?

Q: How should I debug JSP?

A: As far as possible you should avoid debugging JSP by keeping script elements as simple as possible and use tag libraries for more complex processing. Ideally, JSP should be written so that non-programmers can write and edit the contents, so should not contain complex programming structures that are prone to bugs. Tag libraries move complex program components to standard Java classes, which can be tested and debugged outside of the servlet container.

Premium Content: Follow this link for subscription information More details available to subscribers:
How should I debug JSP?

Q: How can I control page output for admins?

A: One approach to govern user levels with JSP pages is to assign a user object reference to each person's session. The simple example below declares a User interface with concrete StandardUser and AdminUser classes. The User interface only has one method, a boolean isAdmin() method that you can check before outputting key page contents.

Premium Content: Follow this link for subscription information More details available to subscribers:
How can I control page output for admins?

Q: Can I assign a Javascript variable to a JSP variable?

A: It is not possible to directly assign client side Javascript variables to JSP variables because the Java assignment is created when the JSP document is compiled into a servlet, before the output is served to the client. Javascript variables are created on the client side when a Web browser interprets a script.

One way to pass Javascript values to JSP variables is to include them as query parameters for a JSP document. The JSP document can then get the values via the request.getParameterValues(String) method. When you pass Javascript variables in query parameters it is important to pass the value through the escape(String) method, as below.

Premium Content: Follow this link for subscription information More details available to subscribers:
Can I assign a Javascript variable to a JSP variable?

Q: What is precompilation of JSP?

A: Normally, the first time a JSP URL is requested, the servlet container generates Java source code to produce a servlet for the JSP, then compiles and deploys it. As you can imagine, this creates a small but significant delay for the first request. All following requests are handled directly by the new servlet. JSP servlets can be pre-compiled to reduce the lag and check there are no compilation errors before they go into service.

Premium Content: Follow this link for subscription information More details available to subscribers:
What is precompilation of JSP?

Java Server Pages API

Q: Can I forward multiple requests to a single JSP?

A: It is certainly possible to forward any number of JSP requests to a single JSP document. Normally, forwarding is handled by a standard servlet rather than a JSP document because there is no document output from the servlet that does the forwarding. You will usually have conditional logic to decide where to forward the request, but the programming is the same in either case.

RequestDispatcher dispatcher =
request.getRequestDispatcher("/example.jsp");

dispatcher.forward(request, response);
      
Q: What's the difference between ServletContext and PageContext?

A: The ServletContext and PageContext classes are quite different and do not belong to the same class hierarchy. The ServletContext holds references to the overall context of the Web application, such as the servlets that belong to the application, server information, logging facilities and global configuration settings. The PageContext is a collection of request and response references for a single JSP servlet instance, for handling errors, forwarding requests and suchlike. The PageContext also has references to the JSP ServletConfig and master ServletContext objects, but is designed only as a temporary interface to those object references for the duration of a single service request.

Q: What's the difference between the implicit page and pageContext variables?

A: The implicit page variable is simply a "this" reference to the JSP instance that is being invoked by the servlet container. This is an object provided by the container that fulfils the JspPage interface, and normally the HttpJspPage interface too. These interfaces are similar to the Servlet and HttpServlet interfaces and implement JSP lifecycle methods jspInit, jspDestroy and _jspService(HttpServletRequest, HttpServletResponse).

The JSP pageContext variable refers to an object that implements the PageContext interface. The page context has convenience methods to access common Web application variables, including the servlet configuration and context objects, request and response objects, request attributes, and session object.

JSP problems

Q: Why are my JSP script tags showing?

A: It sounds like you are opening the JSP file directly from the file system, rather than deploying it in a servlet container perhaps? You must request the JSP page from the servlet container using the HTTP protocol.

Premium Content: Follow this link for subscription information More details available to subscribers:
Why are my JSP script tags showing?

Q: A JSP script causes 500 errors with some browsers!

A: There are many reasons why a JSP may fail, but apparent browser problems may indicate a fault in your program logic. The most common flaws in any server side process are those that assume the client request will have a particular format or all required parameters.

Premium Content: Follow this link for subscription information More details available to subscribers:
A JSP script causes 500 errors with some browsers!

Q: What happens when a JSP has a compilation error?

A: If your JSP fails to compile to a servlet at request time, the servlet container will have no valid response for the request and will issue an HTTP 404, not found, response. Depending on the container and any custom error configuration you may have, the compilation error details may be displayed in the server log.

Q: My relative links to /home.jsp don't work!

A: The use of a forward slash at the start of a relative URL means the path refers to the root of the current host. In this case, /home.jsp would link to http://localhost:8080/home.jsp. If your Web application is not based in the special ROOT application directory, any hyperlinks that take this form will be incorrect.

If your Web application is named myWebApp for example, your home page reference would be /myWebApp/home.jsp. Another option is to give hyperlink references that are relative to the current virtual directory, which is specified with a leading dot: ./home.jsp. To create a link from a document in a sub-directory use an extra dot: ../home.jsp.

JSP application design

Q: How can I forward from one JSP to multiple JSP pages?

A: It is better to use a servlet to process request information and control which of several JSP pages it should be forwarded to. In either case, the technique is the same, to get a RequestDispatcher with the relevant JSP document path.

Using JSP documents to forward requests can be problematic because any document output that is committed before the request is forwarded will throw an exception. This arrangement suggests a lack of clarity about what your JSP document is intended to do. A dedicated servlet would encapsulate the logic about where to forward requests and avoid the technical risk of committed output.

Q: How can I call a servlet from a JSP?

A: When JSP documents are compiled, they extend an HttpServlet type, so they can use the same techniques as standard servlets to interact with resources in the servlet container.

Premium Content: Follow this link for subscription information More details available to subscribers:
How can I call a servlet from a JSP?

Help request

Use the form below to submit a help request or general enquiry about the Code Style Web site. Before you write read the guidelines on asking the right questions, and check this page for periodic updates.

Information: Your email address will not be mis-used. If you include your address you may be sent a personal reply, you will not be added to any mailing list unless you request it. Read the site privacy statement for details.

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log