# Servlet

## Introduction

* A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

## Basic Implementation

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2F47TMdgHig0mNw34sKa9j%2Fimage.png?alt=media\&token=6e09ed34-ced3-4b92-9352-9a733714bbd7)

{% code title="HelloServlet.java" %}

```java
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
  
        // Get the client entered data from request object
        String name = request.getParameter("name");
  
        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
  
        // Print hello message to the client browser in
        // response object
        out.println("<h3>Hello " + name + "!!</h3>");
        out.close();
    }
}
```

{% endcode %}

```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ServletFlow</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>
```

### **Servlet container:**

It is a web container that is part of a web server that interacts with the Java Servlets. Servlet container is responsible for

* Managing the lifecycle of servlets
* Creating servlet object, request, and response objects
* Mapping a URL to a particular servlet
* Ensuring that the URL requester has the correct access rights
* Managing the execution of JSP pages etc

### **Servlet Life cycle**

#### Servlet Loading:

* The first container will perform Servlet Loading.
* The container will check if the same servlet is already available or not, if not then it loads the .class file, the byte code into the memory.
* To perform this, container will call ***class c = class.forName(“helloServlet”);*** internally.

#### Servlet Instantiation:

* After servlet loading, it creates an object for the servlet.
* And it creates “***servletConfig”*** object for that servlet and stores all the data of that particular servlet in it.
* To perform this, container will call ***object obj = c.newInstance();*** internally.

#### Servlet Initialization:

* Now we need to initialize the servlet, the container will call the ***init()*** by passing ***servletConfig*** object to it.
* First, the container will execute parameterized init() method. Inside that, another parameter less init() method will be called from the Generic servlet and that method also will be executed.

### Flow

* The container will recognize the ***web.xml*** file under the WEB-INF folder. After identifying the web.xml file, the container will perform web.xml file loading, parsing, and reading the contents of it. If any application-level data like display names or context parameters are available in the web.xml file, the container will take that application data and store it in “*servletContext*” object. This data is managed by a servlet context object.
* The server will forward the valid request to the servlet container, the container will identify what is the application name and resource name to execute. As we specified in the form, the container will identify the servlet to execute based on the URL pattern(“*hello”)* that associated is with the “*HelloServlet.class”* file under the classes folder. Once the container identifies the servlet .class file, the life cycle of the servlet will start.
* The container will create HTTP Request and HTTP response objects and a thread to execute dopost() method.  We are using HTTPServlet and we need to execute the ***doPost()*** method by passing ***Http servlet request*** and ***Http servlet response.***
* Once the *“doPost()”* method is executed, then the response will be generated in the response object. When the container reaches the end of the doPost() method execution, that thread will be destroyed and the container will dispatch that response to the main server. The main server will transfer the HTTP response to the protocol. The protocol will prepare a Response format that is having Response Header and Response Body.&#x20;

\
Filter
------

* A filter is an object that is invoked at the preprocessing and postprocessing of a request.
* It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.
* The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet.

{% code title="web.xml" %}

```xml
<web-app>  
  <servlet>  
    <servlet-name>s1</servlet-name>  
    <servlet-class>HelloServlet</servlet-class>  
  </servlet>  
  
  <servlet-mapping>  
    <servlet-name>s1</servlet-name>  
    <url-pattern>/servlet1</url-pattern>  
  </servlet-mapping>  
  
  <filter>  
    <filter-name>f1</filter-name>  
    <filter-class>MyFilter</filter-class>  
  </filter>  
   
  <filter-mapping>  
    <filter-name>f1</filter-name>  
    <url-pattern>/servlet1</url-pattern>  
  </filter-mapping>  
</web-app>  
```

{% endcode %}

{% code title="MyFilter.java" %}

```java
import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.*;  
  
public class MyFilter implements Filter{  
  
public void init(FilterConfig arg0) throws ServletException {}  
      
public void doFilter(ServletRequest req, ServletResponse resp,  
    FilterChain chain) throws IOException, ServletException {  
          
    PrintWriter out=resp.getWriter();  
    out.print("filter is invoked before");  
          
    chain.doFilter(req, resp); //sends request to next resource or filter  
          
    out.print("filter is invoked after");  
    }  
    public void destroy() {}  
}  
```

