300+ TOP JSP Interview Questions and Answers

JSP Interview Questions for freshers experienced :-

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

2. What are the two kinds of comments in Jsp and what’s the difference between them ?

<%– JSP Comment –%>

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

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

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

6. How many Jsp Scripting Elements and what are they?

There are three scripting language elements:

  1. declarations
  2. scriptlets
  3. expressions

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

8. Is Jsp technology extensible?

YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

9. 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 Servlet Context.

10. How Can A Servlet Refresh Automatically If Some New Data Has Entered The Database?

You can use a client-side Refresh or Server Push.

JSP Interview Questions
JSP Interview Questions

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

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

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

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

15. 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: \”);
warning = warning.getNextWarning();

16. How Many Jsp Scripting Elements are there and what are they?

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

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

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

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

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

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

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

23. 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:

24. How Do I Perform Browser Redirection From A Jsp Page?

You can use the response implicit object to redirect the browser to a different resource, as: response. send Redirect ; You can also physically alter the Location HTTP header attribute, as shown below: You can also use the:

Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using.

25. 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: 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.

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

27. 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-byreference” 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” 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.

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

29. 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:
<%test(out);% >

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

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

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

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

34. 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”);
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
(“/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” /

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

36. Can A Jsp Page Instantiate A Serialized Bean?

No problem! The use Bean 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.

37. What Is Jsp?

Let’s consider the answer to that from two different perspectives: that of an HTML designer and that of a Java programmer.

If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author. Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program.

Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the servlet generated from the JSP page. The resulting servlet is executed on the server. It is never visible to the user agent. If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user.

38. How Do I Mix Jsp And Ssi #include? What Is The Difference Between Include Directive & Jsp:include Action?

If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.

But it’s 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 <%@ vinclude=”data.inc” %>

The is used for including non-JSP files.

include directive – <%@ include file=”fileName” %> – as is the case with all other directives in a JSP page, this include directive is also processed at the time when the JSP page is translated into its equivalent servlet. This directive simply causes the contents of the specified file to be pasted into the JSP page at the place where the page contains this directive. Irrespective of whether the included resource is a static resource or a JSP page – only the contents of the file are pasted (and not the processed results). This directive is normally used for including static resources only – like, banner, header, footer, etc. for the obvious reason.

include action – this include action is executed at run time and the specified ‘page’ is first executed and then the result of that ‘page’ is appended to the response object of the calling JSP at the point where the tag occurs. Obviously if the specified page is a static resource then the contents of it are included as there won’t be an executed result in that case. This action allows additional parameters to be passed via child element of this include action element.

39. How Do You Prevent The Creation Of A Session In A Jsp Page And Why? What Is The Difference Between Include Directive & Jsp:include Action?

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.

40. 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:

<%//creating a cookieCookie mycookie = new Cookie(“aName”,”aValue”); response.addCookie(mycookie); //delete a cookieCookie killMyCookie = new Cookie(“mycookie”, null); killMyCookie.setMaxAge(0);killMyCookie.setPath(“/”); response.addCookie(killMyCookie);%>

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

42. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session?

<%@ page session=”false”>

43. How Do You Delete A Cookie Within A Jsp?

Cookie mycook = new Cookie(“name”,”value”);
Cookie killmycook = new Cookie(“mycook”,”value”);

44. Can We Implement An Interface In A Jsp?


45. What Is The Difference Between Servletcontext And Pagecontext?

ServletContext: Gives the information about the container
PageContext: Gives the information about the Request.

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

47. How To Pass Information From Jsp To Included Jsp?

Using <%jsp:param> tag.

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

49. Can We Override The Jspinit(), _jspservice() And Jspdestroy() Methods?

We can override jspinit() and jspDestroy() methods but not _jspService().

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

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

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

53. Can You Override Jspinit() Method? If Yes, In Which Cases?

yes, we can. We do it usually when we need to initialize any members which are to be available for a servlet/ JSP throughout its lifetime.

54. What Is The Difference Between Directive Include And Jsp Include?

include directive :

The file gets included at the compile time.
it is static in nature.output comes with jsp page but whole file contains is included in jsp then compilation is done.
action tag :

The file gets included at the run time. This is faster.
it is dynamic in nature.output of yhe file willbe included in the jsp file.

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

56. How Does Jsp Handle Runtime Exceptions?

Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

57. How Can My Application Get To Know When A Httpsession Is Removed?

Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession.

58. 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.
JSP Syntax

Example 1

Displays in the page source:

59. What Is A Hidden Comment?

A 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 –%\>.

JSP Syntax
<%– comment –%>

<%@ page language=”java” %>

<%– This comment will not be visible to the colent in the page source –%>

60. 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
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression.

61. 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.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>

62. What Is A Scriptlet?

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

  1. Declare variables or methods to use later in the file (see also Declaration).
  2. Write expressions valid in the page scripting language (see also Expression).
  3. Use any of the JSP implicit objects or any object declared with a tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

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

64. Difference Between Forward And Sendredirect?

When you invoke a forward request, the request is sent to another resource ohe 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.

65. What Are The Different Scope Valiues For The ?

The different scope values for are
1. page
2. request

66. Explain The Life-cycle Mehtods In Jsp?

The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods – jspInit() and jspDestroy() that must be implemented by all JSP page regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.

This interface declares one method_jspService().

The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.

The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.

The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

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

68. What Is The Difference Between Jsp And Servlets ?

JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

69. 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: the tag handler class that defines the tag’s behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library.

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags .

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.

70. What Are The Different Ways For Session Tracking?

Cookies, URL rewriting, HttpSession, Hidden form fields.

71. What Mechanisms Are Used By A Servlet Container To Maintain Session Information?

Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.

72. Difference Between Get And Post?

In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.

In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

73. What Is Session?

The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests. The session is stored on the server.

74. What Is Servlet Mapping?

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

75. What Is Servlet Context ?

The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

76. What Is A Servlet ?

servlet is a java program that runs inside a web container.

77. How Is Scripting Disabled?

Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a sub element of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:


78. What Is A Jsp Expression?

A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

79. What Are Jsp Declarations?

As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in theservice() method when a JSP is translated to a servlet.

80. What Is The Jsp:plugin Action ?

This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

81. What Are Scripting Elements?

JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

Expressionsof the form <%= expression %> that are evaluated and inserted into the output,
Scriptletsof the form <% code %> that are inserted into the servlet’s service method,
Declarationsof the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

82. What Is The Standard Action?

The standard action is used with or to pass parameter names and values to the target resource. The syntax of the standard action is as follows:

83. What Is The Jsp:getproperty Action?

The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows:

  • If it is an object, it uses the toString() method to convert it to a String.
  • If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
    The syntax of the method is:
  • Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the action before using the action.

84. Differentiate Between Pagecontext.include And Jsp:include?

The standard action and thepageContext.include() method are both used to include resources at runtime. However, thepageContext.include() method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value = of flush is explicitly set to true as follows:

85. What Is The Standard Action?

The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the standard action is as follows:

Here, targetPage is the page to be included in the current JSP.

86. What Is The Standard Action?

The standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

87. What Are The Standard Actions Available In Jsp?

The standard actions available in JSP are as follows:

  • It includes a response from a servlet or a JSP page into the current page.It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
  • It forwards a response from a servlet or a JSP page to another page.
  • It makes a JavaBean available to a page and instantiates the bean.
  • It sets the properties for a JavaBean.
  • It gets the value of a property from a JavaBean component and adds it to the response.
  • It is used in conjunction with ;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
  • It is used to include a Java applet or a JavaBean in the current JSP page.

88. What Are The Jsp Standard Actions?

  • The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
  • They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
  • Ex: include, forward, useBean,etc.

89. What Is The Include Directive?

There are thirteen attributes defined for a page directive of which the importantattributes are as follows:

  • The include directive is used to statically insert the contents of a resource into the current JSP.
  • This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
  • The syntax of the include directive is as follows:
    <%@ include file = “FileName” %>
  • This directive has only one attribute called file that specifies the name of the file to be included.

90. What Are The Attributes Of Page Directive?

There are thirteen attributes defined for a page directive of which the important attributes are as follows:

  • import: It specifies the packages that are to be imported.
  • session: It specifies whether a session data is available to the JSP page.
  • contentType: It allows a user to set the content-type for a page.
  • isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

91. What Is Page Directive?

  1. A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
  2. Typically, the page directive is found at the top of almost all of our JSP pages.
  3. There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
  4. The syntax of the include directive is: <%@ page attribute=”value”>
  5. Example:<%@ include file=”header.jsp” %>

92. What Are Jsp Directives?

• JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page.
• They are used to set global values such as a class declaration, method implementation, output content type, etc.
• They do not produce any output to the client.
• Directives are always enclosed within <%@ ….. %> tag.
• Ex: page directive, include directive, etc.

93. What Are Advantages Of Jsp

whenever there is a change in the code, we dont have to recompile the jsp. it automatically does the compilation. by using custom tags and tag libraries the length of the java code is reduced.

94. 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=”<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>”/ >
<%– scriptlets calling bean setter methods go here –%>
</jsp:useBean >

95. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session:

<%@ page session=”false”>

96. What Are The Steps Required In Adding A Jsp Tag Libraries?

  • Create a TLD file and configure the required class Information.
  • Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport).
  • Compile and package it as loosed class file or as a jar under lib folder in Web Archive File for Class loading.
  • Place the TLD file under the WEB-INF folder.
  • Add reference to the tag library in the web.xml file.

97. Outline The Major Difference Between The Session And Cookie?

Sessions are always stored in the server side whereas cookies are always stored in the client side.

98. How Method Is Declared Within Jsp Page?

Methods can be declared for use within JSP page as declaration and this method can be invoked within any other method which is declared or within JSP scriptlets or expressions. Direct access to the JSP implicit objects like request, response, session etc is forbidden within JSP methods but implicit Java server page variable is allowed to pass as parameters to the method which is declared.

99. Is It Possible By A Jsp Page To Process Html Form Data?

Yes it is possible by simply obtaining the data from the FORM input via the request implicit object which lies with a scriptlet or expression but it doesn’t require to implement any HTTP – Protocol methods like goGet() or doPost() within the JSP page.

100. How Cookies Is Deleted In Jsp?

There are two ways by which the cookies can be deleted in JSP. Firstly, by setting the setMaxAge() of the cookie class to zero. And secondly by setting a timer in the header file that is response. setHeader(expires {Mention the time} attribute), which will delete the cookies after that prescribed time.

101. What Are Custom Tags And Why It Is Needed?

JSP tags are extended by creating a custom set of tags which is called as tag library (taglib). The page which uses custom tags declares taglib and uniquely names, defines and associates a tag prefix to differentiate the usage of those tags.

102. Outline The Difference Between Java Server Page Forward And Servlet Forward Method?

