What is JSESSIONID in J2EE Web application - JSP Servlet?

JSESSIONID is a cookie generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting. If Web server is using cookie for session management it creates and sends JSESSIONID cookie to the client and than client sends it back to server in subsequent http requests


Difference between include directive and include action in JSP Servlet?

What is include directive in JSP

Include directive in JSP is used to import a static file or dynamic file e.g. JSP inside another JSP. Most common example of include directive is including header and footer in JSP. Include directive is also called file include because resource to be included is specified using file attribute as shown in below example of include directive:

<%@ include file="loan.jsp" %>

The code written in loan.jsp will be included as it is in the jsp file which included it during JSP translation time and than merged code is get compiled to generate Servlet which is later used to server request. Include directive is also refereed as static import and it acts like #include from C or C++. file attribute is used specify resource to be included and can be specified in either relative url or absolute url. Since resource included using include directive is included during translation time and jsp doesn't compile if there is any change in included file. So include directive is not suitable to include dynamic resources because if included file changes between multiple request only old value is used always. include action is better choice for including dynamic resource which we will see in next section.

What is include action in JSP

Include action in JSP is another way of including a jsp file inside another jsp file. Included resource is specified using page attribute as shown in below example :

<jsp:include page="loan.jsp" %>

here contents of loan.jsp will be included during request time instead of translation time and any change in loan.jsp will reflect immediately. Due to this nature include action is also called dynamic include in JSP. It also referred as page include because of page attribute used to specify included resource.

Difference between include directive and include action in JSP

include directive is <%@ include file="loan.jsp" %> and include action in JSP is <jsp:include page="loan.jsp" %>
As I said earlier this is one of popular servlet jsp interview question and mostly asked to Junior or mid senior Java programmers during interviews. Following are some common differences between include action and include directive in JSP:

1. Resource included by include directive is loaded during jsp translation time while resource included by include action is loaded during request time.
2. Any change on included resource will not be visible in case of include directive until jsp file compiles
again. While in case of include again any change in included resource will be visible in next request.
3. include directive is static import while include action is dynamic import
4. include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

5.  Another difference suggested by N. Satish babu in comment section is that value of the attribute to  JSP include action can be  dynamic and request time expression and you can also pass parameter to the file which you are going to include using include action e.g.

<jsp:include page="header.jsp">
<jsp:param name="some" value="thing"/>
</jsp:include>


 How do you define application wide error page in JSP?

Page Specific Error page in JSP

Every JSP page has an attribute called "errorpage" on page directive, by using this attribute you can define an error page for any particular JSP. After that if any unhandled Exception thrown from that JSP , this error page will be invoked. In order to make any JSP page as an error page you need to use "isErrorPage" attribute of page directive and mark it true. For example in below JSP pages error.jsp is an error page which can be used to display custom error messages if any unhandled exception is thrown from login.jsp (because it is defined as errorpage for login.jsp)

//error.jsp
<%@ page isErrorPage="true"%>

//login.jsp
<%@ page errorPage="error.jsp"%>

This is preferred way of showing error messages in Java web application if you have custom error messages based on JSP and it also supersede any application wide error page defined in web.xml.

Error page in Java Web Application JSP Servlet

Application wide Error page in Java web application

There is another way to define error pages in java web application written using servlet and JSP. This is called application wide error page or default/general error page because its applicable to whole web application instead of any particular servlet or JSP. Its recommended practice for every Java web application to have a default error page in addtion of page specific error pages. This error page is defined in web.xml by using tag <error-page><error-page> allows you to define custom error message based upon HTTP error code or any Java Exception. you can define a default error message for all exception by specifying <exception-type> as java.lang.Throwable and it would be applicable to all exception thrown form any Servlet or JSP from web application. here is an example of declaring default error page in Java web application based on HTTP Error code and Java Exception type.


Default Error page based on Exception type:

<error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/error.htm</location>
</error-page>


Default Error page based on HTTP Error code:
<error-page>
    <error-code>500</error-code>
    <location>/internal-server-error.htm</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/page-not-found-error.htm</location>
</error-page>

That's all on how to define custom error page in Java application both page specific and an application wide default error page.Important point to note is that page specific error pages takes precedence over application wide default error page defined in web.xml.


Application Server vs Web Server


1. Application Server supports distributed transaction and EJB. While Web Server only supports Servlets and JSP.
2. Application Server can contain web server in them. most of App server e.g. JBoss or WAS has Servlet and JSP container.

3. Though its not limited to Application Server but they used to provide services like Connection poolingTransaction management, messaging, clustering, load balancing and persistence. Now Apache tomcat also provides connection pooling.

4. In terms of logical difference between web server and application server. web server is supposed to provide http protocol level service while application server provides support to web service and expose business level service e.g. EJB.

5. Application server are more heavy than web server in terms of resource utilization.

Personally I don't like to ask questions like Difference between Application Server and Web Server. But since its been asked in many companies, you got to be familiar with some differences. Some times different interviewer expect different answer but I guess on Java's perspective until you are sure when do you need an application server and when you need a web server, you are good to go.


Difference between URL Rewriting and URL Encoding in JSP Servlet

You often need to encode URL before sending it to server and need to rewrite URL with session id in order to maintain session where cookie is not present. here are some more differences between URL-rewriting and URL encoding in Servlet JSP

1) java.servlet.http.HttpServletResponse methods encodeURL(String url) and encodeRedirectURL(String URL) is used to encode SesssionID on URL to support URL-rewriting. don't confuse with name encodeURL() because it doesn't do URL encoding instead it embeds sessionID in url if necessary. logic to include sessionID is in method itself and it doesn't embed sessionID if browser supportscookies or session maintenance is not required. In order to implement a robust session tracking all URL from Servlet and JSP should have session id embedded on it.

In order to implement URL-rewriting in JSP you can use use JSTL core tag all URL passed to it will automatically be URL-rewriting if browser doesn't support cookies.

While java.net.URLEncoder.encode() and java.net.URLDecoder.decode()is used to perform URL Encoding and decoding which replace special character from String to another character. This method uses default encoding of system and also deprecated instead of this you can use java.net.URLEncoder.encode(String URL, String encoding) which allows you to specify encoding. as per W3C UTF-8 encodingshould be used to encode URL in web application.

2) In URL rewriting session id is appended to URL and in case of URL-encoding special character replaced by another character.

That's all on difference between URL-rewriting and URL-encoding, let me know if you come across some more differences between these URL Encoding vs URL-rewriting in Servlet and JSP.


Which open source tag library have you used ?


This is an interesting Servlet JSP questions and gives an opportunity to show how many tag library you are familiar with and which ones have you used. Most J2EE programmer answer this question with saying JSTL core tag library, Struts tag library , Spring tag library or display tag, which is quite popular tag library to display tabular data and provides lot of feature out of box e.g. paging, sorting and export functionality.


Questions : 1Can you explain What is JSP page life cycle?
Answers : 1
When first time a JSP page is request necessary servlet code is generated and loaded in the servlet container. Now until the JSP page is not changed the compiled servlet code serves any request which comes from the browser. When you again change the JSP page the JSP engine again compiles a servlet code for the same.
JSP page is first initialized by jspInit() method. This initializes the JSP in much the same way as servlets are initialized, when the first request is intercepted and just after translation.

Every time a request comes to the JSP, the container generated _jspService() method is invoked, the request is processed, and response generated.

When the JSP is destroyed by the server, the jspDestroy() method is called and this can be used for clean up purposes.
  
Questions : 2What is EL ?
Answers : 2
EL stands for expression language. An expression language makes it possible to easily access application data.In the below expression amountofwine variable value will be rendered. There are ${amount} litres of milk in the bottle.
  
Questions : 3how does EL search for an attribute ?
Answers : 3
EL parser searches the attribute in following order:
Page
Request
Session (if it exists)
Application
If no match is found for then it displays empty string.
  
Questions : 4What are the implicit EL objects in JSP ?
Answers : 4
Following are the implicit EL objects:-
PageContext: The context for the JSP page.
Provides access to various objects for instance:-
ervletContext: The context for the JSP page's servlet and any web components contained n the same application.
ession: The session object for the client.
equest: The request triggering the execution of the JSP page.
esponse: The response returned by the JSP page. See Constructing Responses.
n addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie

initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
Browser: ${header["user-agent"]}
  
Questions : 5How can we disable EL ?
Answers : 5
We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %> .
  
Questions : 6what is JSTL ?
Answers : 6
JSTL is also called as JSP tag libraries. They are collection of custom actions which can be accessed as JSP tags.
  
Questions : 7what the different types of JSTL tags are ?
Answers : 7
Tags are classified in to four groups:-
Core tags
Formatting tags
XML tags
SQL tags
  
Questions : 8How can we use beans in JSP?
Answers : 8
JSP provides three tags to work with beans:-
< jsp:useBean id=“bean name” class=“bean class” scope = “page | request | session |application ”/>

Bean name = the name that refers to the bean. Bean class = name of the java class that defines the bean.
< jsp:setProperty name = “id” property = “someProperty” value = “someValue” / > id = the name of the bean as specified in the useBean tag. property = name of the property to be passed to the bean. value = value of that particular property .
< jsp:getProperty name = “id” property = “someProperty” />

Here the property is the name of the property whose value is to be obtained from the bean.Below is a code snippet which shows how MyUserClass is used and the values accessed.
< jsp:useBean id="user" class="MyUserClass" scope="session"/>
< HTML>
< BODY>
You entered< BR>
Name: <%= user.getUsername() %>< BR>
Email: <%= user.getEmail() %>< BR>
  
Questions : 9) What is the use of ?
Answers : 9
It includes the output of one JSP in to other JSP file at the location of the tag. Below is the syntax for the same:-
< jsp:include page="..some.url.." flush="true or false"/>-
page: A URL that is relative to the current JSP page at request time-
flush: Determines if the buffer for the output is flushed immediately, before the included page's output. 

  
Questions : 10What is < jsp:forward> tag for ?
Answers : 10
It forwards the current request to another JSP page. Below is the syntax for the same:-
< jsp:forward page="...url..." />
We can also forward parameter to the other page using the param tag
< jsp:forward page="..url...">
< jsp:param ..../>
  
Questions : 11What are JSP directives ?
Answers : 11
JSP directives do not produce any output. They are used to set global values like class declaration, content type etc. Directives have scope for entire JSP file. They start with <%@ and ends with %>. There are three main directives that can be used in JSP:-
page directive
include directive
taglib directive
  
Questions : 12How do we prevent browser from caching output of my JSP pages?
Answers : 12
WE can prevent pages from caching JSP pages output using the below code snippet. <%response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>
  
Questions : 13How did you implement caching in JSP?
Answers : 13
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.
  
Questions : 14what are Page directives?
Answers : 14
Page directive is used to define page attributes the JSP file. Below is a sample of the same:- <% @ page language="Java" import="java.rmi.*,java.util.*" session="true" buffer="12kb" autoFlush="true" errorPage="error.jsp" %>
To summarize some of the important page attributes:-
import :- Comma separated list of packages or classes, just like import statements in usual Java code.
session :- Specifies whether this page can use HTTP session. If set "true" session (which refers to the javax.servlet.http.HttpSession) is available and can be used to access the current/new session for the page. If "false", the page does not participate in a session and the implicit session object is unavailable.
buffer :- If a buffer size is specified (such as "50kb") then output is buffered with a buffer size not less than that value.
isThreadSafe :- Defines the level of thread safety implemented in the page. If set "true" the JSP engine may send multiple client requests to the page at the same time. If "false" then the JSP engine queues up client requests sent to the page for processing, and processes them one request at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet.
rrorPage: - Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing.
  
Questions : 15How does JSP engines instantiate tag handler classes instances?
Answers : 15
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.
  
Questions : 16what’s the difference between JavaBeans and taglib directives?
Answers : 16
JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them:-
Taglib 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.
  
Questions : 17what are the different scopes an object can have in a JSP page?
Answers : 17There are four scope which an object can have in a JSP page:-
Page Scope
Objects with page scope are accessible only within the page. Data only is valid for the current response. Once the response is sent back to the browser then data is no more valid. Even if request is passed from one page to other the data is lost. Request Scope
Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available though not if a redirect is required. Session Scope
Objects with session scope are accessible in same session. Session is the time users spend using the application, which ends when they close their browser or when they go to another Web site. So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out. Application Scope
Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that's available to all pages. Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application.
  
Questions : 18what are different implicit objects of JSP?
Answers : 18
Below are different implicit objects of JSP
pageContext :- The PageContext object.
pageScope :- A Map of all the objects that have page scope.
requestScope :- A Map of all the objects that have request scope.
sessionScope :- A Map of all the objects that have session scope.
applicationScope :- A Map of all the objects that have application scope.
param :- A Map of all the form parameters that were passed to your JSP page (for example, the HTML < input name="someName" type="text"/> is passed to your JSP page as a form parameter).
paramValues :- HTML allows for multiple values for a single form parameter. This is a Map of all the parameters, just like param, but in this object the values are an array containing all of the values for a given parameter in the event that there's more than one. header :- A Map of all the request headers.
headerValues :- For the same reasons as paramValues, a headerValues object is provided.
cookie :- A Map of all the cookies passed to your JSP. The value returned is a Cookie object.
initParam :- A Map that maps context initialization parameter names to their parameter values.



Leave a Reply

Subscribe to Posts | Subscribe to Comments

About This Site

Howdy! My name is Suersh Rohan and I am the developer and maintainer of this blog. It mainly consists of my thoughts and opinions on the technologies I learn,use and develop with.

Blog Archive

Powered by Blogger.

- Copyright © My Code Snapshots -Metrominimalist- Powered by Blogger - Designed by Suresh Rohan -