JSP Interview Questions for Freshers Part – 2

1. What is a JSP?
JSP files are HTML files with special tags that contain java source code that provide dynamic content. Google search engine, the search page is dynamic will display the search results based on the user’s search request.
2. Compare between Servlet and JSP?
In servlets HTML is written inside java code using print statements. In JSP java code is embedded inside HTML.
JSP pages are converted to servlets by the web container so actually it can do the same thing as java servlets.
JSP are easier for creating HTML content but servlets are easier for writing the java code.
A combination of JSP and servlet can be used to separate the presentation(HTML) and logic (java code) and taking the advantage of both.
3. Explain JSP life cycle phases?
JSP life cycle phases are:
Translation and compilation: The JSP will be translated into servlet java file and compiled to servlet class by the web container.
Instantiation: The web container creates an instance of the servlet class.
Initialization: The web container instantiates the servlet and makes it ready for servicing the request.
Service: This is the phase during which the JSP services the user requests.
Destroy: JSP is destroyed by the web container when the application is uninstalled.
4. Explain JSP life cycle methods?
JSP life cycle methods are:
jspInit() – The web container calls the jspInit() to initialize the servlet instance generated. It is invoked before servicing the client request and invoke only once for a servlet instance.
_jspService() – The web container invokes the jspService() for each user request, passing it the request and the response objects.
jspDestroy() – The web container invokes this when it decides to take the instance out of service.
5. What are the types of elements in JSP?
There are four types of elements in JSP:
Directives
Actions
Scripting
Comments
6. What is a scripting element?
Scripting element are used to embed java code in JSP files. Contents of JSP scriptlet goes into _jspService() method during the translation phase.
7. What are the types of scripting elements?
There are three types of scripting elements:
Scriptlets
Declaration
Expression
8. How to create a scriptlet?
Scriptlets are embedded between <% and %> delimiters.
Syntax: <% java code goes in here %>
9. What is declaration element?
Declarations are used to declare, define methods and instance variables.
Declaration tags does not produce any output that is sent to client.
The methods and classes declared will be translated as class level variables and methods during translation.
10. How to declare methods or variables in JSP?
Methods or variables are declared using <%! and %> delimiters.
Syntax: <%! variable=0; %>
11. What is expression element?
Expression element are used to write dynamic content back to the client browser. It is used in place of out.print() method. Only expressions are supported inside the tag. Declarations of methods and variables is not possible inside this tag.
12. What happens to expression element during translation?
During translation the return type of expression goes as argument into out.print() method.
13. How to use expression element?
Expressions are embedded in <%= and %> delimiters.
Syntax: <% expression 1 %>
14. What are the two types of comments supported by JSP.
There are two types of comments supported by JSP:
HTML comment – <!—This is a comment –>
JSP comment – <%– This is a comment –%>
15. What is the difference between HTML and JSP comments?
HTML comments are passed during the translation phase and hence can be viewed in the page source in the browser. JSP comments are converted to normal java comments during the translation process and will not appear in the output page source.
16. How variable behaves defined inside a scriptlet element and declaration element?
Variable defined inside scriptlet are like method local variables once the method execution is complete the value stored would be lost. Variables defined inside declaration are like class level instance variables and values will be retained across user requests.
17. What is a JSP directive?
A directive provides meta data information about the JSP file to the web container. Web container uses this during the translation/compilation phase of the JSP life cycle.
18. Give few examples of JSP directives?
Examples of JSP directive are:
Importing tag libraries
Import required classes
Set output buffering options
Include content from external files.
19. What are the different types of JSP directives?
The JSP specification defines three directives:
Page directive: Provides information about page, such as scripting language that is used, content type, or buffer size etc.
Include directive: Used to include the content of external files.
Taglib directive: Used to import custom tags defined in tag libraries. Custom tags are typically developed by developers.
20. What is the syntax for JSP directive?
A JSP directive is declared using following syntax:
<%@directive attribute=”value” %>
Where, directive – The type of directive(page, taglib or include)
attribute – Represents the behavior to be set for the directive to act upon.
21. What is page directive in JSP?
The page directive is used to provide the metadata about the JSP page to the container. Page directives may be coded anywhere in JSP page. By standards, page directives are coded at the top of JSP page. A page can have any number of page directives.
Syntax: <%@page attribute1=”value” attribute2=”value” %>
22. What is the work of include directive?
This directive inserts a HTML file, JSP file or text file at translation time. The include process is not dynamic, it means that the text of the included file is added to the JSP file similar to copy pasting the contents.
23. Should included file in include directive containortags and why?
Included file should not containortags because the entire content of the included file is added to the main JSP file, these tags would conflict with the same tags in the main JSP file, causing an error.
24. How to create an include directive?
Include file is created using the following syntax:
<%@include attribute=”value”%> – Include can have only file attribute.
<%@include file=”value”%> – Where file specifies the relative path of the file to be included.
25. What are JSP implicit objects?
Implicit objects in JSP are the objects that are created by the web container automatically and the container makes them available to the JSP to access it. Implicit objects are available only inside the _jspService() method hence cannot be accessed anywhere outside.
26. List all the JSP implicit objects?
List of implicit objects are
request
response
session
application
page
pagecontext
out
config
exception.
27. Describe briefly about all the JSP implicit objects?
Request – It references to the current request.
Response – HTTPServletResponse object for the current request.
Session – It is the session associated with the current request.
Application – Servlet context to which a page belongs.
Page – An instance of JSP page’s servlet class that processes the current request.
Pagecontext – It is an object to access request, response, session and application associated with a page.
Out – Object that writes to the response output stream.
Config – Servlet configuration for the page.
Exception – This object is available in JSP pages where the page directive isErrorpage is set as true stating that it is an error page for some other JSP page.
28. What are the session management techniques in JSP?
The session management techniques used in servlets are also applicable to handle session in JSP also.
The following are the techniques used to manage session in JSP:
URL rewriting
Hidden field
Cookie
Session object
29. What is an expression language?
Expression language is a simple language for accessing data stored in java beans. This was introduced with the JSP 2.0 specification. It can also be used to access the values from implicit objects like page, context, header, cookie etc.
30. How expression language is specified?
Expression language is specified within curly braces and prefixed with a dollar sign.
Example: ${person.name}
Where ‘person’ is the java bean and ‘name’ is the java bean property.
31. What are the advantages of JSP Expression Language (EL) ?
Concise access to stored objects: Easy to access the attributes stored in session, request or application scope.
Example: ${name} search the PageContext, HTTPServletRequest, HTTPSession and ServletContext(in that order) for an attribute named name.
Equivalent to <%= pageContext.findAttribute(“name”) %>
Short hand notation for bean properties: Easy to access bean properties.
Example: To print the property phoneNumber of a user bean we can use
${user.phoneNumber} instead of <%= user.getPhoneNumber()%>
Easy access to collection elements: To access an element of an array, List, or Map, you use ${variable[index or key]}.
Example: Consider an arraylist myList
${myList[0]}, gets the first element in the list and prints it.
Easy access to request parameters, cookies, and other request data. In order to access the standard types of request data, you can use one of several predefined implicit objects.
Conditional output: To choose among output options, we don’t have to use java coding elements. Instead, you can use
${test ? option1 : option2}
32. What is the use of period (.) operator in JSP Expression Language (EL)?
To access implicit objects attributes:
For example, to read an attributemessage in sessionScope we use
${sessionScope.message}
To access bean properties:
Consider a bean named personhaving a property name which can be accessed as {person.name}
To access map values:
Consider a map named country having a key named “ind”. Value of the key can be accessed as ${country.ind}.
33. What is the use of [ ] operator in JSP Expression Language (EL)?
The [ ] operator can be used instead of the period operator.
To access be ${person[“name”]} reads the property named name in the person bean. Equivalent to ${person.name}.
To access map values: ${country[“ind”]} retrieves the value for the key ind in the country map. Equivalent to ${country.ind}.
To access elements from arrays and list: ${fruits[1]} retrieves the value at index 1 in the fruits array (list}.
34. How to read request parameter values using JSP Expression Language (EL)?
Request parameter values can be read as shown:
${param.userName} or ${param[“userName”]}
Reads the value of the parameter named userName set in the request. If a single request parameter name contains an array of values, example in the case of checkbox parameter. We use,
${paramValues.hobbies[0]}
Reads the first value of the check box hobbies.
35. How to read attributes in JSP Expression Language?
Take a scenario in which you need to access an attribute with name Username stored in some scope we use ${Username} searches the PageContext, HTTPServletRequest, HTTPSesson and ServletContext(in that order) for an attribute named Username. Suppose if we want to get the attribute with name ‘name’ in a specific scope say session, we use {sessionScope.name}.
36. How to access collection objects in JSP Expression Language?
Consider attributeName is a scoped variable referring to an array, List or Map, an entry in the collection can be accessed by ${attributeName[entryName]}.
37. How to deactivate expression language evaluation in JSP?
If your application requires EL to be ignored it can be done by setting the is EL ignored attribute to true in the page directive.
<%@ page isELIgnored=”true” %>
38. When to use JSP Expression Language?
EL should be used for accessing and presenting data from implicit objects. Don’t use EL operators and conditions for performing business logic which should be strictly done in business components.
39. What is server side java bean?
It is a class used to store the details of real world entities.
For Example,
Employee –> Employee Name and Employee Salary
Student –> Student Name and Student Address
Bean is a plain java class which contains
Fields or properties: Fields to store the data, example: Employee name, salary.
Methods: Methods for retrieving and modifying the attributes like setEmployeeName(), setStudentAddress. These methods are referred to as accessors/mutator.
40. What is the design conventions for Java Bean?
A Java Bean component property can be read/write, read-only, or write-only. The bean property needs to be accessible using public methods. For each readable property, the bean must have a method to retrieve the property value.
public Datatype get {
return value; //Returns the property value
}
For each writable property, the bean must have a method.
public void set(Datatype newValue)
{
Property=newValue; //sets the new value into the property
}
41. Why to follow naming conventions for java bean methods?
The web container maps the request attribute with the method names and triggers the appropriate methods for retrieving or setting the values.
For Example,
Request Attribute Name: empId
Method Triggered: setEmpId(), getEmpId()
Web container automatically capitalizes the first character of the attribute name and concatenates “set” or “get” to it for either setting or retrieving property values in bean.
42. How web container finds the properties and invokes the methods of java bean from JSP page?
Web container uses the reflection and introspection java api’s for finding the properties and methods of a class and invoking it dynamically.
43. What is the need of beans in JSP?
Need of beans in JSP are:
Beans are used to JSP for collectively storing some information.
Beans makes transfer of data between JSP’s easier.
For example, if you are handling with a registration form all the registration details can be loaded into a RegistrationBean and can be transported across other components as a single object.
44. What is JSP action tag?
JSP action tags are a set of predefined tags provided by the JSP container to perform some common tasks thus reducing the java code in JSP.
45. Mention some of the common tasks of JSP?
Some of the common tasks are:
Instantiate java bean object.
Setting values to beans.
Reading values from beans.
Forward the request to another resource.
Including another resource.
47. Mention action tags available in JSP?
The following are the action tags available in JSP:
jsp:include
jsp:forward
jsp:usebean
jsp:setProperty
jsp:getProperty
jsp:param
jsp:fallback
jsp:element
jsp:body
jsp:text
jsp:attribute
jsp:plugin
48. what is the use of jsp:include action tag?
It is used for dynamically including the pages. It includes the output of the included page during runtime. Contents of the page are not included, only the response is included. Assume that the following line is included in index.jsp
Here the response of myPage.jsp is included in the index.jsp.
49. what is the use of jsp:forward action tag?
The forward action tag is used to transfer control to a static or dynamic resource. The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a java servlet. The static or dynamic resource to which control has to be transferred is represented as a URL. The user can have the target file as a HTML file, another JSP file, or a servlet. For example,
Forwards the request to the success.jsp.
50. When jsp:forward is used in application?
It is used for forwarding request from one JSP to another resource. It provides the same functionality of the forward() method in RequestDispatcher Interface.
51. Explain jsp:param action tag with example?
The jsp:param action tag is used to add the specific parameter to current request. It can be used inside a jsp:include or jsp:forward. Consider a case in which on successful login the user needs to be forwarded to the success page with the user name set as an parameter to the request object so that name can be accessed in the home page and displayed.
Jsp:param can be used along with jsp:forward as shown below:

