Você está na página 1de 11

Question 1: What is JSESSIONID in Java? When does JSESSIONID gets created?

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 then client sends it back to server in subsequent http
requests.
When JSESSIONID created in Web application?
In Java J2EE application container is responsible for Session management and by default uses Cookie.
When a user first time access your web application, session is created based upon whether its accessing
HTML, JSP or Servlet. If user request is served by Servlet than session is created by
calling request.getSession(true) method. it accepts a boolean parameter which instruct to create session if
its not already existed. If you call request.getSession(false) then it will either return null if no session is
associated with this user or return the associated HttpSession object. If HttpRequest is for JSP page
than Container automatically creates a new Session with JSESSIONID if this feature is not disabled
explicitly by using page directive %@ page session="false" %>. Once Session is
created Container sends JSESSIONID cookie into response to the client. In case of HTML access, no user
session is created. If client has disabled cookie than Container uses URL rewriting for managing session
on which jsessionid is appended into URL as shown below:
https://localhost:8443/supermart/login.htm;jsessionid=1A530637289A03B07199A44E8D531427

When HTTP session is invalidated(), mostly when user logged off, old JSESSIONID destroyed and a
new JSESSIONID is created when user further login.

How to monitor HTTP request to check JSESSIONID
You can check value of JSESSIONID coming in as cookie by monitoring HTTP request. If you are
running Tomcat Server in NetBeans IDE in your development environment than you can use HTTP
Server Monitor to check http requests. You just need to enable it while starting Tomcat Server form
Netbeans. After than with each request you can see all details like request headers, session, cookies etc in
HTTP Server monitor screen. If you look on JSESSIONID cookie it will look like:
cookie JSESSIONID=1A530637289A03B07199A44E8D531427
You can also enable http request and response in Client side by using tools like ethereal or Wireshark.
This tool can monitor all http traffic from and to your machine and by looking on request data you can
see JSESSIONID cookie and its value.

Question 2: What is difference between include action and include directive in JSP?

Both include directive and include action is used to include output of a static page e.g. html or a dynamic
page e.g. jsp inside another jsp file.
Include action vs. Include directive in JSP
In this section we will in detail how pages are included using include action and directive, how JSP pages
are translated into Servlet and how to use include action and directive along with couple of difference
between them.

How Java Server Pages (JSP) Work?

Before discussing about include directive or include action its worth remembering that how JSP pages
works inside servlet container. When a request is come for JSP page, that JSP page first translated
into Servlet class and then that servlet gets compiled and loaded into heap memory by web container.
Code written using JSP declaration e.g. <%!&gt; goes into body of generated servlet as instance
variable and all code from body goes into service() method of generated Servlet. In case of tomcat web-
server these generated servlet files goes inside work directory. In short JSP pages has three steps to get
executed translation-->Compilation -->Execution. Also JSP file will only be re-compiled only if there is a
change in JSP file.
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 then 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. 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>
Question 3: How do you define application wide error page in JSP?
There are two ways to define Error page in Java web application written using Servlet and JSP. First
way is page wise error page which is defined on each jsp page and if there is any
unhanded exception thrown from that page, corresponding error page will be displayed. Second
approach is an application wide general or default error page which is shown if any Exception is
thrown from any Servlet or JSP and there is no page specific error page defined.

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.

Question 4: Difference between sendredirect and forward in Servlet?
This is not just applicable for servlet but also for JSP in which we can use forward action or call
sendRedirect() method from scriptlet. Before examining difference on forward and SendRedirect lets see
what send Redirect method and forward method does.

SendRedirect ():

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

This method is used to redirect client request to some other location for further processing, the new
location is available on different server or different context. Our web container handle this and transfer
the request using browser, and this request is visible in browser as a new request. Sometime this is also
called as client side redirect.
Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)

This method is used to pass the request to another resource for further processing within the same
server, another resource could be any servlet, jsp page any kind of file. This process is taken care by
web container when we call forward method request is sent to another resource without the client being
informed, which resource will handle the request it has been mention on requestDispatcher object which
we can get by two ways either using ServletContext or Request. This is also called server side redirect.


RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
rd.forward(request, response);

Or

RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);

Difference between SendRedirect and Forward
Now lets see some difference between these two method of servlet API in tabular format.

Forward() SendRediret()
When we use forward method request is
transfer to other resource within the same
server for further processing.
In case of sendRedirect request is transfer to
another resource to different domain or
different server for further processing.

In case of forward Web container handle all
process internally and client or browser is not
involved.

When you use SendRedirect container transfers
the request to client or browser so url given
inside the sendRedirect method is visible as
a new request to the client.

When forward is called on requestDispatcher
object we pass request and response object so
our old request object is present on new
resource which is going to process our request

In case of SendRedirect call old request and
response object is lost because its treated as
new request by the browser.
Visually we are not able to see the forwarded
address, it is transparent
In address bar we are able to see the new
redirected address its not transparent.

Using forward () method is faster then send
redirect.
SendRedirect is slower because one extra
round trip is required because completely new
request is created and old request object is lost.
Two browser request required.

When we redirect using forward and we want
to use same data in new resource we can use
request.setAttribute () as we have request
object available.
But in sendRedirect if we want to use we have
to store the data in session or pass along with
the URL.



Example of forward and SendRedirect in JSP Servlet:
Any kind of online payment when we use merchant site will redirect us to net banking site which is
completely new request it process our request and again redirect to merchant site?

In Banking Application when we do login normally we use forward method. In case of online banking we
are asked for username and password if its a correct some another servlet or resource will handle the
request otherwise request has been forwarded to error page.
Which one is good?
Its depends upon the scenario that which method is more useful.

If you want control is transfer to new server or context and it is treated as completely new task then we go
for Send Redirect.
Normally forward should be used if the operation can be safely repeated upon a browser reload of the web
page will not affect the result.

Question 5: How do remove variable using <c:set> tag from JSTL?
JSTL set tag or <c:set> also called as JSTL Core tag library is a good replacement
of <jsp:setProperty> jsp action which lacks lot of functionality and only allow you to set bean property.
You cannot set Map's key value or create a scoped variable by using <jsp:setProperty>. jstl <set> tag
allows you to do all the stuff related to setting or creating variables or attributes. By using
JSTL <c:set> tag you can :
1) Set bean properties
2) Set Map values
3) Create Scoped variable on page, request, session or application scope.
JSTL Core <c:set> tag
As I said earlier JSTL Set tag or <c:set> is use to set bean properties, map value and to create scoped
variables. <c:set> can be used in two different ways either by using "var" or by using "target". Var is
used to define name of variable needs to be created or whose values needs to be set. While "target" is
used to denote Bean Object or Map whose values needs to be set. Here is a simple example of
JSTL <c:set> tag
<c:set var="currency" value="USD" />
JSTL Example: How to create variable in session scope using <c:set> tag in JSP
Above example of <c:set> will create an attribute named "currency" with value "USD" in default
scope which is page scope. you can also create attribute into another scope say session scope, in that case
you need to specify scope with <c:set> attribute scope="". Here is an example of creating variable on
session scope using jstl set tag:

<c:set var="currency" value="USD" scope="session" />

Value of variable can also be a runtime expression e.g. jsp expression or EL expression. Like the one
which is shown in below example of set tag:

<c:set var="currency" value="${user.currency}" scope="session" />

Here Container will copy bean property user.currency in "currency" variable.
JSTL Example: How to pass value in <c:set> tag body in JSP
Another variance of jstl <c:set> tag is that you can supply value in body instead of on attribute line. Some
time when value is long, giving it on body makes code more readable. Here is example of supplying value
on jstl set tag body:

<c:set var="currency" scope="session" >
USD, EUR, AUD,INR
</c:set>

JSTL Example: How to remove attribute using <c:set> in JSP
Keep in mind that <c:set> can also remove a variable or attribute if value resolves to "null" during
runtime. e.g. in below example

<c:set var="currency" value="${user.currency}" />

<c: set> tag of jstl will remove "currency" attribute from any scope if EL expression ${user.currency}
will resolve to null.
JSTL Example: How to set bean property using JSTL <c:set> tag in JSP
All of above example were for setting attribute or creating variables, but <c:set> can also be used to
set bean properties or map value. In that case instead of "var" we need to use "target" and "property"
which will define bean and property name to be set. If "target" is map than "property" is name of key and
"value" is value for that key. What is worth noting here is that <c:set target=""> must point to a real
object and not the name of object as it was with <jsp:useBean> action. If "target" doesn't resolve into
object than web container will throw exception. Here is example of setting bean property using
JSTL <c:set> tag in JSP:

<c:set target="currencyMap" property="USA" value="USD">

This is equivalent to currencyMap.put("USA", "USD"); just like before you can also supply value in body
of jst <c:set> tag in jsp. here is another example of setting bean properties using JSTL <c:set> tag :

<c:set target="trade" property="currency" value="USD">

This example will set currency property of bean named "trade" and equivalent to:
trade.setCurrency("USD");

You just need to make sure that target should resolve into real object.
JSTL <c:set> - Points to remember
Here are few important points to remember on <c:set> tag from JSTL core tag library. I have seen we
often overlooked these small subtle details which causes hard to find bugs in JSP:

1) <c:set> can remove attribute if value="null".
2) Value for JSTL <c:set> tag can be specified in body also.
3) JSTL set tag value can be runtime expression include JSP expression or EL expression.
4) In target version of <c:set> if target is pointing to bean and property is not valid property container
will throw exception.
5) If variable pointed by "var" doesn't exists than JSTL <c:set> tag creates it for you only if value is not
null.
6) Scope attribute is optional in JSTL <c:set> tag and default scope is page scope.

These were some examples of JSTL core <c:set> or set tag. <c:set> is very convenient and provides
lots of key functionality required in JSP pages. I recommend using <c:set> over <jsp:property> or JSP
actions.

Você também pode gostar