Here we have mentioned most frequently asked JSP Interview Questions and Answers specially for freshers and experienced.


 

1. Explain JSP and tell its uses.

Ans:

JSP stands for Java Server Pages. It is a presentation layer technology independent of platform. It comes with SUN’s J2EE platforms. They are like HTML pages but with Java code pieces embedded in them. They are saved with a .jsp extension. They are compiled using JSP compiler in the background and generate a Servlet from the page.

2. What is the requirement of a tag library?

Ans:

A collection of custom tags is called a Tag Library. Recurring tasks are handled more easily and reused across multiple applications to increase productivity. They are used by Web Application designers who focus on presentation rather than accessing database or other services. Some popular libraries are String tag library and Apache display tag library.

3. Explain JSP Technology.

Ans:

JSP is a standard extension of Java and is defined on top of Servlet extensions. Its goal is to simplify management and creation of dynamic web pages. It is platform-independent, secure, and it makes use of Java as a server side scripting language.

4. Explain Implicit objects in JSP.

Ans:

Objects created by web container and contain information regarding a particular request, application or page are called Implicit Objects. They are :
1)response
2)exception
3)application
4)request
5)session
6)page
7)out
8)config
9)pageContext

5. How can multiple submits due to refresh button clicks be prevented?

Ans:

Using a Post/Redirect/Get or a PRG pattern, this problem can be solved.
1. A form filled by the user is submitted to the server using POST or GET method. The state in the database and business model are updated.
2. A redirect response is used to reply by the servlet for a view page.
3. A view is loaded by the browser using the GET command and no user data is sent. This is safe from multiple submits as it is a separate JSP page.

6. Is JSP technology extensible?

Ans:

Yes, JSP is easily extensible by use and modification of tags, or custom actions, encapsulated in tag libraries.

7. Differentiate between response.sendRedirect(url) and < jsp:forwordpage=…> .

Ans:

< jsp:forwordpage=…>element forwards the request object from 1 JSP file to another. Target file can be HTML, servlet or another JSP file, but it should be in the same application context as forwarding JSP file.
sendRedirect send HTTP temporary redirect response to the browser. The browser then creates a new request for the redirected page. It kills the session variables.

8. Can a subsequent request be accessed with one’s servlet code, if a request attribute is already sent in his JSP?

Ans:

The request goes out of scope, thus, it cannot be accessed. However, if a request attribute is set in one’s servlet, then it can be accessed in his JSP.
A JSP is a server side component and the page in translated to a Java servlet, and then executed. Only HTML code is given as output.

9. How to include static files in a JSP page?

Ans:

Static pages are always included using JSP include directive. This way the inclusion is performed in the translation phase once. Note that a relative URL must be supplied for file attribute. Although static resources may be included, it is not preferred as each request requires inclusion.

10. Why is it that JComponent have add() and remove() methods but Component doesn’t?

Ans:

JComponent is a subclass of Container. It contains other Components and JComponents.



 

11. How can a thread safe JSP page be implemented?

Ans:

It can be done by having them implemented by the SingleThreadModel Interface. Add <%@page isThreadSafe=”false” %> directive in the JSP page.

12. How can the output of JSP or servlet page be prevented from being cached by the browser?

Ans:

Using appropriate HTTP header attributes to prevent the dynamic content output by a JSP page from being cached by the browser.

13. How to restrict page errors display in a JSP page?

Ans:

By setting up an “ErrorPage” attribute of PAGE directory to the name of the error page in the JSP page, and then in the error jsp page set “isErrorpage=”TRUE”, Errors can be stopped from getting displayed.

14. What are JSP Actions?

Ans:

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

15. Differentiate between and <%@include file=…>.

Ans:

Both these tags include information from 1 page to another.
The first tag acts as a function call between two Jsp’s. It is executed each time client page is accessed by the client. It is useful to modularize the web application. New content is included in the output.
The second tag content of file is textually embedded having similar directive. The changed content is not included in the output. It is helpful when code from one jsp is required by several jsp’s.

16. Can constructor be used instead of init(), to initialize servlet?

Ans:

