Wednesday, December 9, 2009

Things to remember in Servlet URL Mapping






Most of the time when we work, we always uses any web MVC framework like struts. And we start forgetting the advantages which are in the web.xml by default.
I just thought sharing about servlet url mapping in web.xml. You may thing this is a very basic in j2ee. That right, however they are some important points which should be remembered ;)
SUFIX Wins
When we map the URL for servlet, always suffix wildcard string will be taken as the first priority than prefix wildcard.
Example:
      For above URL two pattern matches in the below weeb.xml file,even SampleServlet matches the long string.Only the SampleServlet2 should get executed.
      So the bottom line is suffix always wins first ;)
Wildcard only before or after /
When you want to apply wildcard (*), it will work only after or before the / in the url mapping.  
  <servlet-mapping>
    <servlet-name>SampleServletservlet-name>
    <url-pattern>/servlet/SampleServlet*url-pattern>
  servlet-mapping>
The above code will not get matched if we have URL like this www.passion4java.com/servlet/SampleServlet1
Wildcard at the start or end
You can apply wildcard only at the start or the end, if you try to apply the wildcard in between the url like below.
  <servlet-mapping>
    <servlet-name>SampleServletservlet-name>
    <url-pattern>/servlet/SampleServlet/*/testurl-pattern>
  servlet-mapping>
And trying to call with the URL: www.passion4java.com/servlet/SampleServlet1/wildcardhere/test , the mapping will not be picked.

Sample Web.xml


  
    SampleServlet
    com.passion4java.servlet.SampleServlet
    
    	name
    	This is a SampleServlet
    
  
  
    SampleServlet2
    com.passion4java.servlet.SampleServlet
    
    	name
    	This is a SampleServlet 2
    
  
  
    SampleServlet
    /servlet/SampleServlet/*
  
  
    SampleServlet2
    *.mama
  

1 comment:

Anonymous said...

This is a nice post. keep it up... :)

Post a Comment

 

This content comes from a hidden element on this page.

The inline option preserves bound JavaScript events and changes, and it puts the content back where it came from when it is closed.
Click me, it will be preserved!

If you try to open a new ColorBox while it is already open, it will update itself with the new content.

Updating Content Example:
Click here to load new content