Concurrent programming features Q: Can a class have more than one thread? A: Any Java class may be loaded and instantiated as part of a multi-threaded program. Since Java is fundamentally a multi-threaded programming language all classes should be designed with this possibility in mind, with a judgement whether it is likely and what its consequences would be. You should normally have enough information to judge whether your own classes are likely to be used in a multi-threaded context. If there is the no immediate requirement, avoid thread-proofing your class until that time comes. The Java API is used for general programming purposes that cannot be anticipated in advance, so thread safety considerations are usually noted in classes' API documentation. Many data storage and management classes in the java.util package are distinguished by their thread safety status because safety is usually a trade-off against the time-performance of key operations. Q: What is threaded programming and when is it used? A: Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction. The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications. Q: What is a thread? A: In Java the Thread class represents a single independent path of execution in a Java Virtual Machine. When you run a Java program it implicitly starts a single thread of execution. The Thread class enables programmers to create additional threads and set them running. A number of threads may run in parallel, but only one is actively executed at a given moment. The Java runtime system uses fairly complex thread scheduling mechanisms to coordinate the execution of threads, but this does not require privileged knowledge or detail level intervention by programmers. Programmers can manage the high level creation, initiation and distribution of tasks amongst threads through simple Application Programming Interface (API) methods. The example below shows the simplest approach to thread creation and task execution; construct a new Thread with a Runnable argument and start it. What is a thread? Q: How do Java threads make the environment asynchronous? A: The thread mechanism in Java begins with the main entry point thread the runtime environment creates to start a Java program. When you use that initial thread create secondary threads, each one runs independently of the other. The Java virtual machine manages the execution of the threads so they behave as if they all run at the same time, in fact each thread briefly takes turns at execution. In its simplest form there may be no communication or synchronization between multiple threads in a Java program and they each run to completion independently of each other. In this respect Java threads are fundamentally asynchronous, there is no master clock that governs when threads will run and when they synchronize variables to “catch-up” with each other. It is often necessary and more useful if threads do check ready states before progressing, synchronize read and write access to shared variables and call-back to each other when their work is done. This is where the synchronized keyword and the various sleep(), wait() and notify() methods are used to more closely schedule the interaction between asynchronous threads. Threads and runnable types Q: What's the difference between Thread and Runnable types? A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main() method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it. The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run(), which makes the interface very easy to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation. Q: What is a Runnable object and a Runnable argument? A: A Runnable object is one that implements the Runnable interface, which is the type used to execute new threads. The Runnable interface only has one method, run(), which must be implemented by a Runnable class. In Java an argument is a primitive value or object reference that is passed to a constructor or method, defined in the method signature. A Runnable argument would be a constructor or method argument that is declared to be a Runnable type. The constructor of the Thread class is the most obvious example. public Thread(Runnable target); This constructor requires a Runnable type argument to be passed when a Thread is instantiated. Q: How does the run() method in Runnable work? A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects. Q: A Thread is runnable, how does that work? A: The Thread class' run() method normally invokes the run() method of the Runnable type it is passed in its constructor. However, it is possible to override the thread's run method with your own. It is more common to implement the Runnable interface in a separate class and pass it to a standard Thread constructor. This approach usually requires less coding and allows your Runnable class to inherit useful application-specific behaviour from a separate class hierarchy. Q: Do Thread and Runnable types have their own run() methods? A: The Runnable interface defines an abstract run() method and the Thread class implements the interface, so has its own concrete run() method. However the Thread class implementation of run() is different from most others because of its special use in the creation of new threads. In a typical Runnable class the run() method contains code that does the main work of a thread. It may complete one long-running process or set up a loop that repeats a series of actions, for example. The Thread run() method has no “worker” code of its own, it just calls the run() method of the Runnable object that was passed to its constructor. To instantiate a Thread object you normally pass a Runnable class to the constructor as the “target” of the thread. When you call the Thread's start() method it creates a new thread whose first and only action is the to call Thread class' own run() method once. The Thread class run() calls the run() method on the target Runnable, which does the work of the thread. Q: Why not override Thread to make a Runnable? A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method to be implemented. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited. Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed. Q: When could I adapt the Thread class though? A: It is always best to implement a Runnable type rather than extend a Thread. On that basis, the extension of the Thread class should only be considered in exceptional circumstances when the application is very simple, composed of few classes, where the interaction of threads is minimal and requires only minimal control over thread execution. The start() method Q: What's the difference between a thread's start() and run() methods? A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns. The Thread class' run() method calls the run() method of the Runnable type class passed to its constructor. Subclasses of Thread should override the run() method with their own code to execute in the second thread. Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method. Howevever, the code will only be executed in a new thread if the start() method is used. Q: Can I implement my own start() method? A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method. Thread management methods Q: Which class is the wait() method defined in? A: The wait() method is defined in the Object class, which is the ultimate superclass of all others. So the Thread class and any Runnable implementation inherit this method from Object. The wait() method is normally called on an object in a multi-threaded program to allow other threads to run. The method should only be called by a thread that has ownership of the object's monitor, which usually means it is in a synchronized method or statement block. Q: Which class is the sleep(long) method defined in? A: The sleep(long) method is defined as a static method of the Thread class for two reasons. First, it is responsible for delaying the execution of threads rather than any other objects, so Thread is the logical host for the method. Secondly, it is static because it suspends the currently executing thread, which is implicitly the thread that called the method. The programmer does not need to know which other threads are alive. The sleep(long) method retains the synchronization locks of the current thread, so it can have a significant effect on the behaviour of multi-threaded applications. If the exact period of the delay you require is not important, it may be better to use the wait(long) method. Q: Why are wait(), notify() and notifyAll() methods defined in the Object class? A: The purpose of the wait(), notify() and notifyAll() methods is to temporarily pause and resume the execution of code in an object. Typically the host object is not in a state where it can proceed with a method call it has been given and the thread of execution must literally wait for the object to return to a ready state. A common example would be a limited pool or store of objects where you must wait for a storage slot to be released or an object to be returned to the pool before you can use it. public synchronized Object getNextObject() { // Waiting loop while (! objectAvailable()) { try { wait(); } catch (InterruptedException e) { // Handle exception } } // No longer waiting, get the return object Object returnObject; // Assign the returnObject from store // Notify state change for other waiters notify(); return returnObject;} The act of waiting is associated with the Object class because any subclass may need to wait for a ready state to occur (Java is fundamentally a multi-threaded language). The waiting process acts on a single thread of execution, but the wait mechanism expects that multiple threads may be waiting for the same object. The wait() and notify() methods are hosted by the Object class so that the Java Virtual Machine can manage the “wait set” of threads through the objects they are waiting for. Q: Why are there separate wait() and sleep() methods? A: The static Thread.sleep(long) method maintains control of the thread execution but delays the next action until the sleep time expires. The wait() method gives up control over thread execution indefinitely so that other threads can run. Multi-threaded design questions Q: If all methods are synchronized, is a class thread safe? A: Even if all the methods of a class are synchronized, it may still be vulnerable to thread safety problems if it exposes non-final fields or its methods return mutable object references that could be manipulated by multiple threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy. A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level. These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor. Q: Do I need to use synchronized on setValue(int)? A: It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues. Q: How do I create a Runnable with inheritance? A: To introduce a Runnable type to an existing class hierarchy, you need to create a sub-class that declares that it implements the Runnable interface, and provide a run() method to do so. This combination of interface and inheritance means that runnable implementations can be very minor extensions of existing classes, as in the example below. Q: What is the volatile modifier for? A: The Java language specification allows the runtime system to keep a local copy of a variable in each thread that refers to it. These thread-local copies of a variable act like a cache to improve the performance of multi-threaded programs, they avoid having to check the true master value of the variable every time it is needed. One consequence of this thread cache behaviour is that at the moment of execution the value of thread-local variables may be different from the true master value of the variable. For variables whose value does not change frequently and would not critically affect the behaviour of a program, thread-local cached values are a tolerable compromise of precision for the sake of better performance, if not they should be controlled. You can use synchronized blocks to ensure the true master value of a variable is used, but at the cost of excluding all other thread access to those code blocks. The volatile modifier ensures the integrity of a variable value without the performance impact of full synchronization, it means that any thread that sets or gets the variable must use the true master value. The volatile modifier effectively disables thread-local caching of values for specific variables. Q: What is the SwingUtilities.invokeLater(Runnable) method for? A: The static utility method invokeLater(Runnable) is intended to execute a new runnable thread from a Swing application without disturbing the normal sequence of event dispatching from the Graphical User Interface (GUI). The method places the Runnable object in the queue of Abstract Windowing Toolkit (AWT) events that are due to be processed and returns immediately. The runnable object's run() method is only called when it reaches the front of the queue. The deferred effect of the invokeLater(Runnable) method ensures that any necessary updates to the user interface can occur immediately, and the runnable work will begin as soon as those high priority events are dealt with. The invoke later method might be used to start work in response to a button click that also requires a significant change to the user interface, perhaps to restrict other activities, before the runnable thread executes. Q: Which has priority with a static synchronized thread? A: A synchronized method uses what is called an intrinsic lock to control thread execution, an object reference that is used as a monitor for the lock. Synchronized instance methods implicitly use their own object instance as the monitor. Only one thread can hold the monitor object at a given moment and execute the synchronized code. Static synchronized methods may be executed when there is no instance of the class to serve as a lock monitor, so must use a different lock object. When class methods are invoked the Java runtime system automatically creates an object of the type Class as the context for the method to be executed. If the class method happens to be synchronized, this Class instance is the intrinsic lock used as the monitor object for synchronization. Since synchronized instance and class methods have different monitor objects, there is no effective synchronization control between them and no guarantee to their sequence of execution. If a closer level of control is required, it may be necessary to remove the synchronized modifier from the instance method and create a synchronized block inside the method that uses the Class instance as its monitor, as in the example below. Multi-threaded design patterns Q: What is a working thread? A: A working thread, more commonly known as a worker thread, is the key part of a design pattern that allocates one thread to execute one task. When the task is complete, the thread may return to a thread pool for later use. In this scheme a thread may execute arbitrary tasks, which are passed in the form of a Runnable method argument, typically execute(Runnable). The runnable tasks are usually stored in a queue until a thread host is available to run them. The worker thread design pattern is usually used to handle many concurrent tasks where it is not important which finishes first and no single task needs to be coordinated with another. The task queue controls how many threads run concurrently to improve the overall performance of the system. However, a worker thread framework requires relatively complex programming to set up, so should not be used where simpler threading techniques can achieve similar results. Thread programming jargon Q: What is a green thread? A: A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If a Java program has any concurrent threads, the JVM manages multi-threading behaviour internally rather than use additional operating system threads. There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads. These days there is no case where the green thread approach is useful except on systems where this is the only concurrency scheme that is available for Java, on old operating systems and hardware platforms. Q: What are native operating system threads? A: Native operating system threads are those provided by the computer operating system that plays host to a Java application, be it Windows, Mac or GNU/Linux. Operating system threads enable computers to run many programs simultaneously on the same Central Processing Unit (CPU) without clashing over the use of system resources or spending lots of time running one program at the expense of another. Operating system thread management is usually optimised to specific microprocessor architecture and features so that it operates much faster than Java green thread processing. Thread programming problems Q: I get “incompatible return type” for my thread's getState() method! A: It sounds like your application was built for a Java Software Development Kit (SDK) before Java 1.5. The Java Application Programming Interface (API) Thread class method getState() was introduced in version 1.5. Your thread method has the same name but different return type. The compiler assumes your application code is attempting to override the API method with a different return type, which is not allowed, hence the compilation error. You have two main options; compile your program with a Java SDK before version 1.5, or rename your method and adapt any client classes to the new name. Q: Apache Log4J has thrown a ThreadDeath error! A: The java.lang.ThreadDeath type signals a serious Error in the execution of a Java program and should not normally be caught by applications, it should be left to escalate and terminate the application. ThreadDeath is a Throwable type, so the Apache logging package may blindly catch Throwable rather than an Exception, which is not recommended. More likely ThreadDeath is caught so that other asynchronous threads may be cleaned up before logging is terminated. Since this ThreadDeath instance is wrapped in the commons LogConfigurationException, the root cause of the problem is most likely that “a suitable LogFactory or Log instance cannot be created by the corresponding factory methods”. In other words, your logging configuration declares a type that cannot be instantiated, possibly because of bad spelling, ultimately because the named class is not available to the relevant classloader. Servlets ConceptsQ: What's the difference between applets and servlets? A: There are many fundamental differences between Applet and Servlet classes, the Java API documentation for the two types will show you they have little in common. Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment, typically embedded in an HTML page. Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser, in a restrictive security environment called a "sandbox". Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. Servlets are often used to validate and process HTML form submissions and control a series of user interactions in what is known as a Web application. Servlets can be used to control all aspects of the request and response exchange between a Web browser and the server, called a servlet container. Q: Do we open servlet classes directly instead of HTML? A: Servlets are used to deliver HTML to Web browsers, but they are not like static HTML documents. When you set up a servlet in a Web application it has a URL like a static HTML document, so you can link to it, bookmark it or send the URL by email, just as you would with an standard Web page. The main difference is that the HTML sent to the Web browser is composed dynamically by the servlet and its contents can be customised based on the details of the request sent by the Web browser. When you open a servlet URL the browser does not display content of the servlet class, but a dynamic HTML document created by the servlet. The servlet class is written as a standard Java class that extends the HttpServlet class. In its most basic form, the HTML output can be created by a series of print() statements on a PrintWriter. The method that handles simple Web requests is called doGet(), as below. public final void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter output = response.getWriter(); output.println(""); output.println("
"); output.println("
"); // Other HTML output output.flush(); output.close();}Q: What part of the Java platform do servlets and JSP belong to? A: The servlet and JSP APIs are a standard extension to the core Java API and runtime system. Their package names are prefixed javax to indicate they are standard extensions, but that means that they rely upon a code implementation provided by a specific vendor. For example, the Apache Tomcat project supplies its own implementation of the servlet and JSP API that is integrated with the servlet container. Developers must compile their code using the vendor's servlet package implementation by including it in the compiler's classpath. The servlet container includes the same package classes in its runtime system and feeds concrete instances of the servlet interface types to the servlet's lifecycle methods. Q: How does the JVM execute a servlet compared with a regular Java class? A: Servlets are standard Java classes and are executed by the Java Virtual Machine in exactly the same way as any other. However, the environment or context in which servlets are executed is different. A servlet is not invoked directly through a main() method, the class is loaded and run by a servlet container. When you run a servlet container, it reads its configuration, identifies the servlet classes to make available, and uses the Java classloader system to load and run the servlets. When the servlets are first brought into service, the servlet container calls the servlet's init() method and passes the ServletConfig object as an argument. Whenever a request is made to the servlet, the container creates a new thread in which to handle it. Q: How can I tell when a servlet is instantiated? A: A servlet must be instantiated before it is brought into service by the servlet container, so one way to check is to make a request to the servlet and check the response. If you need to check indirectly, you can override the init(ServletConfig) method and add log(String) statements to it. This method is called after the servlet container has instantiated the servlet before it is brought into service. Servlet programming Q: How can I write a servlet using Javascript? A: Java servlets is a server side technology that delivers dynamic content to Web browsers and other clients. Javascript is also delivered by a Web server, but the code is only interpreted and executed after it has been downloaded by the Web browser. This means that it is not possible to write servlet code in Javascript. It is possible to include Javascript in the output of servlets and Java Server Pages, just like standard Web pages. It is also possible to dynamically generate Javascript using a servlet and use it as the source for a script tag, though this is only advisable in rare cases. Q: Can I use a normal class to handle my requests? A: Servlets are normal Java classes, they compile and run just like any other class. All that is required is that servlets implement the javax.servlet.Servlet interface. Usually, they extend a protocol-specific class such as javax.servlet.http.HttpServlet. Q: Can I include normal Java classes in servlets? A: Any Java class can be used in a Web application, provided you make the classes available to the servlet container at runtime. The Java API classes can be used directly by adding import statements to your servlet class. Other supporting classes can also be imported, but these classes must be added to the classes or lib directory of your application. If you need to configure the supporting classes, this can be done with standard servlet configuration features using the ServletConfig and ServletContext objects available to the init(ServletConfig) method. Q: Can I use a constructor in my servlet? A: A servlet is a normal Java class, so when there are no custom constructors, there is an implicit default constructor with no arguments. Servlet containers typically use the Class.newInstance() method to load servlets, so you must be careful to add an explicit default constructor if you add non-default constructors. Q: What happens if I add a main method to my servlet? A: It is possible to write a main method for a servlet, but it will not be called by the servlet container, it is not part of the servlet lifecycle process. If you invoke your servlet through the main method using the java command it will behave exactly like a standard Java class, it cannot operate as a Web application in its own right and cannot be addressed using HTTP requests. Servlets must run in a servlet container to deliver Web applications as intended. Servlet start up Q: Can one JSP or Servlet extend another Servlet or JSP A: It is possible and necessary for servlets to extend other classes, they are standard Java classes in most respects. Most servlets extend the abstract HttpServlet class included in a servlet container's API implementation. This abstract class implements the generic Servlet interface with HTTP-specific methods and provides a minimal basis to extend and create your own servlet classes. If you need to develop complex behaviour across a set of servlets you can extend this hierarchy to create numerous servlet subclasses. The automatic source code generation and compilation scheme used to create JSP servlets means that extension of the JSP servlet class is more complex and should generally be avoided. Q: How do I compile a servlet? A: To compile a servlet, you will need to have the Java Servlet API classes in your classpath. Most Java servlet containers come with a copy, it may be called servlet.jar or something similar. The basic classes are in the packages javax.servlet and javax.servlet.http. Q: Why won't my servlet compile? A: All those "cannot find symbol" error messages mean that you do not have the Java servlet JAR file on your compiler's classpath, so it cannot find the servlet class files. The servlet JAR file is normally distributed with your servlet container. For Apache Tomcat it is a file named {CATALINA_HOME}/common/lib/servlet-api.jar. Add this to your compiler classpath as follows. Q: Where is the servlet stored and where does it run? A: When you create a servlet, the code must be installed in a servlet container which operates as an HTTP server application. In the a development environment the servlet container is often installed on a developer's own workstation, or a hardware server in the local network where it can be accessed privately for testing. In a production environment the servlet container is usually installed on a server that is accessible from the Internet, but the Java software arrangement is basically the same. Servlet code is compiled to Java class byte code which is physically located on the server hardware with the servlet container. The servlet operates as an extension of the servlet container and its code is executed on the server. Web browsers operate as clients which connect to the servlet container, issue HTTP requests and receive HTTP responses from the servlet container, mostly in the form of HTML pages and other Web content. The servlet code is not downloaded or executed by the Web browser at all, it only receives standard Web content and renders it accordingly. Q: What are the basic steps to run a servlet? A: The key steps in creating and running a servlet are outlined below in the simplest form. There are different techniques that can be used to complete these stages, described in other FAQ answers. Write and compile your servlet, e.g. ExampleServlet.class Create a Web application directory structure under the webapp directory of your servlet container (or use an existing one), e.g. {webapps-dir}/example{webapps-dir}/example/WEB-INF{webapps-dir}/example/WEB-INF/classesPlace your servlet class file in the WEB-INF/classes directory for your application, e.g. {webapps-dir}/example/WEB-INF/classes/ExampleServlet.classCreate a WEB-INF/web.xml file for your application (or edit an existing one) and add servlet and servlet-mapping elements for your servlet, e.g. {webapps-dir}/example/WEB-INF/web.xmlStart the servlet container. Q: What is the difference between JAR and WAR files? A: There is no difference between the binary form of JAR and WAR files, they both use zip compression provided by the jar tool. You can create a WAR file by navigating to the root directory of your Web application and typing the jar command, as below. Servlet techniques Q: Can I access a servlet from a stand-alone client? A: It is certainly possible to access a servlet that is hosted in a servlet container. Any HTTP client should be able to connect to a properly configured servlet container and make requests to a servlet. However, servlets do not run in their own right, they are not server applications. Q: How can I write a servlet client for testing? A: Marty Hall provides the source code for a basic HTTP client in his book Core Servlets and Java Server Pages. The source code for chapter 3 is available online. Look for WebClient.java and supporting classes. This application allows you to manually input the host, request path, HTTP header values and view the headers returned by a Web application. Q: What is URL-rewriting? A: URL-rewriting is a way of maintaining a session between an HTTP client and a servlet container which does not use cookies. Rather than exchange a session ID in a cookie, the servlet container includes it in the hyperlink URLs it generates for servlets and JSP. Q: How can I redirect a request to another URL? A: The standard servlet method to redirect one HTTP request to another is the HttpServletResponse sendRedirect(String) method. The String argument is the URL for the address you want to direct people to. String otherURL = "http://example.com/otherPage.jsp";response.sendRedirect(otherURL);When you call this method it will issue an HTTP redirect request to the browser, commit the servlet response and end the HTTP exchange. The browser should automatically create a new HTTP request for the given URL that will be entirely separate from the original request. HTTP redirection is different from the RequestDispatcher forward() method, which sends the forwarded content in the original HTTP response stream. Q: What's the difference between forward, include and redirection? A: The RequestDispatcher forward() and include() methods are mechanisms that are internal to a servlet container and do not affect the public URL of a Web resource. When you call the forward() method on a RequestDispatcher with a JSP path, the servlet container returns the JSP content on the original servlet's URL; this effectively becomes the response of the servlet itself. 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 servlet source is created; as a standard Java source file, or a template that is essentially an HTML document with JSP tags. Q: Can we implement an interface in a JSP? A: A Java Server Page (JSP) implements the HttpJspPage interface and its superinterface JspPage. The implementation of these interfaces is necessary for a JSP to conform to the Java servlets specification and run in a servlet container. The implementation code for these interfaces should be provided by the servlet container and will include container-specific details. When a servlet container converts a JSP document to Java source code the servlet code it generates extends the container's HttpJspPage implementation class and inherits the container-specific code necessary to execute the servlet. The automated code generation and compilation scheme used to create JSP servlets means that it is practically impossible for a JSP to implement any other Java interface. Since JSP servlet classes are dynamically generated it would also be difficult to use them in any other environment. Q: How is JSP code interpreted and executed? A: A useful way to understand how JSP code is handled by a servlet container is to look at the contents of the Tomcat "work" directory after you have deployed your Web application. For a host named org.example, the ROOT level application code will be located at: $CATALINA_HOME/work/Catalina/example.org/_/org/apache/jspQ: 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. 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: Java Server Pages 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 isThreadSafe 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. 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. 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. 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.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. 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 fulfills 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. 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. 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 JSP throws IllegalStateException! A: It seems you are using your JSP to serve content through RequestDispatcher forwarding, a role that would normally be assigned to a servlet. This is possible with JSP, but its not recommended. The problem you have found is where the JSP has output the HTTP headers, and possibly HTML content, before attempting to forward the request. What this means is that part of the content had already been sent to the Web browser and it was too late to feed another resource into the response. The RequestDispatcher forward() method is not like a standard Web page redirect which prompts a browser request for the second page. The forward() method attempts to push another resource back through the response opened for the original request. 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 What is difference between page and pageContext in JSP pages?The page and pageContext are implicit JSP Objects. The page object represents the generated servlet instance itself, i.e., it is same as the "this" keyword used in a Java file. As a result, you do not typically know who the super class is, and consequently do not normally make use of this object or its methods.The pageContext object represents the environment for the page, containing useful information like page attributes, access to the request, response and session objects, as well as the JspWriter referenced by out. This object also has methods for including another URL's contents, and for forwarding or redirecting to another URL. For example, to forward a request to another resource from in a JSP page, we can do that by using the pageContext variable:pageContext.forward ("other.jsp"); Implicit ObjectClass or InterfacePurpose, Function, or Usespagejava.lang.ObjectRefers to the generated Servlet class. Since page refers to the generated class and the class implements the Servlet interface, it is a valid cast it to Servlet. And the page variable could also be cast to JspPage or HttpJspPage since these two interfaces are derived from the Servlet interface and are implemented by the generated servlet class. For example, <%= ((Servlet)page).getServletInfo () %>pageContextjavax.servlet. jsp.PageContextUsed for storing and retrieving page-related information and sharing objects within the same translation unit and same request.Also used as a convenience class that maintains a table of all the other implicit objects. For example,public void _jspService ( HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { ... try { ... application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); ... } catch (Throwable t) { ... } finally { ... }}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. Q: Can my JSP support the FTP protocol? A: Java Server Pages have been designed specifically to behave as dynamic web pages using the HTTP request and response protocol, they are highly specialised for this purpose and not suitable to implement any other protocol. If you want to use Java servlet technology to develop an FTP service, it would be better to start with the generic javax.servlet.Servlet interface and abstract javax.servlet.GenericServlet class and build FTP-specific behaviour around them. You would also need to develop an FTP-specific servlet container to host FTP servlets. It would be possible to use servlets and JSP to create a Web application that behaves like an FTP client. For example, you could use an HTML form with a file input field to select and upload files via a servlet, and a JSP to list files on the server with links to download them. Your web application would need to take account of various security issues and may not have the full functionality of the FTP protocol but could provide a simple alternative.