Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Order of elements in DD and servlet/servlet-mapping

 
Karim Kiswarday
Ranch Hand
Posts: 50
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Rancheros,
I've read this article http://www.coderanch.com/how-to/java/InvokerServlet and it reports:
...For each servlet you want to call, provide a pair of tags like the following:

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>your.package.name.HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

There are a couple things to note when you do this. Order of elements in web.xml is very important. So when you go to create your second 'couplet', make sure all your <servlet> tags are declared before your <servlet-mapping> tags. You'll maybe want to keep the 'couplets' together, because it will be easier to see which one belongs to which, but don't do it!...


Now I don't understand the two bold texts:
1) I know that the order of elements in deployment descriptor is not important, but here it tells the opposite.
2) Why is not advisable to keep <servlet> and <servlet-mapping> together?

Thanks
Karim
 
Stoian Azarov
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karim,

I didn't read the article but from what I see I think that they just tried to protect people that just start to learn about servlets from unexpected behavior.

1. You are right the order in DD doesn't matter in general. But this is not completely true. When you have many <servlet-mapping> elements that overlap(uri-patterns overlap) then the container has special conditions(rules) to determine which servlet to choose. You can read about this in "HF Servlets and JSP" book Chapter 11 page 619. Or even better in Serlvet Specification 3.0 - Chapter 12 Mapping Request to servlets(it is only 3 pages).

In general the rule is that the container orders mappings(I will provide the order above) and then starts choosing the servlet mapping that wins the competition - the first found mapping is used:
- Exact match <servlet-mapping>/hello/mello</servlet-mapping>
- Directory match <servlet-mapping>/hello/*</servlet-mapping>
- Extension match <servlet-mapping>*.jsp</servlet-mapping>

2. I suppose that if you keep all mappings in one place it will be easier to see which mapping will be chosen by the container. If you have mappings scattered all around the DD you might miss duplicate mapping and it will become nightmare finding the problem in your application.

HTH

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic