rh banner

Saturday, 3 January 2015

JSP - Experienced Candidates Interview Question and Answers

JSP - Experienced Candidates Interview Question and Answers

Explain JSP and tell its uses.

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.

What are JSP lifecycle methods?

jspInit(): This method is declared in JspPage and it’s implemented by JSP container implementations. This method is called once in the JSP lifecycle to initialize it with config params configured in deployment descriptor. We can override this method using JSP declaration scripting element to initialize any resources that we want to use in JSP page.

_jspService(): This is the JSP method that gets invoked by JSP container for each client request by passing request and response object. Notice that method name starts with underscore to distinguish it from other lifecycle methods because we can’t override this method. All the JSP code goes inside this method and it’s overridden by default. We should not try to override it using JSP declaration scripting element. This method is defined in HttpJspPage interface.

jspDestroy(): This method is called by container when JSP is unloaded from memory such as shutting down application or container. This method is called only once in JSP lifecycle and we should override this method to release any resources created in JSP init method.

Which JSP lifecycle methods can be overridden?

We can override jspInit() and jspDestroy() methods using JSP declaration scripting element. We should override jspInit() methods to create common resources that we would like to use in JSP service method and override jspDestroy() method to release the common resources.

Difference between forward and sendRedirect?

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

How did you implement caching in JSP?

OSCache is an open-source caching library that's available free of charge from the OpenSymphony organization . OSCache has a set of JSP tags that make it easy to implement page caching in your JSP application.

Following are some Cache techniques it fulfills:-

Cache entry

An object that's stored into a page cache is known as a cache entry. In a JSP application, a cache entry is typically the output of a JSP page, a portion of a JSP page, or a servlet.

Cache key

A page cache is like a hash table. When you save a cache entry in a page cache, you must provide a cache key to identify the cache data. You can use keys like URI, other parameters like username, ipaddress to indentify cache data.

Cache duration

This is the period of time that a cache entry will remain in a page cache before it expires. When a cache entry expires, it's removed from the cache and will be regenerated again.

Cache scope

This defines at what scope the data is stored application or session scope. <%= new java.util.Date().toString() %>
The above tag says that refresh after every 60 seconds the user requests data. So if user1 s requesting the page it will display fresh date and if an other user requests with in 60 seconds it will show same data. If any other user requests the page after 60 second he will again see refreshed date.

Why to use the HttpServlet Init method to perform expensive operations that need only be done once?

Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.

What are the advantages of JSP over Servlet?

JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.

What are implicit objects in JSP?

Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:
request
response
pageContext
session
application
out
config
page
exception
The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

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.

Can we use the constructor, instead of init(), to initialize servlet? 

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

What is page directive?

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

What is the difference between include directive and include action?

Include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. Include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
Include directive is used to statically insert the contents of a resource into the current JSP. Include standard action enables the current JSP page to include a static or a dynamic resource at runtime.

How to pre-compile jsp?

Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile. http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes execution of JSP life cycle until jspInit() method without executing _jspService() method.

What is the difference between variable declared inside the declaration tag and variable declared in scriptlet?

Variable declared inside declaration part is treated as a instance variable and will be placed directly at class level in the generated servlet. Variable declared in a scriptlet will be placed inside _jspService () method of generated servlet. It acts as local variable.

What is the different scope available in jsp?

Page: Within the same page.
Request: After forward or include also you will get the request scope data.
Session: After sendRedirect also you will get the session scope data. All data stored in session is available to end user till session closed or browser closed.
Application: Data will be available throughout the application. One user can store data in application scope and other can get the data from application scope.

What are the standard actions available in JSP?

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: 
<jsp:include>: 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.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

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

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.

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

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.

Explain handling of runtime exceptions.

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.

Explain client and server side validation.

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.

How to read form data using JSP?

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.

How do you set cookies in the JSP?

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

How can you delete a session data?

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

What is a hit count for a web page?

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

How do you impement hit counter in JSP?

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.

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

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.