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:
<%!public void jspInit() {. . .}%><%!public void jspDestroy() {. . .}%>

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

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

How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught runtime 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.






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:<%@ page buffer="none" %>

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: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-INFjspbeans directory for it to be located by the JSP engine.

What is the page directive is used to prevent a JSP page from automatically creating a session?

<%@ page session="false">

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.

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.






What is preinitialization of a servlet?

A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

What is the difference between ServletContext and ServletConfig?

ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

Explain ServletContext.

ServletContext interface is a window for a servlet to view it’s environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container’s version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a “/” and are interpreted as relative to curent context root.

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. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

How many JSP scripting elements are there and what are they?

There are three scripting language elements: declarations, scriptlets, expressions






What are cookies and how will you use them?

Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user.
a) Create a cookie with the Cookie constructor: public Cookie(String name, String value)
b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie)
c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().

What is Server-Side Includes (SSI)?

Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.

What is session tracking and how do you track a user session in servlets?

Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:
a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password.
b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server.
c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.
d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.
e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.

What is the difference between doPost and doGet methods?

a) doGet() method is used to get information, while doPost() method is used for posting information.
b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length.
c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

What is the difference between HttpServlet and GenericServlet?

A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract






What is a Expression?

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like

You cannot use a semicolon to end an expression

What is a Hidden Comment?

comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.
You can use any characters in the body of the comment except the closing –%> combination. If you need to use –%> in your comment, you can escape it by typing –%\>.

What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann’t be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

How do servlets handle multiple simultaneous requests?

The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

What is Servlet chaining?

Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.






What are implicit objects? List them?

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
* request
* response
* pageContext
* session
* application
* out
* config
* page
* exception

Difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

What are the different scope available in JSP Page?
The different scope available are
1. page
2. request

What is a output comment?

A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

What is a Declaration?

A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.






What does the JSP engine do when presented with a JavaServer Page to process?

The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to methods of the appropriate JavaBean class whose output is translated into more calls to a println method to place the result in the HTML document

Explain the directory structure of a web application.

The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.
WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory

What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?

Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

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

How does JSP handle run-time exceptions?

One 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"%>
Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.






What is the difference between RequestDispatcher and sendRedirect?

RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

What is the difference between directive include and jsp include?

<%@ include>: Used to include static resources during translation time.
JSP include: Used to include dynamic content or static content during runtime.

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource.
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

What is a translation unit?

JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit. Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

What are the lifecycle phases of a JSP?

JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.

    Jsp Sets


    July 2008

    RSS Feed