Yes, it is possible. But it is not preferred because init() was developed because earlier Java versions could not invoke constructors with arguments dynamically. So they could not assign a servletConfig. Today, however, servlet containers still call only no-arg constructor. So there is no access to servletContext or servletConfig.

17. Explain lifecycle methods.

Ans:

1) jsplnit(): The container calls this to initialize servlet instance. It is called only once for the servlet instance and preceded every other method.
2) _jspService(): The container calls this for each request and passes it on to the objects.
3) jspDestroy(): It is called by the container just before destruction of the instance.

18. Explain JSP Output comments?

Ans:

They are comments that can be viewed in HTML Source File.

19. Define Expression

Ans:

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

20. Define Composition.

Ans:

Composition has a stronger relationship with the object than Aggregation.




 

21. Define JSP Scriptlet.

Ans:

It a JSP tag that encloses Java code in JSP pages. Their syntax is <% %>. Code written in scriptlet executes every time the program is run.

22. How can information from one JSP be passed to another JSP?

Ans:

The tag < jsp:param> allows us to pass information between multiple Jsp’s.

23. Explain the uses of tag.

Ans:

This tag creates an instance of java bean. It firstly tries to find if bean instance already exist and assign stores a reference in the variable. Type is also specified; otherwise it instantiates from the specified class storing a reference in the new variable.

24. Explain handling of runtime exceptions.

Ans:

Errorpage attribute is used to uncatch the run-time exceptions forwarded automatically to an error processing page.
It redirects the browser to JSP page error.jsp if any uncaught exception is faces during request handling. It is an error processing page.

25. Why does _jspService() start with an ‘_’ but other lifecycle methods do not?

Ans:

Whatever content made in a jsp page goes inside the _jspService() method by the container. If it is override, the compiler gives an error, but the other 2 lifecycles can be easily override. So ‘_’ shows that we cannot override this method.

26. Explain the various scope values for < jsp: useBean> tag.

Ans:

tag is used to use any java object in the jsp page. Some scope values are :
1)application
2)request
3)page
4)session

27. Show the 2 types of comments in JSP.

Ans:

The 2 types are :

<%–JSP Comment–%>
<!–HTML comment–>

28. Can Static method be Override?

Ans:

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’.

29. Explain JSP directives.

Ans:

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

30. Explain pge Directives.

Ans:

Page Directives inform the JSP Engine about headers and facilities that the page receives from the environment. It is found at the top of all JSP pages. Its syntax is <%@ page attribute=”value”>


 

31. Show attributes of page directives.

Ans:

1)Session : It shows if a session data is available to the page.
2)Import : it shows packages that are imported.
3)isELIgnored : It shows whether EL expressions are ignored when JSP translates into a servlet.
4)contentType : it allows the user to specify the content type of page.

32. What is Include directive?

Ans:

The include directive statically inserts the contents of a resource into the current JSP. It helps in the reuse of code without duplication. and includes contents of the file at translation time. Its syntax is as follows <%@ include file=”Filename”%>.

33. What are standard actions in JSP?

Ans:

They affect overall runtime behaviour of a page and response sent to the client. They are used to include a file at request time, to instantiate a JavaBean or find one. They are also used to generate a browser-specific code or forward a request to a new page.

34. Explain the jsp:setProperty action.

Ans:

It is used to give values to properties of beans that have been referenced beforehand.

jsp:setproperty is executed even if a new bean is instantiated or existing bean is found.

By adding at the end of the code, the condition for execution is inverted i.e. It is not executed if existing object was found and only if a new object was instantiated.

35. Define Static Block.

Ans:

It is used to start the static data member. It is executed before classloading.

36. Explain jsp:plugin action.

Ans:

This action helps in insertion of a specific object in the browser or embed the element needed to specify the running of applet using Java plugin.

37. Explain client and server side validation.

Ans:

Javascript is used for the client-side validation. It takes place within the browser. Javascript is used to submit the form data if validation is successful. Validation errors require no extra network trip because form cannot be submitted.
Validation is also carried out in the server after submission. If validation fails, extra network trip is required to resend the form to the client.

38. What is Translation Phase?

Ans:

