MARQUEE

this blog is only for the important notes for the paper solving systematic created by RANJEET TIWARI.

facebook page

Wednesday, 21 February 2018

Web technology 2

Java Servlet






Application server: An application server is a server program in a computer in a distributed network that provides the business logic for an application program. The application server is frequently viewed as part of a three-tier application, consisting of a graphical user interface (GUI) server, an application (business logic) server, and a database and transaction server. More descriptively, it can be viewed as dividing an application into:

1.A first-tier, front-end, Web browser-based graphical user interface, usually at a personal computer or workstation.

2.A middle-tier business logic application or set of applications, possibly on a local area network or intranet server.

3.A third-tier, back-end, database and transaction server, sometimes on a mainframe or large server
Architecture of  APPLICATION Server.

1.What is a Web server definition?

A web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer to the entire system, or specifically to the software that accepts and supervises the HTTP requests.

Web server is a computer where the web content is stored. Basically web server is used to host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc.
Web site is collection of web pages while web server is a software that respond to the request for web resources.

Web Server Working

Web server respond to the client request in either of the following two ways:

•Sending the file to the client associated with the requested URL.

•Generating response by invoking a script and communicating with database
Key Points

•When client sends request for a web page, the web server search for the requested page if requested page is found then it will send it to client with an HTTP response.

•If the requested web page is not found, web server will the send an HTTP response:Error 404 Not found.

•If client has requested for some other resources then the web server will contact to the application server and data store to construct the HTTP response.

Architecture

Web Server Architecture follows the following two approaches:

1.Concurrent Approach

2.Single-Process-Event-Driven Approach.

Concurrent Approach

Concurrent approach allows the web server to handle multiple client requests at the same time. It can be achieved by following methods:

•Multi-process

•Multi-threaded

•Hybrid method.

Multi-processing

In this a single process (parent process) initiates several single-threaded child processes and distribute incoming requests to these child processes. Each of the child processes are responsible for handling single request.

It is the responsibility of parent process to monitor the load and decide if processes should be killed or forked.

Multi-threaded

Unlike Multi-process, it creates multiple single-threaded process.

Type of web srever:


Apache Tomcat

Web logic

Glass fish
J Boss

Steps to create a servlet example

There are given 6 steps to create a servlet example. These steps are required for all the servers.
The servlet example can be created by three ways:
1.By implementing Servlet interface,
2.By inheriting GenericServlet class, (or)
3.By inheriting Http Servlet class

The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1.Create a directory structure

2.Create a Servlet

3.Compile the Servlet

4.Create a deployment descriptor

5.Start the server and deploy the project

6.Access the servlet

1)Create a directory structures
The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the WEB-INF folder.

What are Servlets?

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

Servlets Architecture


The following diagram shows the position of Servlets in a Web Application
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

• The servlet is initialized by calling the init () method.

• The servlet calls service() method to process a client's request.

• The servlet is terminated by calling the destroy() method.

• Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() Method

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.
public void init() throws Servlet Exception {
// Initialization code...
}

The service() Method

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Here is the signature of this method:
public void service(Servlet Request request,
Servlet Response response)
throws Servlet Exception, IO Exception{
}
The service () method is called by the container and service method invokes do Get, do Post, do Put, do Delete, etc. methods as appropriate.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by do Get() method.
public void do Get(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() Method

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, and write cookie lists.
public void destroy() {
// Finalization code...
}

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:
1.public void destroy() 
 

Architecture Diagram

The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
DemoServlet.java
1.import javax.servlet.http.*; 
2.import javax.servlet.*; 
3.import java.io.*; 
4.public class Demo Servlet extends Http Servlet{ 
5.public void doGet(HttpServletRequest req,HttpServletResponse res) 
6.throws ServletException,IOException 
7.{ 
8.res.setContentType("text/html");//setting the content type 
9.PrintWriter pw=res.getWriter();//get the stream to write the data 
10. 
11.//writing html in the stream 
12.pw.println("<html><body>"); 
13.pw.println("Welcome to servlet"); 
14.pw.println("</body></html>"); 
15. 
16.pw.close();//closing the stream 
17.}} 
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:
Jar file Server
1) servlet-api.jarApache Tomcat
2) weblogic.jarWeblogic
3) javaee.jarGlassfish
4) javaee.jarJBoss
Two ways to load the jar file
1.set classpath
2.paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-INF/classes directory.
4)Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program.
web.xml file
1.<web-app> 
2.<servlet> 
3.<servlet-name>sonoojaiswal</servlet-name> 
4.<servlet-class>DemoServlet</servlet-class> 
5.</servlet> 
6. 
7.<servlet-mapping> 
8.<servlet-name>sonoojaiswal</servlet-name> 
9.<url-pattern>/welcome</url-pattern> 
10.</servlet-mapping> 
11. 
12.</web-app> 

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.
One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:


1.set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).
2.Change the port number of tomcat (optional). It is required if another server is running on same port (8080).

In any J2EE web applications servlets are an integral part. The server side component of a servlets gives a powerful mechanism for developing server side web applications. It provides an important role in the explosion of Internet, its reusability, performance and scalability.
The advantages of servlets are discussed below.

1.Portability
2.Powerful
3.Efficiency
4.Safety
5.Integration
6.Extensibility
7.Inexpensive
8.Secure
9.Performance

Servlet Interface

Servlet interface provides common behaviour to all the servlets.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.


Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.

Method Description

public void init(ServletConfig config)initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.

public void service(ServletRequest request,ServletResponse response)provides response for the incoming request.

It is invoked at each request by the web container.

public void destroy()is invoked only once and indicates that servlet is being
destroyed.

public ServletConfig getServletConfig()returns the object of ServletConfig.

public String getServletInfo()returns information about servlet such as writer,
copyright, version etc


GenericServlet class :

GenericServlet class implements Servlet, ServletConfig and Serializableinterfaces. It provides the implementation of all the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

1.public void init(ServletConfig config) is used to initialize the servlet.

2.public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.

3.public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.

4.public ServletConfig getServletConfig() returns the object of ServletConfig.
5.public String getServletInfo() returns information about servlet such as writer, copyright, version
etc.

6.public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)

7.public ServletContext getServletContext() returns the object of ServletContext.

8.public String getInitParameter(String name) returns the parameter value for the given parameter name.

9.public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.

10.public String getServletName() returns the name of the servlet object.

11.public void log(String msg) writes the given message in the servlet log file.

12.public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows:

1.Servlet
2.ServletRequest
3.ServletResponse
4.RequestDispatcher
5.ServletConfig
6.ServletContext
7.SingleThreadModel
8.Filter
9.FilterConfig
10.FilterChain
11.ServletRequestListener
Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:

1.GenericServlet
2.ServletInputStream
3.ServletOutputStream
4.ServletRequestWrapper
5.ServletResponseWrapper
6.ServletRequestEvent
7.ServletContextEvent
8.ServletException
Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:

1.HttpServletRequest
2.HttpServletResponse
3.HttpSession
4.HttpSessionListener
Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

1.HttpServlet
2.Cookie
Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1.Servlet class is loaded.

2.Servlet instance is created.

3.init method is invoked.

4.service method is invoked.

5.destroy method is invoked.


1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:

1.public void init(ServletConfig config) throws ServletException
 
4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:

1.public void service(ServletRequest request, ServletResponse response)  

2.  throws ServletException, IOException 


What is different between web server and application server?

A web server responsibility is to handler HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.

Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.

Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.

1.What is the difference between GET and POST method?

•GET is a safe method (idempotent) where POST is non-idempotent method.

•We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.

•GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.

•GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.

•Hyperlinks in a page uses GET method.

2.What is MIME Type?

The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

We can use ServletContext getMimeType () method to get the correct MIME type of the file and use it to set the response content type. It’s very useful in downloading file through servlet from server.

3.What is a web application and what is it’s directory structure?

Web Applications are modules that run on server to provide both static and dynamic content to the client browser. Apache web server supports PHP and we can create web application using PHP. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to client browser.

Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like below image.

1.What are common tasks performed by Servlet Container?

Servlet containers are also known as web container, for example Tomcat. Some of the important tasks of servlet container are:

•Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of container, we don’t need to build a server socket to listen for any request from web client, parse the request and generate response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.

•Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. Container also provides utility like JNDI for resource pooling and management.
•Multithreading Support: Container creates new thread for every request to the servlet and provide them request and response objects to process. So servlets are not initialized for each request and saves time and memory.

•JSP Support: JSPs doesn’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.

•Miscellaneous Task: Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.


2.What is ServletConfig object?

javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

3.What is ServletContext object?

javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet
containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we can programmatically add Listeners and Filters and Servlet to the application. It also provides some utility methods such as getMimeType(), getResourceAsStream() etc.

4.What is difference between ServletConfig and ServletContext?

Some of the differences between ServletConfig and ServletContext are:

•ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.

•ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.

•We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.

5.What is Request Dispatcher?

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

There are two methods defined in this interface:

0.void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

1.void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.

We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.
1.why we should override only no-agrs init() method.

If we have to initialize some resource before we want our servlet to process client requests, we should override init() method. If we override init(ServletConfig config) method, then the first statement should be super(config) to make sure superclass init(ServletConfig config) method is invoked first. That’s why GenericServlet provides another helper init() method without argument that get’s called at the end of init(ServletConfig config) method. We should always utilize this method for overriding init() method to avoid any issues as we may forget to add super() call in overriding init method with ServletConfig argument.

No comments:

Chapter 5 dccn

                                           Transport layer In computer networking, the transport layer is a conceptual division of metho...