Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Advantages of JSP

JSP vs Active Server Pages: The major benefit offered by the JSP as compared to Active Server Pages is that it uses Java for expression writing which is more helpful, powerful and easy to use. Where as in Active Server Pages, you will need to use Visual Basic or any other Microsoft language. The second benefit offered by the JSP is that you can port it to any other operating system.
  • JSP vs Pure Servlets: In the servlets, you have to write the entire html in println statements which is hard to format, hard to understand and manage. JSP offers HTML writing in a simple file which is easy to manage.
  • JSP vs Server Side Includes: Server Side Includes is not designed for real programs and it is used for simple inclusions. So it does not support database connections and other functionality.
  • JSP vs JavaScript: JavaScript is used to generate dynamic HTML content on the client end and for other scripting functionality. On the other hand it does not provide server interaction, database access, image processing etc.
  • JSP vs Static HTML: Static HTML is used to just render output on the browser and it does not provide dynamic information.

JSP Interview Questions and Answers

Q. How does JSP differ from a desk top application?
A. Desktop applications (e.g. Swing) are presentation-centric, which means when you click a menu item you know which window would be displayed and how it would look. Web applications are resource-centric as opposed to being presentation-centric. Web applications should be thought of as follows: A browser should request from a server a resource (not a page) and depending on the availability of that resource and the model state, server would generate different presentation like a regular “read-only” web page or a form with input controls, or a “page-not-found” message for the requested resource. So think in terms of resources, not pages. 

Servlets and JSPs are server-side presentation-tier components managed by the web container within an application server. Web applications make use of HTTP protocol, which is a stateless request-response based paradigm. JSP technology extends the Servlet technology, which means anything you can do with a Servlet you can do with a JSP as well.



Q. Did JSPs make servlets obsolete?  
A. No. JSPs did not make Servlets obsolete. Both Servlets and JSPs are complementary technologies. You can look at the JSP technology from an HTML designer’s perspective as an extension to HTML with embedded dynamic content and from a Java developer’s as an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“….. ”) statements, where “out” is a PrintWriter. This process of embedding HTML code with escape characters in Servlets is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.



Q. What is a model 0 pattern (i.e. model-less pattern) and why is it not recommended? What is a model-2  or MVC architecture?
A. 

Problem: The example shown above is based on a “model 0” (i.e. embedding business logic within JSP) pattern.  The model 0 pattern is fine for a very basic JSP page as shown above.  But real web applications would have business logic, data access logic etc, which would make the above code hard to read, difficult to maintain, difficult to refactor, and untestable. It is also not recommended to embed business logic and data access logic in a JSP page since it is protocol dependent (i.e. HTTP protocol) and makes it unable to be reused elsewhere like a wireless application using a WAP protocol,  a standalone XML based messaging application etc.        

Solution:  You can refactor the processing code containing business logic and data access logic into Java classes, which adhered to certain standards. This approach provides better testability, reuse and reduced the size of the JSP pages.  This is known as the “model 1” pattern where JSPs retain the responsibility of a controller, and view renderer with display logic but delegates the business processing to java classes known as Java Beans. The Java Beans are Java classes, which adhere to following items:

  • Implement java.io.Serializable or java.io.Externalizable interface.
  • Provide a no-arguments constructor.
  • Private properties must have corresponding getXXX/setXXX methods.


The above model provides a great improvement from the model 0 or model-less pattern, but there are still some problems and limitations. 

Problem:  In the model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the user. This architecture may be suitable for simple applications, but complex applications will end up with significant amount of Java code embedded within your JSP page, especially when there is significant amount of data processing to be performed.  This is a problem not only for java developers due to design ugliness but also a problem for web designers when you have large amount of Java code in your JSP pages. In many cases, the page receiving the request is not the page, which renders the response as an HTML output because decisions need to be made based on the submitted data to determine the most appropriate page to be displayed.   This would require your pages to be redirected (i.e. sendRedirect (…)) or forwarded to each other resulting in a messy flow of control and design ugliness for the application. So, why should you use a JSP page as a controller, which is mainly designed to be used as a template?        

Solution: You can use the Model 2 architecture (MVC – Model, View, Controller architecture), which is a hybrid approach for serving dynamic content, since it combines the use of both Servlets and JSPs. It takes advantage of the predominant strengths of both technologies where a Servlet is the target for submitting a request and performing flow-control tasks and using JSPs to generate the presentation layer. As shown in the diagram below, the servlet acts as the controller and is responsible for request processing and the creation of any beans or objects used by the JSP as well as deciding, which JSP page to forward or redirect the request to  (i.e. flow control) depending on the data submitted by the user. The JSP page is responsible for retrieving any objects or beans that may have been previously created by the servlet, and as a template for rendering the view as a response to be sent to the user as an HTML.

