Java Servlets

Java Servlet Mapping

Servlet mappings specifies the web container of which java servlet should be invoked for a URL given by client. When there is a request from a client, servlet container decides to which application it should forward to. The context path of URL is matched for mapping servlets.

How are Servlet mappings defined?

Servlets should be registered with servlet container. Add into web.xml file as such:

<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>

The URL pattern specifies the type of URLs for which, the servlet given in the servlet name should be called. The container uses case-sensitive string comparisons for servlet matchings.

ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.

If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-parm> element.

*Context PATH: Meaning

The context path is the prefix of a URL path that is used to select the context(s) to which an incoming request is passed. Typically a URL in a Java servlet server is of the format http://hostname.com/contextPath/servletPath/pathInfo, where each of the path elements can be zero or more / separated elements.

ServletContext context=getServletContext();  
  
//Getting the value of the initialization parameter and printing it  
String driverName=context.getInitParameter("dname");  
pw.println("driver name is="+driverName); 

Servlet Life Cycle

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

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

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

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

*When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread calls service(). This method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

References

Last updated