Friday, May 10, 2013

What is a JSP..? components of a JSP


JSP:

A Jsp refers to Java Server Pages, a dynamic web component runs inside server. A Jsp is also a servelt converted by jsp compiler.

According to Jsp specification every server vendor must have their own jsp compiler as part of server and their own servelt that extends HttpServlet.

As part of Tomcat we can observe HttpJspBase extending HttpServlet which is Tomcat's proprietary class to handle jsp's.

Jsp Compiler:

A Jsp compiler is a tool (program) as part of every server supporting jsp's which converts the jsp into corresponding servlet following jsp specification.

Jsp Life Cycle:

Similar to servlet, a jsp (which will be converted into servelt) can also be illustrated with the help of  life cycle methods.

jspInit(), _jspService() and jspDestroy() are the life cycle methods of a jsp.

jspInit() will be called immediately when the jsp(generated servlet) object is created and will be called only once .

For every client request to the jsp _jspService() will be called by the servlet container.

When the project got undeployed from the server, jspDestroy() will be called.



A jsp is a program which can contain different components as listed below.

--> Template text

--> Scriptlet

--> Jsp declarations

--> Jsp Expressions

--> Jsp Directives

--> Jsp action tags

--> Jsp custom tags

--> EL expressions

A Jsp file must have an extension of ' .jsp ' and all the jsp's as part of the web application will be placed outside WEB-INF folder. (only server can access files inside WEB-INF )

Template text:

Normal static text written in a jsp is called 'Template text'. What ever we write the template text as part of jsp, will be converted by jsp compiler into corresponding servlet code as shown.


That means, if we want to display normal text to user , we will use template text. Here, text which written in jsp is the template text. 


Scriptlet:

A scriptlet is used to write java code as part of jsp. Java code as part of jsp must be enclosed in a scriptlet (<% %>).

Syntax: 


Once we run the application, jsp compiler will convert the above code into corresponding servlet code and is placed inside _jspService().

It can be observed as part of the generated servlet by the jsp compiler,


Jsp Declarations:

A Jsp declaration is used to write instance / static variables and methods as part of Jsp.

The variable or(and) method declarations have to be written inside <%!  %>

Syntax:


Once jsp compiler converts this jsp into corresponding servlet, the above code will be placed outside the _jspService() and inside the generated servlet class.

The generated code by the jsp compiler will look like,


Jsp Expressions:

A Jsp expression is used to display the content available in a variable to the client.

The Java code has to be write inside Jsp Expression ( <%=  %> ), in order to display the content available in that variable.

Syntax:


Once Jsp compiler has converted the jsp into corresponding servlet, the above code will be placed as part of the generated servlet as shown.



Jsp Directives:

Jsp Directives are used to give instructions to the jsp compiler. <%@  %> represents a jsp directive.

Syntax:



Genearated Servlet by the jsp compiler:

Let's see the generated servlet by the jsp compiler corresponding to our jsp 'sample.jsp'



How and when the jsp is converted into servlet:

A jsp can be configured as part of web.xml as shown below.


If we didn't mention load-on-startup tag for the jsp, when we deploy the application server will read the contents of web.xml, but jsp compiler won't convert jsp into servlet.

When we send the request to the corresponding jsp, jsp compiler will convert the jsp (sample.jsp) into corresponding servlet by following jsp specification.

If we use load-on-startup tag for the jsp in web.xml,


Jsp compiler will convert the jsp into corresponding servlet when we deploy our application in the server. To the generated servlet, container will create object and call the life cycle methods initially jspInit(). It will be calles only once through out the life time of the jsp (converted servlet).

When the client sends the request to the jsp, every time container will call _jspService(). It will be called for every request.

jspDestroy() will be called by the servlet container only once , when the application has been undeployed from the server.


Note:

As per jsp specification, we should not write java code as part of a jsp, which means we should use tags instead of direct java code.

For this reason,components related to java code ( scriptlet, jsp declarations, jsp expressions which ) should be eliminated from jsp.

In place of java code we can use corresponding tags as part of jsp.

Jsp action tags, custom tags and EL expressions( non java code ) will resolve the problem of writing java code as part of jsp and will be discussed in next article



Thursday, May 9, 2013

Difference between RequestDispatcher and response.sendRedirect()

Using RequestDispatcher, we can send request to a resource (html,servlet or jsp) which is available in same application or different application running on the same server.

Suppose a resource (/requestR) is available in different application (ServletApp2) running on the same server, Create a project 'ServletApp' with a servlet, RequestDServlet.


To send request to a resource available in same server different application, we need to get the context path of that applicatio( ServletApp2 ).

Once we got the context path, we can get the RequestDispatcher object to send request to the resource (/requestR).

configure the servlet  in web.xml


Now create another project with the name 'ServletApp2' with a servlet RequestRServelt.


and configure the servlet in web.xml of ServletApp2


Now deploy both applications ServletApp and ServletApp2 in the same server.

Once we run the application ServletApp, we are able to forward the request from a resource '/requestD' to a resource 'requestR' available in different application of same server.

Note: In a security conscious environment, the servlet container may return null for a given URL , i.e we can't get the context path of other applications

If resource available in different server: 


Incase if the resource to which request has to be sent, is available in a different application which runs in a different server, then RequestDispatcher will not work to send the request.

response.sendRedirect("location"):


HttpServletResponse provides a method to redirect to any location within the project or outside the project.

response.sendRedirect("location"), will take a string parameter location which is the relative or absolute path of the resource to which request has to be redirected.

Change the RequestDServlet with sendRedirect() code,


Once if we run the application , request will be redirected to ServletApp2 application's resource (/requestR).

As part of location, we can give relative path as well as absolute path.

Difference between RequestDispatcher.forward() and response.sendRedirect():

Using RequestDispatcher, we can forward or include the request to a resource available in same application or difefrent application available in same server.

Using response.sendRedirect(), we can redirect the request to a resource available in same application or different application in same server or different server.

If the resource is available in different server , we can redirect the request by using 
response.sendRedirect("http:// ip: port/ Application name/Resource name")




Wednesday, May 8, 2013

RequestDispatcher and it's working with Relative,Absolute path

A RequestDispatcher is an object which receives the request from the client and sends (forward or include) the request to any resource ( a servlet, jsp or html).

RequestDispatcher is an interface available as part of javax.servlet package. A servlet container will creates the RequestDispatcher object.

As RequestDispatcher is an interface, it can't directly create the object . Container will creates the object to it's (RequestDispatcher) implementation class. 

The class name will differ from server to server as every server should implement servlet api they chose proprietay names to the implementation classes.

Incase of Tomcat the implementation class to RequestDispatcher is ApplicationDispatcher . you can get more information from here.

Once we got RequestDispatcher object we can perform two operations.

forward (request, response) and
include (request, response).

Getting RequestDispatcher object:

There are mainly three ways to get the RequestDispatcher object created by the servlet container.

1. Using ServletContext.getRequestDispatcher("/path"):

Once we have ServletContext object we can get the RequestDispatcher object by using context.getrequestDispatcher("/path"). where path is the absolute path of the resource to which we want to send the request.

Here is the example.

RequestDServlet is the one which will send request to another resource.


in above servlet,' /requestR ' is the absolute path of the resource (RequestRServlet) to which request has to be sent.

forward(request, response) will through ServletException,IOException. That's why we have placed that code in try catch block.

RequestRServlet is the servlet which will receive request from RequestDServlet with the help of RequestDispatcher.


Configure both servlets in web.xml


If we run the application , we will get output showing text "Request Dispatcher Dispacthed the REQUEST" as the request is forwarded to RequestRServlet.

We can perform include() operation too , will be discussed in next way of getting RequestDispatcher.

2. ServletContext.getNamedDispatcher("name"):

This is another way of getting RequestDispatcher if we have ServletContext object.

The only change we need to do is in RequestDServlet .


getNamedDispatcher("name") will accept name of resource to which request has to be sent.

include(request, response) will include the contents of both resources and display to the client.

3. ServletRequest.getRequestDispatcher("path"):

If we have a request object, we can get the RequestDispatcher object from
request.getRequestDispatcher("path"), where path refers to absolute or relative path of the resource to which request has to be sent.

Again, the change only we need to do in RequestDServlet.


Here, two types of paths we can give to the request.getRequestDispatcher().
If we give '/path' it will be considered as absolute path and if we mention "path" it will be treated as relative path.

Absolute path and Relative path :

Absolute path is the exact path showing the location of resource where it is available.

example:' /ServletApp/requestR ' or ' /requestR'

Server will get's the context path (/ServletApp) and appends the path (/requestR) to it.

Relative path is the path relative to the current path of the resource.

example: ' requestR '

Server will get's the current path of the resource executing, i.e,(/ServletApp/requestD) and get's the context path from that (/ServletApp/) by removing resource path (requestD) . Finally it will append the resource to which request has to be sent (requestR).

Note:

We can use any resource (html, jsp, servlet) to forward or include the request with RequestDispatcher.



Tuesday, May 7, 2013

servlets based on GenericServlet and HttpServlet

javax.servlet.GenericServlet and javax.servlet.http.HttpServlet are the implementation classes of javax.servlet.Servlet

If we write a servlet based on javax.servlet.Servlet every time we need to provide implementation to all abstract methods of Servlet interface as part of our servlet. Instead of that Sun microsystems has implemented Servlet and released as GenericServlet and HttpServlet.

servlet's based on GenericServlet class:

GenericServlet is an abstract class available as part of javax.servlet package. As part of GenericServlet all abstract methods are implemented except service().

Here is the sample code of GenericServlet(source code)


Here GenericServlet is implementing all the abstract methods except service(). That's why it was declared as abstract class.

We can found two init() methods ( init(ServletConfig config) and init() ) as part of GenericServlet.

init(ServletConfig config) is the first init method and servlet container always calls this method which internally calls the second init method ( init() ).

If we want to perform some task when ever servlet object got created , we need to write code as part of init(). Our servlet will override init(), but container will always call init(ServletConfig config) of GenericServlet, which will call init() of our servlet.

If we create a class extending GenericServlet, it is also known as a servlet  since it is implementing javax.servlet.Servlet interface indirectly.

Here is our servlet based on GenericServlet.


We are implementing abstract method (service()) in our servlet ( SampleServlet ).

Just override init() of GenericServlet in SampleServlet.


So if we observe, when ever container created the object to SampleServlet, it will call init() of SampleServlet instead of init() of GenericServlet since we have overridden the method.

Why init() over init(ServletConfig config) :

It's easy and recommended to override init() than init(ServletConfig config) since there is no need to call super.init(config) if we use init().

Without having ServletConfig object we can simply override init() which will be called by init(ServletConfig config).

servlet's based on HttpServlet class:

HttpServlet is an abstract class available as part of javax.servlet.http package.

Here is the source code of HttpServlet implementation .


As part of HttpServlet service() was implemented as it is abstract as part of GenericServlet.

In HttpServlet two service methods were implemented. service(ServletRequest request, ServletResponse response) is the first service() and service(HttpServletRequest request, HttpServletResponse response) is the second service().

Also doXXX() were provided as part of HttpServlet for every request type (GET,POST,PUT ..etc).

Why two service():

If we use first service(), i.e service(ServletRequest request, ServletResponse response) incase of http request handling we need to type cast ServletRequest , ServletResponse into HttpServletRequest, HttpServletResponse in order to access the methods of HttpServletRequest, HttpServletResponse.

So every time type casting and repeating the same code is not recommended. That's why HttpServlet itself providing two service(), and it's always recommended to use second service(), i.e service(HttpServletRequest request, HttpServletResponse response) as part our servlet .

Here is our servlet(SampleServlet) based on HttpServlet.


We are overriding second service() as part of SampleServlet. Container will always call first service(), i.e service(ServletRequest request, ServletResponse response) which internally calls second service() of SampleServlet.

So, Whenever we are writing a servlet it's always recommended to override second init and second service methods, and container will always call first initand first service methods.


Which one to use either GenericServlet or HttpServlet:

It's always recommended to use HttpServlet while developing servlets because if we use Generic Servlet we need to implement service(ServletRequest request, ServletResponse response) with which we cant access the methods of HttpServletRequest and HttpServletResponse. 
 Every time we need to type cast  ServletRequest,ServletResponse into HttpServletRequest ,HttpServletResponse to access them.

What happens if we did not override any method:

If we have not provided any method as part of our servlet just like as shown.



When client sends the request to the SampleServlet as we have not provided init() container will call init(ServletConfig config) of GenericServlet which internally calls init() of GenericServlet. As part of init() in GenericServlet nothing was coded.

As service() was not overridden as part of SampleServlet, container will call first service of super class(HttpServlet) which internally calls second service() of HttpServlet.

As part of second service() of HttpServlet , calling doXXX() has provided. So if we don't override any method as part of our servlet (SampleServlet), doXXX() will be called based on request method type. If it is GET, it will display error message GET METHOD NOT SUPPORTED  which is available as part of doGet().

So as per the servlet specification we need to override atleast one of these methods :

init(),
destroy(),
service(),
doGet(),
doPost(),
doDelete(),
doPut().


Monday, May 6, 2013

Basic information of a servlet and servlet container

What's a Servlet :

A Servlet is a normal java program which provides the implementation of javax.servlet.Servlet interface.

We can also define as a server side program which handles all the requests from the client. For this reason frameworks that follows MVC design pattern will consider a servlet as controller.

Example for servlet: 

Here is a servlet program which is implementing javax.servlet.Servlet interface.


We have created our own servlet SampleServlet by implementing Servlet interface. As we are familiar with interfaces, we need to provide implementation to all abstract methods of interface in the corresponding implementation class.

So we are implementing all the abstract methods( init(), service(), destroy(), getServletConfig() and getServletInfo() ) as part of our SampleServlet.

We need to configure our servlet as part of deployment descriptor( web.xml ) in order to access from the client. 


A servlet is defined with the help of servlet tag whose child tags describes the name of servlet and class.

To use our servlet as part of our application we need to give url pattern to the servlet as mentioned.

What happens when we deploy our project:

When we deploy our project in the server, server will start parsing web.xml with the help of parsers(SAX,DOM) in it. while parsing the xml if it founds any error it will throw exception. If everything fine, then server will check for the servlet class we have defined in the web.xml.

If it doen't found the class in the class path it will through ClassNotFoundException. If it finds the class, then server will loads the class into the jvm memory and creates servlet's ( SampleServlet) object as we have mentione load-on-start up tag.

What is a ServletContainer:

The implementation of servlet api as part of the server will be known as servlet container. Every server need to provide implementation of servlet api to run the servlets as part of the server. A servlet container is a part of web/application server to handle servlets. A servlet's life cycle methods will be called by the servlet container.

Servlet life cycle :

Life cycle describes when the servlet object gets created and when it will be removed by calling appropriate methods.

init(), service() and destroy() are the life cycle methods of a servlet.

When we deploy our project servlet container will creates object to our servlet and immediately it will call init() of our servelt.

init() will be calles only once through out the life cycle of the servlet. So when the object is created what ever the task which we want to perform only once, will do as part of init(). examples are opening a file, opening database connection etc.

Now when ever client sends the request to the server to access our servlet, just like http://ip address:server port/ServletApp/ servlet container will call service() of SampleServlet. 

For every request from the client container will call service() of our servlet. so service() will be called any number of times based on the request from the client.

For every request what ever the task which we want to perform , will be provided as part of service().

Now, when the project is undeployed from the server , servlet container will call the destroy() and removes the servlet object from the jvm memory.

destroy() will be called only once and as part of destroy we will provide code to close connections, files, clean up memory (removing objects) etc.

After destroy() got called, container will not call service() as there is no servlet object.

getServletConfig() will return ServletConfig object by using which we can get the details of servlet like class, name of servlet etc.

getServletInfo() will return  string information like version,author etc. related to the servlet.


Working with GenericServlet and HttpServlet's will be discussed in next article.