JSP engine translates and compiles a JSP file to a servlet. This servlet moves to the execution phase where requests and responses are handled. They are compiled for the first time they are accessed unless manually compiled ahead of time. The manual or explicit compilation is useful for long and convoluted programs.

39. Perform a Browser Redirection from a JSP Page.

Ans:

<% response.sendRedirect(URL); %>

or we can change the location of the HTTP header attribute as follows:

<% response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader(URL); %>

40.Give uses of Object Cloning.

Ans:

Object cloning is used to create an exact copy of an object by typing the same code or using various other techniques.



 

41. How can you avoid scriptlet code in JSP?

Ans:

JavaBeans or Custom Tags can be used instead of scriptlet code.

42. Explain the jspDestroy() method.

Ans:

Whenever a JSP page is about to be destroyed, the container invokes the jspDestroy() method from the javax.servlet.jsp.JspPage interface. Servlets destroy methods are similar to it. It can be easily overridden to perform cleanup, like when closing a database connection.

43. Explain static method.

Ans:

A static method is of the class and not the object of a class. It can be invoked without instance of a class. Static members can also access the static data and change its value.

44. How to disable scripting?

Ans:

Scripting can be easily disabled by setting scripting-invalid element of the deployment descriptor to true. It is a sub-element of property group. Its can be false as well.

45.Define JSP Declaration.

Ans:

JSP Declaration are tags used in declaring variables. They are enclosed in <%!%> tag. They are used in declaring functions and variables.

<%@page contentType=”text/html” %>

<%!
int a=0;
private int getCount(){
a++;
return a;
}
%>

Values of a are:

 

<%=getCount()%>

 

46. How can HTML Output be prevented from being cached?

Ans:

<%
response.setHeader(“Cache-Control”, “no=store”);
response.setDateHeader(“Expires”, 0);
%>

47. How is JSP better than Servlet technology?

Ans:

JSP is a technology on the server’s side to make content generation simple. They are document centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside HTML template file. It provides the framework for development of a Web Application.

48. What is JSP?

Ans:

JSP stands for Java Server Pages, it is a server side technology which is used for creating dynamic web pages. It is the extension of servlets.

49. What does dynamic web page means here?

Ans:

The web pages that are generated based on user’s response and may be different for
each user are called dynamic web pages unlike the static web pages that are same for every user no matter how they interact with the application.

50. What does Server side technology means?

Ans:

There are basically two types of technologies: client-side and Server-side. Client-side means that the action takes place on the user’s (the client’s) computer. Server-side means that the action takes place on a web server (the place where you have stored all your JSP pages).




 

51. What are JSP life cycle phases?

Ans:

A JSP page goes through the below phases:
1) Compilation: In this phase the JSP code gets converted into the equivalent servlet code.
2) Initialization: The converted JSP code gets loaded into the memory. jspInit() method gets called in this phase.
3) Execution: _jspService() method gets called in this phase. In this step a response is generated for the user based on the request made by them.
4) Destroy: jspDestroy() method gets called in this phase to unload the JSP from the memory. This is also known as cleanup step.

52. What all JSP lifecycle methods can you override in your JSP application?

Ans:

You can only override jspInit() and jspDestroy(), you cannot override the _jspService() method within a JSP page. By overriding jspInit() method you can initialize things like database connections, network connections etc. Whatever you initialize in jspInit() method can be freed up (released) in jspDestroy() method.

53. How many implicit objects you have in JSP, name them?

Ans:

The objects that can directly be used on any JSP page without the need of being declared first are known as implicit objects. In JSP we have total 9 implicit objects, they are as follows:
1) out
2) request
3) response
4) session
5) config
6) exception
7) page
8) pageContext
9) application

54. What is the purpose of scriptlets in JSP? What’s the syntax of it?

Ans:

A scriptlet is used for including java code in a JSP page.
Syntax:

<% Java Code %>

55. What is JSP declaration tag?

Ans:

A JSP declaration tag is used for declaring variables and methods so that you can use them later on a JSP page based on the requirement.
Syntax:

<%! Declare variables /Methods %>

56. Is JSP technology extensible?

Ans:

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

57. What are advantages of using JSP?

Ans:

JSP offer several advantages as listed below –
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself.
JSP are always compiled before it’s processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.


 

58. What are the advantages of JSP over Active Server Pages (ASP)?

Ans:

The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

59. What are the advantages of JSP over Pure Servlets?

Ans:

It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are –
Embedding of Java code in HTML pages.
Platform independence.
Creation of database-driven Web applications.
Server-side programming capabilities.

60. What are the advantages of JSP over Server-Side Includes (SSI)?

Ans:

SSI is really only intended for simple inclusions, not for “real” programs that use form data, make database connections, and the like.

61. What are the advantages of JSP over JavaScript?

Ans:

JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.

62. What are the advantages of JSP over Static HTML?

Ans:

Regular HTML, of course, cannot contain dynamic information.
Explain lifecycle of a JSP.
A JSP Lifecycle consists of following steps –
Compilation – When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps –
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
Initialization – When a container loads a JSP it invokes the jspInit() method before servicing any requests
Execution – Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
Cleanup – The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.

63. What is a sciptlet in JSP and what is its syntax?

Ans:

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet –

<% code fragment %>

64. What are JSP declarations?

Ans:

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.

<%! declaration; [ declaration; ]+ ... %>

65. What are JSP expressions?

Ans:

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Its syntax is –

<%= expression %>

66. What are JSP comments?

Ans:

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or “comment out” part of your JSP page.
Following is the syntax of JSP comments –

<%-- This is JSP comment --%>

67. What are JSP Directives?

Ans:

A JSP directive affects the overall structure of the servlet class. It usually has the following form –

<%@ directive attribute = "value" %>

68. What are the types of directive tags?

Ans:

The types directive tags are as follows –
<%@ page … %> – Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include … %> – Includes a file during the translation phase.
<%@ taglib … %> – Declares a tag library, containing custom actions, used in the page.

69. What are JSP actions?

Ans:

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.

70. What are JSP literals?

Ans:

Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals –
Boolean – true and false
Integer – as in Java
Floating point – as in Java
String – with single and double quotes; ” is escaped as \”, ‘ is escaped as \’, and \ is escaped as \\.
Null – null



 

71. What is a page directive?

Ans:

The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.

72. What are various attributes Of page directive?

Ans:

Page directive contains the following 13 attributes.
language
extends
import
session
isThreadSafe
info
errorPage
isErrorpage
contentType
isELIgnored
buffer
autoFlush
isScriptingEnabled

73. What is a buffer attribute?

Ans:

The buffer attribute specifies buffering characteristics for the server output response object.

74. What happens when buffer is set to a value “none”?

Ans:

When buffer is set to “none”, servlet output is immediately directed to the response output object.

75. What is autoFlush attribute?

Ans:

The autoFlush attribute specifies whether buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate buffer overflow.
A value of true (default) indicates automatic buffer flushing and a value of false throws an exception.

76. What is contentType attribute?

Ans:

The contentType attribute sets the character encoding for the JSP page and for the generated response page. The default content type is text/html, which is the standard content type for HTML pages.

77. What is errorPage attribute?

Ans:

The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL.

78. What is isErrorPage attribute?

Ans:

The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP.
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false.

79. What is extends attribute?

Ans:

The extends attribute specifies a superclass that the generated servlet must extend.

80. What is import attribute?

Ans:

The import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import.




 

81. What is info attribute?

Ans:

The info attribute lets you provide a description of the JSP.

82. What is isThreadSafe attribute?

Ans:

The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP.

83. What is language attribute?

Ans:

The language attribute indicates the programming language used in scripting the JSP page.

84. What is session attribute?

Ans:

The session attribute indicates whether or not the JSP page uses HTTP sessions. A value of true means that the JSP page has access to a builtin session object and a value of false means that the JSP page cannot access the builtin session object.

85. What is isELIgnored Attribute?

Ans:

The isELIgnored option gives you the ability to disable the evaluation of Expression Language (EL) expressions.
The default value of the attribute is true, meaning that expressions, ${…}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.

86. What is isScriptingEnabled Attribute?

Ans:

