Thursday, July 6, 2017

Web-Application

1. Create a simple maven webapp project. (maven-archetype-webapp)
groupid - artifactid - version
org.education - simplewebapp - 0.0.1-SNAPSHOT

2. Your project directory structure will look like below
    |>src
      |>main
        |>java
        |>resources
        |>webapp(context-root)
          |>WEB-INF
               
|>classes
                |>lib
                |>views
                web.xml
          index.html/index.jsp

3. When we start tomcat web server by running bin/catalina.sh start, servlet/web container org.apache.catalina.startup scan webapps folder to deploy war application. And reads/parses user defined web.xml using SAX Parser.
We can define ROOT/folder_name as our application name.
ROOT -> localhost:8080/
folder_name -> localhost:8080/folder_name/
Browser will get index.html/index.jsp in response.

4. What is Servlet?
Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests(GET,POST,PUT,DELETE).

5. Creating a Servlet

 There are three different ways to create a servlet.

    By implementing Servlet interface
    By extending GenericServlet class
    By extending HttpServlet class

But mostly a servlet is created by extending HttpServlet abstract class. The servlet class that we will create should not override service() method. Our servlet class will override only doGet() or doPost() method.

6. There are four phases in the life cycle of Servlet.

Loading and Instantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.

Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.

Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.




web.xml
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>org.education.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
        throws IOException {
        System.out.println("Inside doGet");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Hello Servlet</h1>");
        out.println("</body></html>");
    }
}

7. When a web browser sends a request to the web server, it receives the request and sends the response based on the request. That’s how transaction gets completed.

    Request
    Response
    Header

Client sending a request to Sever

When a client(web browser) sends a http request to the web server. First line in the http request it specifies is the URL and the version of HTTP protocol.

GET /index.html HTTP/1.0


The above request is using the GET method to ask for a webpage index.html using HTTP version 1.0. Along with the above line, client can send optional header information which can be helpful for webserver in order to generate better response. for example:-

user-Agent: Firefox/4.0 (compatible; Windows 2000)
Accept: image/jpg, image/png, */*


User-Agent header: It provides the information about client(web browser) software. In the above example it is telling web-server that request is being sent from a Firefox version 4.0 browser.
Accept header: It specifies the media(MIME) time which client can easily accept.

Server sending a response to client

Once Web-Server processed the request it sends a response to client. In the first line it specifies the HTTP protocol server is using along with the status code of request.

HTTP/1.0 200 OK

The status code 200 means request processed successfully.
Another example:

HTTP/1.0 404 Not Found

The status code 404 means request document was not found by server.


Code Range     Response Meaning
100-199           Informational
200-299          Client request successful
300-399          Client request redirected, further action necessary
400-499          Client request incomplete
500-599          Server error


Along with above status line Response header contains few additional things which tells client more about Sever side software and content type – for example –

Date: Monday, 15-May-2012 02:03:52 GMT
Server: JavaWebServer/1.1.1
MIME-version: 1.0
Content-type: text/html
Content-length: 2024
Last-modified: Tuesday, 9-May-2012 01:02:12 GMT


Points to remember:
1. Server sends a blank line after the header section to separate it from content section.
2. If server process the request successfully it sends the response along with header otherwise it respond back in human readable format to let them know why it had not be able to process the request.

8. When a http request comes in for the servlet, the web/servlet container creates an HttpServletRequest/HttpServletResponse objects, calls the servlet's service() method by passing these objects as arguments and depending on the type of request the service() method calls either the doGet() or doPost() method.

NOTE: By default a request is Get request.


By default container follows MultiThreadModel. If the container receives concurrent multiple requests for one servlet simultaneously, the service() method of that servlet will be executed concurrently in multiple threads. Thus,  Servlet containers(Eg. Tomcat) usually manage concurrent multiple requests by creating a new Java thread for each request. The new thread is given an object reference(instance) to the requested servlet, which issues the response through the same thread. This instance properties/variables are shared among all requests.

If a servlet implements the SingleThreadModel interface, the container will not execute the service() method in more than one thread simultaneously. The servlet container may synchronize access to a single instance of the servlet.
However, servicing requests sequentially seriously hurts performance. To avoid the performance problem, a servlet container may create multiple instances of the servlet class.


A single thread model for servlets is generally used to protect sensitive data (bank account operations).

So, the way that servlet containers handle servlet requests is implementation dependent; they may use a single servlet OR they may use servlet pooling, it depends on the vendor's system architecture.

Servlets are normal java classes and thus are NOT Thread Safe. But we can make it as a thread safe by implementing that servlet class to SingleThreadModel but again the performance problem will be there so better option would be use synchronized portion.

 

No comments:

Post a Comment

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...