Q. If you set a request attribute in your JSP, would you be able to access it in your subsequent request within your servlet code? 
    [This question can be asked to determine if you understand the request/response paradigm]
A. The answer is no because your request goes out of scope, but if you set a request attribute in your servlet then you would be able to access it in your JSP. 



Important: Servlets and JSPs are server side technologies and it is essential to understand the HTTP request/response paradigm. A common misconception is that the Java code embedded in the HTML page is transmitted to the browser with the HTML and executed in the browser. As shown in the diagram above, this is not true. A JSP is a server side component where the page is translated into a Java servlet and executed on the server. The generated servlet (from the JSP) outputs only HTML  code to the browser.   


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Structure of Web Applications


Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server.
A web application has the directory structureas shown in below figure.
J2EE Web Application Directory Structure
The root directory of the application is called the document root. Root directory is mapped to the context path. Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. So if there are any resources like JSPs or HTML document that you don’t wish to be accessible directly from web browser, you should place it under WEB-INF directory.

WEB-INF directory structure

WEB-INF directory contains
  • WEB-INF/web.xml deployment descriptor
  • WEB-INF/classes directory
  • WEB-INF/lib directory

/WEB-INF/web.xml

web.xml is called the web application deployment descriptor. This is a XML file that defines servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any J2EE web application, so every web application must have a web.xml deployment descriptor directly under WEB-INF folder.

/WEB-INF/classes

The classes directory is used to store compiled servlet and other classes of the application. If your classes are organized into packages, the directory structure must be reflected directly under WEB-INF/classes directory. The classes directory is automatically included in CLASSPATH.

/WEB-INF/lib

Lib directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j, JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.
All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory are included in classpath and made visible to the containing web application.

JSP Implicit Objects

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 :It represents the request made by the client. The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
  • response :The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
  • pageContext : This is used to access page attributes and also to access all the namespaces associated with a JSP page. The lass or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext The PageContext object has a page scope. It is an instance of the javax.servlet.jsp.PageContext class.
  • session :The session object has a scope of an entire HttpSession. It is an instance of the javax.servlet.http.HttpSession class. It represents the session created for the requesting client, and stores objects between client's requests. The session object views and manipulates session information, such as the session identifier, creation time, and last accessed time. It also binds objects to a session, so that the user information may persist across multiple user connections.
  • application :The application object has an application scope. It is an instance of the javax.servlet.ServletContext class. It represents the context within which the JSP is executing. It defines a set of methods that a servlet uses to communicate with its servlet container.
  • out :The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.
  • config :The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
  • page :The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object.
  • exception :The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.

Life cycle methods in JSP

Life-cycle methods of the JSP are:
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.
_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.
jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

Types of Comments in JSP

There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output.
Example of hidden comment:

<%-- This is hidden comment --%>
Example of output comment:
<!-- This is output comment -->

Advantages of JSP over Servlet.



  • Efficient: With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.
  • Convenient: Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
  • Powerful: Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.
  • Portable: Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.
  • Inexpensive: There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

Difference between JSP include directive and JSP include action


  • <%@ include file=”filename” %> is the JSP include directive.
    At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers.
    The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output.
  • <jsp:include page=”relativeURL” /> is the JSP include action element.
    The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters.
    If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

Difference Between Forward and Include in JSP


The <jsp:forward> action enables you to forward the request to a static HTML file, a servlet, or another JSP.
<jsp:forward page="url" />
The JSP that contains the <jsp:forward> action stops processing, clears its buffer, and forwards the request to the target resource. Note that the calling JSP should not write anything to the response prior to the <jsp:forward> action.
You can also pass additional parameters to the target resource using the <jsp:param> tag.
<jsp:forward page="test.htm" >
   <jsp:param name="name1" value="value1" />
   <jsp:param name="name2" value="value2" />
</jsp:forward>

In this example, test.jsp can access the value of name1 using request.getParameter("name1").


To "include" another resource with a JSP, you have two options: the include directive and the include action.
The include directive executes when the JSP is compiled, which parses any JSP elements in the included file for a static result that is the same for every instance of that JSP. The syntax for the include directive is <@ include file="some-filename" %>.
The include action, on the other hand, executes for each client request of the JSP, which means the file is not parsed but included in place. This provides the capability to dynamically change not only the content that you want to include, but also the output of that content. The syntax for the include action is <jsp:include page="some-filename" flush="true" />. Note that the flush attribute must always be included (in JSP 1.1) to force a flush of the buffer in the output stream.

You can also pass parameters to the included file using the same process as the <jsp:forward> action:
<jsp:include page="template.htm" flush="true" >
   <jsp:param name="name1" value="value1" />
</jsp:include>

Difference between forward and response.sendRedirect


Forward : when forward is used server forwards the request to the new url and the control stays on the same page. in other words it just forward the request to new url and come back fomr where forward is called.
sendRedirect : sendRedirect forward the request to url as new request and the cotrol goes to the destination page and never come back to the calling page 

Difference between the request attribute and request parameter


Request parameters are the result of submitting an HTTP request with a query string that specifies the name/value pairs, or of submitting an HTML form that specifies the name/value pairs. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using request.getParameter(). Parameters are Strings, and generally can be retrieved, but not set.
Let's take a real example, you have one html page named RegisterForm.html and JSP page named Register.jsp. The RegisterForm.html contains a form with few parameters for user registration on web application and those parameters you want to store in database.
<html>
  <body>
    <form name="regform" method="post" action="../Register.jsp">
      <table ID="Table1">
        <tr>
          <td>
       First Name : <input type="text" name="FIRSTNAME" size="25" value="">
          </td>
        </tr>
        <tr>
          <td>
            <input type="Submit" NAME="Submit" value="Submit" >
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

  
When user will enter first name in the text filed and press submit button, it will callRegister.jsp page. Now you want the value entered in text field by user in jsp/servlet so there you use request.getParameter() method.
<%
  String lFirstName = request.getParameter("FIRSTNAME");
  ...................
%>
On the server side, the request.getParameter() will retrieve a value that the client has submitted in the First Name text field. Using this method you can retrive only one value. This method i.e. getParameter method is in ServletRequest interface which is part of javax.servlet package.
Request attributes (more correctly called "request-scoped variables") are objects of any type that are explicitly placed on the request object via a call to the setAttribute() method. They are retrieved in Java code via the getAttribute() method and in JSP pages with Expression Language references. Always use request.getAttribute() to get an object added to the request scope on the serverside i.e. using request.setAttribute().
Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern. For example, you want to take values from database in one jsp/servlet and display them in another jsp. Now you have resultset filled with data ready in servlet then you use setAttributemethod and send this resultset to another jsp where it can be extracted by using getAttributemethod.
Once a servlet gets a request, it can add additional attributes, then forward the request off to another servlet for processing. Attributes allow servlets to communicate with one another.

Difference Between Servlets And Jsp


Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server's servlet engine, servicing client requests forwarded to it through the server. A Java Server Page is a slightly more complicated beast. JSP pages contain a mixture of HTML, Java scripts (not to be confused with JavaScript), JSP elements, and JSP directives. The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.


The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development. Rather than choosing between servlets and Java Server Pages, you will find that most non-trivial applications will want to use a combination of JSP and servlets. In fact, the JSP 1.1 and Servlet 2.2 specifications are based around the concept of the Web application, combining the two APIs into a unified framework.

Latest JSP Interview Questions and Answers

1. What is JSP?

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.

2. What do you understand by JSP Actions?

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

< jsp : include / >

< jsp : forward / >

< jsp : plugin / >

< jsp : usebean / >

< jsp : setProperty / >

< jsp : getProperty / >


3. What is the difference between < jsp : include page = ... > and < % @ include file = ... >?

Both the tags include information from one JSP page in another. The differences are:

< jsp : include page = ... >

This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.

< % @ include file = ... >

In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

4. What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?

The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.

sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.


5. Name one advantage of JSP over Servlets? 

Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.

However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.

6. What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:

application
config
exception
out
page
pageContext
request
response and
session

7. What are all the different scope values for the < jsp : useBean > tag?

< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:

a) page
b) request
c) session and
d) application


8. What is JSP Output Comments?

JSP Output Comments are the comments that can be viewed in the HTML source file. They are comments that are enclosed within the < ! - - Your Comments Here - - >

9. What is expression in JSP?

Expression tag is used to insert Java values directly into the output.

Syntax for the Expression tag is: <%= 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. The most commonly used language is regular Java.

10. What types of comments are available in the JSP?

There are two types of comments that are allowed in the JSP. They are hidden and output comments.

A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output.

Example of hidden comment:
< % - - This is a hidden comment - - % >

Example of output comment:
< ! - - This is an output comment - - >


11. What is a JSP Scriptlet?

JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.


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

13. What are JSP Custom tags?

JSP Custom tags are user defined JSP language elements. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the readability of JSP pages.

14. What is the role of JSP in MVC Model?

JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.

15. What do you understand by context initialization parameters?

The context-param element contains the declaration of a web application's servlet context initialization parameters.


namevalue


The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.

16. Can you extend JSP technology?

Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features.

17. What do you understand by JSP translation?

JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.

18. How can you prevent the Browser from Caching data of the Pages you visit?

By setting properties that prevent caching in your JSP Page. They are:
<% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1); response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents caching at the proxy server response.addHeader("cache-Control", "private"); %>