The isScriptingEnabled attribute determines if scripting elements are allowed for use.
The default value (true) enables scriptlets, expressions, and declarations. If the attribute’s value is set to false, a translation-time error will be raised if the JSP uses any scriptlets, expressions (non-EL), or declarations.

87. What is a include directive?

Ans:

The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows –

<%@ include file = "relative url" >

88. What is a taglib directive?

Ans:

The taglib directive follows the following syntax –

<%@ taglib uri = “uri” prefix = “prefixOfTag”>
uri attribute value resolves to a location the container understands
prefix attribute informs a container what bits of markup are custom actions.
The taglib directive follows the following syntax –

<%@ taglib uri = "uri" prefix = "prefixOfTag" >

89. What do the id and scope attribute mean in the action elements?

Ans:

Id attribute – The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
Scope attribute – This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.

90. What is the function of action?

Ans:

This action lets you insert files into the page being generated. Where page is the relative URL of the page to be included.
Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included.


 

91. What is the difference between include action and include directive?

Ans:

Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, include action inserts the file at the time the page is requested.

92. What are the different scope values for the JSP action?

Ans:

The scope attribute identifies the lifecycle of the Action element. It has four possible values: (a) page, (b)request, (c)session, and (d) application.

93. What are JSP implicit objects?

Ans:

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

94. What implicit objects are supported by JSP?

Ans:

request, response, out, session, application, config, pageContext, page, Exception

95. What is a request object?

Ans:

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.

96. How can you read a request header information?

Ans:

Using getHeaderNames() method of HttpServletRequest to read the HTTP header information. This method returns an Enumeration that contains the header information associated with the current HTTP request.

97. What is a response object?

Ans:

The response object is an instance of a javax.servlet.http.HttpServletRequest object. Just as the server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.

98. What is the out implicit object?

Ans:

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.

99. What is the difference between JspWriter and PrintWriter?

Ans:

The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.

100. What is the session Object?

Ans:

The session object is an instance of javax.servlet.http.HttpSession and is used to track client session between client requests



 

101. What is an application Object?

Ans:

The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.

102. What is a config Object?

Ans:

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.

103. What is a pageContext Object?

Ans:

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.

104. What is a page object?

Ans:

This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.

105. What is an exception Object?

Ans:

The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

106. What is difference between GET and POST method in HTTP protocol?

Ans:

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character.
The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.

107. How to read form data using JSP?

Ans:

JSP handles form data parsing automatically using the following methods depending on the situation –
getParameter() – You call request.getParameter() method to get the value of a form parameter.
getParameterValues() – Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterNames() – Call this method if you want a complete list of all parameters in the current request.
getInputStream() – Call this method to read binary data stream coming from the client.

108. What are filters?

Ans:

JSP Filters are Java classes that can be used in JSP Programming for the following purposes –
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.

109. How do you define filters?

Ans:

Filters are defined in the deployment descriptor file web.xml and then mapped to either servlet or JSP names or URL patterns in your application’s deployment descriptor.
When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

110. What are cookies?

Ans:

Cookies are text files stored on the client computer and they are kept for various information tracking purpose.




 

111. How cookies work?

Ans:

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser).If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.

112. How do you set cookies in the JSP?

Ans:

Setting cookies with JSP involves three steps –
Creating a Cookie object – You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Setting the maximum age – You use setMaxAge to specify how long (in seconds) the cookie should be valid.
Sending the Cookie into the HTTP response headers – You use response.addCookie to add cookies in the HTTP response header

113. How to read cookies with JSP?

Ans:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

114. How to delete cookies with JSP?

Ans:

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps –
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Add this cookie back into response header.

115. How is Session Management done in JSP?

Ans:

Session management can be achieved by the use of –
Cookies – A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
Hidden Form Fields – A web server can send a hidden HTML form field along with a unique session ID as follows –

This implies that when the form is submitted, the specified name and value will be getting included in GET or POST method.
URL Rewriting – In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled.
The session Object – JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

116. How can you delete a session data?

Ans:

When you are done with a user’s session data, you have several options –
Remove a particular attribute – You can call public void removeAttribute(String name) method to delete the value associated with the a particular key.
Delete the whole session – You can call public void invalidate()method to discard an entire session.
Setting Session timeout – You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Log the user out – The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration – If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.

