Spring - Yash-777/MyWorld GitHub Wiki

DispatcherServlet

The DispatcherServlet is a part of the Spring Framework and is not available from the Servlet API itself.

In a Spring-based web application, the DispatcherServlet serves as the front controller that receives all incoming requests and routes them to the appropriate handler methods. It also provides support for many key web application features, such as URL mapping, view resolution, and exception handling.

Under the hood, the DispatcherServlet uses the Servlet API to interact with the web container and handle HTTP requests and responses. However, the DispatcherServlet itself is a Spring-specific component that provides additional functionality and features beyond what is available in the Servlet API alone.

servlet container vs spring container and which objects are get stored in which container.


Http Protocol's

URL javasript read URL

URL
image

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.

Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

HTTP Methods: GET, POST, PUT, HEAD, DELETE, PATCH, OPTIONS, CONNECT, TRACE

GET vs POST vs PUT w3schools.com

HTTP Request Response wiki

HTTP requests are sent by a client to the server. The server sends back a response. The response could be HTML, or JSON, or whatever the server decides to send.

The HTTP/1.0 specification defined the GET, HEAD and POST methods and the HTTP/1.1 specification added five new methods: OPTIONS, PUT, DELETE, TRACE and CONNECT.

Status Code: provides meta information required in the response.

HTTP response status codes mozilla.org

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(@PathVariable Long id) {
    return Optional
            .ofNullable( userRepository.findOne(id) )
            .map( user -> ResponseEntity.ok().body(user) )          //200 OK
            .orElseGet( () -> ResponseEntity.notFound().build() );  //404 Not found
}

Jersey (JAX-RS) @PathParam, @QueryParam
URL: https://www.nullpointer.at/orders/<@PathParam>/?queryParamName=<@QueryParm>
Framework Path segment http query parameter
Jersey (JAX-RS) @PathParam @QueryParam
Spring RESTFul @PathVariable @RequestParam
example xyz.com/{segment} xyz.com/?param{param}

Jersey (JAX-RS) (javax.ws.rs.) @PathParam @QueryParam

PathParam  E.g. a class annotated with: @Path("widgets/{id}") can have methods annotated whose arguments are annotated with @PathParam("id").
QueryParam E.g. if the parameter name is "a b" then the value of the annotation is "a b", not "a+b" or "a%20b".
@Get
@Path("/orders/{id}")
public String getOrder(@PathParam("id") final String id, @QueryParam("queryParamName") int i) {
  return "Order ID: " + id;
}

Spring RESTFul(org.springframework.web.bind.annotation.) @PathVariable, @RequestParam

The @PathVariable annotation is used for data passed in the URI (e.g. RESTful web services) while @RequestParam is used to extract the data found in query parameters.

//@RequestMapping(value = "/orders/{id}", method = RequestMethod.GET)
@GetMapping("/orders/{id}")
@ResponseBody
public String getOrder(@PathVariable final String id, @RequestParam("queryParamName") int i) {
  return "Order ID: " + id;
}

See



https://www.interviewbit.com/angular-interview-questions/

Control Flow Statements <sup>if-else, while, for, switch</sup>

Thread pool
how do make a method as thread safe using 




Serialization - can be acheived in 2 way [Serializable and Externalizable] https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html


What is ConcurrentHashMap and Hashtable? In java, why is ConcurrentHashMap considered faster than Hashtable?

DataStructure of Collection that you have worked : TreeMap, AL, LHM ...
HashMap<> - Internals

hm.put(1,"A");
hm.put(2,"B");
hm.put(2,"A");

What are different design patterns?
SingeTone - To break design pattern :: ReflectionAPI, clone
Factory

Build purpose, which tool are you using in the project?

Servlet Interfaces (GenricServlet, Http, CustomServlet), Life cycle methods

bean scopes, default scope of a bean {s}
bean Injection and can we use both at a time
Auto Wiring vs manual wiring


Exceptions, handle exceptions, try catch finally
 - ClassDefinationNotFOund
 CompileTIme and Runtime(FileNotFound]


framework vs library vs utility
IOC Container, Dependency Injection


@Primary, Qualifier ambiguity problem

Tata extends car     @Q("t")  or @Primary
Mahendra extends car @Q("M")
@Autowire Car obj;  

Read application properties file

@PropertySource("classpath:config.properties")
or
@PropertySources({
  @PropertySource("classpath:config.properties"),
  @PropertySource("classpath:db.properties")
})
public class AppPropertiesComponent {
   @Value("${some.key:my default value}")
   private String stringWithDefaultValue;
}


By default web-server creates only one instance per servlet, if multiple request is going to a servlet then each request will processed in a separate thread, and these threads are maintained by thread pool.

Sevlet API Servlet LifeCycle

Tomcat Application Server: servlet-api.jar.

Test your webservice (swagger/postman) unittest(integration testcase)

Servlet lifecycle methods (init, service, destroy, getservletconfig, getservlet

public abstract interface Servlet {
  public abstract void init(ServletConfig paramServletConfig) throws ServletException;
  public abstract ServletConfig getServletConfig();
  public abstract void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse)
    throws ServletException, IOException;
  public abstract String getServletInfo();
  public abstract void destroy();
}

GenericServlet vs HttpServlet

Call we call destroy() inside service() « What will happen?

Yes, we can call destroy() from the service() « It will execute the code inside destroy() method, but it will not dispose the servlet object. Servlet get instantiated, disposed by the container.


Spring Bean Lifecycle Spring Beans are Instantiated / Managed by Spring IoC Container. These beans can be created by providing bean specific configuration metadata to the container. Configuration Metadata can be provided in any of below formats.

XML, Annotation, Java Code

Spring Framework

Bean: All the objects created by spring container and stores/manages by IOC is called Spring Bean

What are different types of containers in Spring?

There are basically two types of IOC Containers in Spring:

  1. BeanFactory Container: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.
  2. ApplicationContext Container: The ApplicationContext interface is built on top of the BeanFactory interface.
What are the bean scopes in Spring?

There are five types of spring bean scopes:

  • singleton - only one instance of the spring bean will be created for the spring container. This is the default spring bean scope. While using this scope, make sure bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues.
  • prototype – A new instance will be created every time the bean is requested from the spring container.
  • request – This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
  • session – A new bean will be created for each HTTP session by the container.
  • global-session – This is used to create global session beans for Portlet applications.
Spring IOC Object creation
 * SingleTon
 * prototype
bean.getBean(); // T1 thread, hold object for 1min
bean.getBean(); // T2 thread check object same for single ton & new object for prototype.

Spring Boot


What is DevTools in Spring Boot?

Spring Boot DevTools helps you to increase the productivity of the developer. So, you don't require to redeploy your application every time you make the changes. It allows the developer to reload changes without the need of restarting of the server.

What is an embedded server? Why is it important?
What are embedded containers support by Spring?

Spring Boot support the main three embedded containers:

  1. Tomcat
  2. Jetty
  3. Undertow. By default, it uses Tomcat as an embedded container.
I have an Interface(Car) and their are two implementation classes like(Tata, Martuthi). Now i am usig `@Autowired Car car` to interfacewill it inject the proper obj or any exception (or) How will you solve the ambiguity problem

ambiguity problem - NoUniqueBeanDefinitionException

Interface Car {                   |  @Component                             |  @Configuration                
                              |  @Qualifier("tataCar")                  |  public class Config {
}                             |  public class Tata implements Car {     |   
class Tata implements Car {      |      //...                              |      @Bean
                              |  }                                      |      public Car tatCar() {
}                             |                                         |          return new Tata();
class Maruthi implements Car {   |  @Component                             |      }
                              |  @Qualifier("maruthiCar")               |   
}                             |  public class Maruthi implements Car {  |      @Bean
                              |      //...                              |      @Primary
                              |  }                                      |      public Car maruthiCar() {
                              |                                         |          return new Maruthi();
                              |                                         |      }
                              |                                         |  }
																	    | 
@Component
public class CarsService {
     
    @Autowired
    private Car car; // Spring finds multiple beans of the same type
}

If more than one bean of the same type is available in the container, the framework will throw NoUniqueBeanDefinitionException

If we try to load CarsService into our context, the Spring framework will throw a NoUniqueBeanDefinitionException. This is because Spring doesn't know which bean to inject. To avoid this problem, there are several solutions;

@Qualifier, @Primary Annotation

It's worth noting that if both the @Qualifier and @Primary annotations are present, then the @Qualifier annotation will have precedence. Basically, @Primary defines a default, while @Qualifier is very specific.

Autowiring by Name

Another way to decide between multiple beans when autowiring, is by using the name of the field to inject. This is the default in case there are no other hints for Spring.

@Component
public class CarsService {
     
    @Autowired
    private Car tata; // Spring injects tata since the field name is matched to the value that we used in the @Component annotation for that bean.
}

Bean scopes singletone, prototype
@Configuration
public class AppConfig {

    @Bean
    //@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Scope(value = "prototype")
    public PrototypeBean prototypeBean() {
        return new PrototypeBean();
    }

    @Bean
    public SingletonBean singletonBean() {
        return new SingletonBean();
    }
}

⚠️ **GitHub.com Fallback** ⚠️