The only minor difference between both the methods is that Java Server page forward method can’t forward to another JSP page in another web application or container whereas servlet forward method can do so.

103. State The Difference Between The Expression And Scriptlet?

JSP, Expressions is used to display the values of variable or to return the values by invoking the getter methods. However, JSP expressions begins with <> and does not have semicolon at the end of the expression. Scriptlet can contain variable, method or expressions that are valid within the page scripting language. Within the scripting tags and page scripting language any valid operations can be performed.

104. How A Run – Time Application Is Handled In Jsp?

In JSP the errorpage attribute of the page is used as a directive to have uncaught run – time exceptions and which is automatically forwarded to an page which processes the error. If an uncaught exception is encountered while processing the request, then the browser redirects to the JSP error page.

105. What Is Declaration In Jsp?

In Java Server pages Declaration is used to declare and define variables and methods that can be used in the Java Server Pages. The variable which is declared is initialized once and it retain its value for every subsequent client request.

106. How To Override The Lifecycle Methods Of Jsp?

Lifecycle method jspService() cannot be overridden within a JSP page however methods like jspInit() and jspDestroy() can be overridden within a JSP page. Method jspInit() is used for allocating resource while method jspDestroy() is used to free allocated resource. But it should be kept in mind that during the lifecycle of a Java Server Page both the method jsplnit() and jspDestroy() is executed once and are declared as JSP declarations.

107. How Jsp Calls A Stored Procedure?

Java Server Pages possess all the characteristics of java and to call and have similar syntax to call a function. Functions and stored procedures of a database can be called by using the statement callable. Another way to call the stored procedure is by writing the JDBC code in between the tag of scriptlet tab.write.

108. What Are The Implicit Objects In Jsp?

There are all total 9 implicit objects in JSP. Application interface refers to the web application’s interface whereas Session interface refers to the user’s session. Request interface refers to the page which is currently requested whereas Response interface refers to the response which is currently made by the user. Config interface refers to the servlet configuration. Class like out, page, page Context and exception refers to the output stream of the page, servlet instance of the page, environment of the page, error handling respectively.

109. How Servlet Differ From Jsp?

Both Servlet and Java Server Pages are API which generate dynamic web content. A servlet is nothing but a java class which implements the interface to run within a web and on the other hand Java server pages is a bit complicated thing which contain a mixture of Java scripts, Java directives, Java elements and HTML. The main difference among both servlet and Java server pages is that JSP is document oriented and servlet on the other hand act likes a program.

110. What Is Jsp? Describe Its Concept?

JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic.

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

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

113. How Is Jsp Used In The Mvc Model

JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

114. What Are Context Initialization Parameters

Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

115. What’s The 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 completely with in the web container And then returns to the calling method. When a sendRedirect 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 completely 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.

116. How Can You Store International / Unicode Characters Into A Cookie?

One way is, before storing the cookie URLEncode it.
And use URLDecoder.decode(str) when you get the stored cookie.

117. In The Servlet 2.4 Specification Singlethreadmodel Has Been Deprecates, 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.

JSP Questions and Answers Pdf Download

Leave a Reply

Your email address will not be published. Required fields are marked *