117. What is JSP page redirection?

Ans:

Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.

118. How do you implement hit counter in JSP?

Ans:

To implement a hit counter you can make use of Application Implicit object and associated methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.

119. How can you implement hit counter to avoid loss of count data with each restart of the application?

Ans:

You can follow the below steps –
Define a database table with a single count, let us say hitcount. Assign a zero value to it.
With every hit, read the table to get the value of hitcount.
Increase the value of hitcount by one and update the table with new value.
Display new value of hitcount as total page hit counts.
If you want to count hits for all the pages, implement above logic for all the pages.

120. What is auto refresh feature?

Ans:

Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your Webpage regularly using refresh or reload button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.



 

121. How do you implement the auto refresh in JSP?

Ans:

The simplest way of refreshing a Webpage is using method setIntHeader() of response object. Following is the signature of this method –
public void setIntHeader(String header, int headerValue)
This method sends back header “Refresh” to the browser along with an integer value which indicates time interval in seconds.

122. What is JSTL?

Ans:

The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which 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 tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.

123. What the different types of JSTL tags are ?

Ans:

Types of JSTL tags are –
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions

124. What are the options in JSP to include files?

Ans:

In JSP, we can perform inclusion in the following ways –
By include directive – For example –

<%@ include file = ”header.jsp” %>

By include action – For example –

<%@ include file = ”header.jsp” %>

By using pageContext implicit object For example –

<% pageContext.include(“/header.jsp”); %>

By using RequestDispatcher object – For example –

<%
RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);
Rd.include(request,response);
%>

125. What are JSTL XML tags?

Ans:

The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP.

<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>

126. What is a JSP custom tag?

Ans:

A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page’s servlet is executed.

127. What is JSP Expression Language?

Ans:

JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. A simple syntax for JSP EL is –

${expr}

Here expr specifies the expression itself.

128. What are the implicit EL objects in JSP ?

Ans:

The JSP expression language supports the following implicit objects –
pageScope – Scoped variables from page scope
requestScope – Scoped variables from request scope
sessionScope – Scoped variables from session scope
applicationScope – Scoped variables from application scope
param – Request parameters as strings
paramValues – Request parameters as collections of strings
headerHTTP – request headers as strings
headerValues – HTTP request headers as collections of strings
initParam – Context-initialization parameters
cookie – Cookie values
pageContext – The JSP PageContext object for the current page

129. How can we disable EL ?

Ans:

We can disable using isELIgnored attribute of the page directive –

<%@ page isELIgnored = "true|false" %>

If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

130. What type of errors you might encounter in a JSP code?

Ans:

Checked exceptions – Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions – A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors – These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.


 

131. In JSP page how can we handle runtime exception?

Ans:

We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
Example: <%@ page errorPage = “error.jsp” %>
It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage=”true” %>

132. What is Internationalization?

Ans:

Internationalization means enabling a web site to provide different versions of content translated into the visitor’s language or nationality.

133. What is Localization?

Ans:

Localization means adding resources to a web site to adapt it to a particular geographical or cultural region for example Telugu translation to a web site.

134. What is locale?

Ans:

This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example “en_US” represents english locale for US.

135. How do I include static files within a JSP page?

Ans:

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.

136. Can a JSP page process HTML FORM data?

Ans:

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.

137. How do you pass control from one JSP page to another?

Ans:

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.
Using the response.sendRedirect method.

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

Ans:

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.

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

Ans:

<%@ page session = "false">

140. How to pass information from JSP to included JSP?

Ans:

Using <%jsp:param> tag.



 

141. When do use application scope?

Ans:

If we want to make our data available to the entire application then we have to use application scope.

142. How does JSP engines instantiate tag handler classes instances?

Ans:

JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it.

143. What’s the difference between JavaBeans and taglib directives?

Ans:

JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them –
Taglibs are for generating presentation elements while JavaBeans are good for storing information and state.
Use custom tags to implement actions and JavaBeans to present information.

144. What is a hit count for a Webpage?

Ans:

A hit counter tells you about the number of visits on a particular page of your web site.