JSP

What is JSP ? What is its purpose ?

JSP stands for Java Server Page. It is a technology used in presentation layer independent of any platform. It originates from Sun’s J2EE platform. It is similar to HTML page but with Java code embedded within it. It is saved in file that has a .jsp extension. It is compiled using JSP compiler in the background and generate a Servlet from the page. Its goal is to simplify management and creation of dynamic web pages.

What are the implicit objects in JSP ?

Objects created by web container and contain information regarding a particular request, application or page are called implicit objects. In JSP implicit objects are request, session, application, page, pageContext, out, config, exception and response.

What is differentiate between response.sendRedirect(url) and <jsp:forward page = …>

<jsp:forward> element forwards the request object from one JSP to another JSP file. In this case target file can be HTML, servlet or another JSP file, but it has to be in the same application context as forwarding JSP file. In this case the browser URL does not change.

response.sendRedirect sends the temporary HTTP redirect response to the browser. The browser then creates a new request for the redirected page. It kills the session variables. In this case the old browser URL is replaced by new redirected URL.

What are JSP Actions ?

They are typically XML tags, which direct the server to using existing components or control the behavior of JSP Engine. They consist of a typical prefix of “jsp:” and action name.

What is the differentiate between <jsp:include page=…> and <%@include file=…> ?

Both tags include information from one page to another page.

The <jsp:include page=…> tag acts as a function call between two Jsp’s. It is executed each time the page is accessed by the client. It is useful to modularize the web application. The updated content is included in the output.

Using <%@include file=…> tag, the updated content is not included in the output. It is helpful when code from one jsp is required by several jsp’s.

Explain lifecycle in JSP

jsplnit(): The container calls this to initialize servlet instance. It is called only once for the servlet instance and preceded every other method.

_jspService(): The container calls this method for each request and passes it on to the objects.

jspDestroy(): It is called by the container only once just before destruction of the instance.

How do you prevent the Creation of a Session in a JSP Page and why ?

By default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.
The page directive is used to prevent a JSP page from automatically creating a session:

How can I pass information from one JSP to another JSP ?

The tag <Jsp:param> allows us to pass information between multiple JSP files.

Is it possible to share an HttpSession between a JSP and EJB ? What happens when I change a value in the HttpSession from inside an EJB ?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as “passed-by-value”, that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The “pass-by-reference” can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be “bad practice (1)” in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb’s api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it.

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

within your JSP page.

What are JSP directives ?

JSP directives are messages to JSP Engine. They serve as a message from page to container and control the processing of the entire page. They can set global values like class declaration. They do not produce output and are enclosed within <%@…%>

What are page Directives ?

Page Directives inform the JSP Engine about headers and facilities that the page receives from the environment. The page directive is found at the top of the JSP page using the tag <%@page attribute=”value”>.

What are expression and JSP scriplets ?

Expression tag is used to insert Java values directly in the output. Its syntax is <%=expression%>. It contains a scripting language expression that is evaluated, then converted to a string, and then inserted where the expression comes in JSP file.

Scriplets are JSP tags that enclose Java code in JSP pages. Their syntax is <% %>. Code written in scriptlet executes every time the program is run.

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().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

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 is a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use

The <!–#include file=”data.inc”–> is used for including non-JSP files.

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:

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:

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.

Can a JSP page instantiate a serialized bean ?

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

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.

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

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

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

Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server’s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free – which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

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:

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.

Can I just abort processing a JSP ?

Yes. Because your JSP is just a servlet method, you can just put (whereever necessary) a < % return; % >

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:

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:

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.

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:

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:

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

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

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

How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default ?

One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:

What is the difference between ServletContext and ServletConfig ?

Both are interfaces.
The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet’s init() method.
The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.

What are the differences between GET and POST service methods ?

A GET request is a request to get a resource from the server. Choosing GET as the “method” will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won’t show up in the URL bar. You can send much more information to the server this way – and it’s not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects.

What is the difference between GenericServlet and HttpServlet ?

GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.