19. How will you handle the runtime exception in your jsp page?

The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True.

20. What is JavaServer Pages Standard Tag Library (JSTL) ? 

A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.


21. What is JSP container ? 

A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

22. What is JSP custom action ? 

A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

23. What is JSP custom tag ? 

A tag that references a JSP custom action.

24. What is JSP declaration ? 

A JSP scripting element that declares methods, variables, or both in a JSP page.

25. What is JSP directive ? 

A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

26. What is JSP document ? 

A JSP page written in XML syntax and subject to the constraints of XML documents.

27. What is JSP element ? 

A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.


28. What is JSP expression ? 

A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.


29. What is JSP expression language ? 

A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.


30. What is JSP page ? 

A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.


31. What is JSP scripting element ? 

A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".


32. What is JSP scriptlet ? 

A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".

33. What is JSP tag file ? 

A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

34. What is JSP tag handler ? 

A Java programming language object that implements the behavior of a custom tag.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them. 

Most Important JSP Interview Questions with Answers


What is a JSP and what is it used for?
Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.
What is difference between custom JSP tags and beans? 
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:
1. the tag handler class that defines the tag\'s behavior
2. the tag library descriptor file that maps the XML element names to the tag implementations
3. the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.

<%=identifier.getclassField() %>
Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
What are the two kinds of comments in JSP and what's the difference between them ?
<%-- JSP Comment --%>
<!-- HTML Comment -->
What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.
What is JSP page? 
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.
What are the implicit objects? 
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
--request
--response
--pageContext
--session
--application
--out
--config
--page
--exception
How many JSP scripting elements and what are they? 
There are three scripting language elements:
--declarations
--scriptlets
--expressions
Why are JSP pages the preferred API for creating a web-based client program? 
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
Is JSP technology extensible? 
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
Can we use the constructor, instead of init(), to initialize servlet? 
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
How can a servlet refresh automatically if some new data has entered the database? 
You can use a client-side Refresh or Server Push.

The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.
How many messaging models do JMS provide for and what are they? 
JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.
What information is needed to create a TCP Socket? 
The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.
What Class.forName will do while loading drivers? 
It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
How to Retrieve Warnings? 
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object


SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println(\"Message: \" + warning.getMessage());
System.out.println(\"SQLState: \" + warning.getSQLState());
System.out.print(\"Vendor error code: \");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
How many JSP scripting elements are there and what are they? 
There are three scripting language elements: declarations, scriptlets, expressions.
In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
What are stored procedures? How is it useful? 
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.
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.
Why does JComponent have add() and remove() methods but Component does not? 
because JComponent is a subclass of Container, and can contain other components and jcomponents. 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.
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.
How do you restrict page errors display in the JSP page? 
You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage="error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page.
How can I declare methods within my JSP page?
You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.
For example:
Another Example:
file1.jsp:
file2.jsp
<%test(out);% >
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 (assuming Java is your scripting language) is to use the return statement when you want to terminate further processing.
Can a JSP page process HTML FORM data? 
Yes. However, unlike Servlet, 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.
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.
How do you pass control from one JSP page to another? 
Use the following ways to pass control of a request from one servlet to another or one jsp to another.
The RequestDispatcher object ‘s forward method to pass the control.
The response.sendRedirect method
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 JSPengine 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.
How does a servlet communicate with a JSP page? 
The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));

//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .

f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
. . .
}
}

The JSP page Bean1.jsp can then process fBean, a
fter first extracting it from the default request
scope via the useBean action.

jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getProperty
name="fBean" property="name" / jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean"
property="personalizationInfo" /
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. 
How do I use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
value=""/ >
How can I set a cookie and delete a cookie from within a JSP page? 
A cookie, mycookie, can be deleted using the following scriptlet:
How do you connect to the database from JSP? 
A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets.
Further then you can use the resultset object "res" to read data in the following way. 
What is the page directive is used to prevent a JSP page from automatically creating a session? 
<%@ page session="false">
How do you delete a Cookie within a JSP? 
Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);
Can we implement an interface in a JSP? 
No
What is the difference between ServletContext and PageContext? 
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request
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.
How to pass information from JSP to included JSP? 
Using <%jsp:param> tag.
How is JSP include directive different from JSP include action. ?
When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page's output is returned back to the added page. This happens at runtime.
Can we override the jspInit(), _jspService() and jspDestroy() methods? 
We can override jspinit() and jspDestroy() methods but not _jspService().
Why is _jspService() method starting with an '_' while other life cycle methods do not? 
_jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.
What happens when a page is statically included in another JSP page? 
An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the current page. This process of including a file is also called as static include.
A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSP page, index.jsp, which has a instance variable "int a" declared. What happens when the index.jsp page is requested by the client? 
Compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error. 


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email