{% endcode %}

## DispatcherServlet

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2F94vUZnpD6q6ZcjaTLSas%2Fimage.png?alt=media\&token=b165d88a-513e-49a0-8722-4e18f9b6bf5a)

* A Spring servlet is a Java class that serves as the central point for handling requests and managing the lifecycle of the Spring IoC container.
* The Spring Framework provides a class called DispatcherServlet, which acts as the front controller in a Spring-based web application. When a user makes a request to a Spring web application, the DispatcherServlet is responsible for handling the request, delegating responsibility to other components, and ultimately returning a response to the user.
* The DispatcherServlet also manages the lifecycle of the Spring IoC container, including creating and initializing the container and making its beans available for use by other components in the application.
* `DispatcherServlet` expects a `WebApplicationContext` (an extension of a plain `ApplicationContext`) for its own configuration. `WebApplicationContext` has a link to the `ServletContext` and the `Servlet` with which it is associated
* The root `WebApplicationContext` typically contains infrastructure beans, such as data repositories and business services that need to be shared across multiple `Servlet` instances. Those beans are effectively inherited and can be overridden (that is, re-declared) in the Servlet-specific child `WebApplicationContext`, which typically contains beans local to the given `Servlet`.

### Configuration (By XML)

1. web.xml

* To tell where the config file is
* Setup the dispatcherServlet so as to send the user request to corresponding controller to handle the request and return the correct view
* The output file(war) will be generated based web.xml so as to do deployment

```markup
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">

	<display-name>spring-mvc-demo</display-name>

	<absolute-ordering />

	<!-- Spring MVC Configs -->

	<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<!-- Spring creates a WebApplicationContext object 
		based on the bean definitions 
		and stores it in the ServletContext of one's web application. -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
</web-app>
```

2\. spring-mvc-demo-servlet.xml

* To perform component scanning
* Allow the support of validation
* Define the pattern of getting the view

```markup
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
    	http://www.springframework.org/schema/beans/spring-beans.xsd
    	http://www.springframework.org/schema/context
    	http://www.springframework.org/schema/context/spring-context.xsd
    	http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<!-- Step 3: Add support for component scanning -->
	<context:component-scan base-package="com.luv2code.springdemo" />

	<!-- Step 4: Add support for conversion, formatting and validation support -->
	<mvc:annotation-driven/>

	<mvc:resources mapping="/resources/**" location="/resources/"></mvc:resources>


	<!-- Step 5: Define Spring MVC view resolver -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>
```

### Configuration (By Annotation)

{% code title="DemoAppConfig.java" %}

```java
package com.luv2code.springdemo.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.luv2code.springdemo")
public class DemoAppConfig {
 
	// define a bean for ViewResolver
	@Bean
	public ViewResolver viewResolver() {
		
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		
		viewResolver.setPrefix("/WEB-INF/view/");
		viewResolver.setSuffix(".jsp");
		
		return viewResolver;
	}
}
```

{% endcode %}

{% code title="MySpringMvcDispatcherServletInitializer.java" %}

```java
package com.luv2code.springdemo.config;
 
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 
	@Override
	protected Class<?>[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return null;
	}
 
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { DemoAppConfig.class };
	}
 
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
}
```

{% endcode %}

## Spring boot

* Spring Boot automatically configures a spring application based on dependencies present or not present in the classpath as a jar, beans, properties, etc.
* It makes development easier and faster as there is no need to define certain beans that are included in the auto-configuration classes.
* A typical MVC database driven Spring MVC application requires a lot of configuration such as **dispatcher servlet, a view resolver, Jackson, data source, transaction manager,** among many others.
  * Spring Boot auto-configures a **Dispatcher Servlet** if **Spring MVC jar** is on the classpath.
  * Auto-configures the **Jackson** if **Jackson jar** is on the classpath.
  * Auto-configures a **Data Source** if **Hibernate jar** is on the classpath.
* Auto-configuration can be enabled by adding **@SpringBootApplication** or **@EnableAutoConfiguration** annotation in startup class. It indicates that it is a spring context file.
