What is Servlet Mapping ?

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

How is servlet mapping defined?

Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:

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

servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

Syntax for servlet mapping as per servlet specification SRV.11.2:

A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.

All other strings are used for exact matches only.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.

1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

What is implicit mapping?

A servlet container can have a internal JSP container. In such case, *.jsp extension is mapped to the internal container. This mapping is called implicit mapping. This implicit mapping allows ondemand execution of JSP pages. Servlt mapping defined in web application has high precedence over the implicit mapping.

Example code for java servlet mapping:

<servlet>
<servlet-name>milk</servlet-name>
<servlet-class>com.javapapers.Milk</servlet-class>
<!–servlet>
<servlet>
<servlet-name>points</servlet-name>
<servlet-class>com.javapapers.Points</servlet-class>
</servlet>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.javapapers.ControllerServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>points</servlet-name>
<url-pattern>/pointlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

What is Servlet Invoker?

As defined by Apache Tomcat specification, the purpose of Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a element in the /WEB-INF/web.xml deployment descriptor.By enabling servlet invoker the servlet mapping need not be specified for servlets. Servlet ‘invoker’ is used to dispatch servlets by class name.

Enabling the servlet invoker can create a security hole in web application. Because, Any servlet in classpath even also inside a .jar could be invoked directly. The application will also become not portable. Still if you want to enable the servlet invoker consult the web server documentation, because every server has a different method to do it.

In Tomcat 3.x, by default the servlet invoker is enabled. Just place the servlets inside /servlet/ directory and access it by using a fully qualified name like http://%5Bdomain%5D:%5Bport%5D/%5Bcontext%5D/servlet/%5Bservlet.
This mapping is available in web application descriptor (web.xml), located under $TOMCAT_HOME/conf.

/servlet/ is removed from Servlet 2.3 specifications.
In Tomcat 4.x, by defaul the servlet invoker id disabled. The tag is commented inside the default web application descriptor (web.xml), located under $CATALINA_HOME/conf. To enable the invoker servlet uncomment the following two blocks.

<!–– The mapping for the invoker servlet –>
<!–
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
–>


<!–
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
–>

Design Pattern : Adapter in Java

The adapter pattern is a structural design pattern that allows you to repurpose a class with a different interface, allowing it to be used by a system which uses different calling methods.

Adopter Design pattern

 

A square peg in a round hole

A square peg in a round hole

 

The Adapter pattern translates one interface for a class into a compatible interface. It is used when two classes could conceptually work together but cannot because of implementation details. For this example, I create a few simple classes modeling the problem of fitting a square peg into a round hole. A square peg will sometimes fit into a round hole, as illustrated in figure depending on the relative sizes of the peg and the hole:

 

 

To determine if a square will fit into a circle, I use the formula shown here



Figure 2. Formula for determining if a square will fit into a circle

I could trivially solve the square peg/round hole problem with a simple utility class that handles conversions. But it exemplifies a larger problem. For example, what if I’m adapting a Button to fit on a type of Panel that it wasn’t designed for yet can be made compatible with? The problem of square pegs and round holes is a convenience simplification of the general problem addressed by the Adapter design pattern: adapting two incompatible interfaces. To enable square pegs to work with round holes, I need a handful of classes and interfaces to implement the Adapter pattern, as shown in Listing 1:

 

Listing 1. Square pegs and round holes in Java

 

public class SquarePeg {

private int width;

 

public SquarePeg(int width) {

this.width = width;

}

 

public int getWidth() {

return width;

}

}

 

public interface Circularity {

public double getRadius();

}

 

public class RoundPeg implements Circularity {

private double radius;

 

public double getRadius() {

return radius;

}

 

public RoundPeg(int radius) {

this.radius = radius;

}

}

 

public class RoundHole {

private double radius;

 

public RoundHole(double radius) {

this.radius = radius;

}

 

public boolean pegFits(Circularity peg) {

return peg.getRadius() <= radius;

}

}

 

To reduce the amount Java code, I’ve added an interface named Circularity to indicate that the implementer has a radius. This lets me write the RoundHole code in terms of round things, not just RoundPegs. This is a common concession in the Adapter pattern to make type resolution easier.

To fit square pegs into round holes, I need an adapter that adds Circularity to SquarePegs by exposing a getRadius() method, as shown in Listing 2:
Listing 2. Square peg adapter

 

public class SquarePegAdaptor implements Circularity {

private SquarePeg peg;

 

public SquarePegAdaptor(SquarePeg peg) {

this.peg = peg;

}

 

public double getRadius() {

return Math.sqrt(Math.pow((peg.getWidth()/2), 2) * 2);

}

}

 

To test that my adapter does in fact let me fit suitably sized square pegs in round holes, I implement the test shown in Listing 3:
Listing 3. Testing adaptation

 

@Test

public void square_pegs_in_round_holes() {

RoundHole hole = new RoundHole(4.0);

Circularity peg;

for (int i = 3; i <= 10; i++) {

peg = new SquarePegAdaptor(new SquarePeg(i));

if (i < 6)

assertTrue(hole.pegFits(peg));

else

assertFalse(hole.pegFits(peg));

}

}

 

In Listing 3, for each of the proposed widths, I wrap the SquarePegAdaptor around the creation of the SquarePeg, enabling hole’s pegFits() method to return an intelligent evaluation as to the fitness of the peg.

This code is straightforward, because this is a simple albeit verbose pattern to implement in Java. This paradigm is clearly the GoF design-pattern approach. However, the pattern approach isn’t the only way.

UML

 

what is moneky patching ?

Monkey-patching is the dangerous-yet-frequently-useful technique of re-opening existing classes to change or add to their behavior. The term monkey patch only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as you desire.

Do not confuse it with sub class and use, that is some thing which the compile time stuff in java and related languages. I can be though of as using filters or reflection to modify or tweek the run time behavior of a class.there are libraries like cglib (code generation library – which adds or intercepts the main class file) which helps to do that.

In monkey patching main class is called and you additional behaviour, however in subclass you have to explicitly call the sub class.