”/>
52. What is jsp:useBean action tag?
The tag attempts to locate a bean or if the bean does not exist, instantiates it from the class specified. Syntax:
Where,
id – The name used for referring bean object
Class – The bean class
Scope – The scope in which the bean object is available.
53. How jsp:useBean works?
For example: 
Sequence of steps:
Attempts to locate a bean with the name “userBean” in the request scope.
If it finds the bean, stores a reference in the variable user.
If it does not find the bean, instantiates a bean using the class userBean, and stores the reference to the variable user.
54. Name JSP bean object scopes and explain them briefly?
Bean object scopes are:
page: It is available only within the JSP page and is destroyed when the page has finished generating its output for the request.
request: It is valid for the current request and is destroyed when the response is sent.
session: It is valid for a user session and is destroyed when the session is destroyed.
application: valid throughout the application and is destroyed when the web application is destroyed/uninstalled.
55. Explain jsp:setProperty action?
The setProperty action sets the properties of a bean. The bean must have been previously defined before this action.
Syntax:
Where
name: The name of the bean object and should be the same as the id value specified in useBean.
property: the bean property (field name) for which the value is to be set. There should be a instance variable with the property name specified and accessors/mutator methods.
Value: The value to be set for the property.
56. What are the two options by which setProperty automatically set the values from an HTML form to a java bean?
The following options can be used to automatically set the values from an HTML form to a java bean using the setProperty action.
Option 1: 
Option 1: 
Sets the value of the HTML form element with the name userName into the bean UserBean’s property someProperty.
Option 2: 
Option 2: 
Sets all the values of the form elements into the bean properties. In this case the name of the property and the name of the form element should be the same.
57. Explain jsp:getProperty action tag with example?
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

Where,
Name: Bean name same as the id specified in the userbean action.
Property: The bean property name whose value is to be retrieved.
Example:

This reads the value of the property named userName from the userBean and prints it.
58. What is a custom tag?
Custom tags are nothing but tags which are developed by programmers for performing specific functionalities. For example:
Custom tag developed by programmers to print the current date in a specified format. The above tag when used in JSP will print the current system date.
59. Why JSP custom tags are required?
Any common code which needs to be reused across the web application can be developed using custom tags. It is easy to maintain as the logic is centralized. Any change to the logic just requires a one place change thus reducing the effort to change it.
60. What are the types of JSP custom tags and explain them briefly?
Simple tags: A simple tag contains no body and no attributes.
Tags with attributes: A custom tag can have attributes. Attributes are listed in the start tag and have the syntax: attributeName=”value”. Attribute are like configuration details for the custom tag.
Tags with bodies: A custom tag can contain custom, core tags, scripting elements and HTML text content between the start and end tag.

Related

Interview Questions 5868746591515592154

Post a Comment

emo-but-icon

item