What happens when Rest API is fired?

  • The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 for development and port 80 in production).
  • When a client (user with a web browser) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects and passes them through any defined Filter chain and, eventually, the Servlet instance.
  • In the case of filters, the doFilter() method is invoked.
  • When its code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.
  • In the case of servlets, the service() method is invoked.
  • By default, this method determines which one of the doXxx() methods to invoke based on request.getMethod().
  • If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.
  • The request object provides access to all of the information about the HTTP request, such as its headers and body.
  • The response object provides the ability to control and send the HTTP response the way you want by.
  • For instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file).
  • When the HTTP response is committed and finished, both the request and response objects are recycled and made for reuse.

Sample Spring Filter

// Sample Spring Filter
public class CustomFilter extends GenericFilterBean {

@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}

javax Filter

// javax Filter
@Provider
public class RestActivityLogFilter implements ContainerRequestFilter {

@Override
public void filter( ContainerRequestContext requestContext) {
System.out.println("rest activity log");
}
}

Spring Adapter

public class SampleInterceptor extends HandlerInterceptorAdapter {

private static final Log logger = LogFactory.getLog(TenantInterceptor.class);
@PostConstruct
public void init(){
logger.info("initializing...");
}

@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

}

}
Lifecycle of HttpServletRequest and HttpServletResponse
  • The HttpServletRequest and HttpServletResponse live from the time the servlet receives an HTTP request from the client until the complete response (the web page) has arrived. It is not shared elsewhere.
  • All ServletFilter and Listener instances live as long as the web app lives. They are shared among all requests in all sessions.
Categories: JAVA

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *