2

In my servlet class, I have annotated the class with:

@WebServlet("/OnlinePostListener/testFromAnnotation")
public class OnlinePostListener extends HttpServlet {
   ...
}

My web.xml contains the following:

<servlet>
    <description>
    </description>
    <display-name>OnlinePostListener</display-name>
    <servlet-name>OnlinePostListener</servlet-name>
    <servlet-class>com.me.forwardingProxy.OnlinePostListener</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>OnlinePostListener</servlet-name>
    <url-pattern>/testFromWebXML</url-pattern>
</servlet-mapping>

My servlet only responds when I access the URL:

http://localhost:8080/forwardingProxy/OnlinePostListener/testFromAnnotation

but not:

http://localhost:8080/forwardingProxy/OnlinePostListener/testFromWebXML

What is the difference between the @WebServlet's annotation and servlet-mapping? Why is the servlet-mapping not working for this URL-pattern?

Steve C
  • 322
  • 1
  • 5
  • 11

2 Answers2

5

Because the Servlet specification requires that mappings defined in web.xml override rather than add to those defined in annotations. The reason is that without this, there would be no way to disable a mapping defined in an annotation.

Mark Thomas
  • 16,339
  • 1
  • 39
  • 60
  • I understand that there should always be a servlet-mapping due to the specification. However, the URL that I've included in the servlet-mapping simply doesn't work while the annotation does. – Steve C Jul 12 '12 at 18:50
  • 1
    Sorry mis-read the question. The second URL you quote doesn't match what is in web.xml. You are missing a /OnlinePostListener from the URL pattern. – Mark Thomas Jul 12 '12 at 19:48
  • After reading the answer I too found it unsatisfactory. didn't read the comment before posting my own answer. – KNU Nov 05 '14 at 12:39
5

It's because you are using wrong url to fetch the servlet in the later case.

Use the correct url :

http://localhost:8080/forwardingProxy/testFromWebXML

ERROR : You used an extra /OnlinePostListener in later case.

In the first case your mapped URL for the specified servlet is "/OnlinePostListener/testFromAnnotation" hence you have used this string as appending URL to http://localhost:8080/forwardingProxy BUT in the later case you have mapped the servlet to /testFromWebXML ( AND NOT /OnlinePostListener/testFromWebXML).

If,however, you insist on using the URL http://localhost:8080/forwardingProxy/OnlinePostListener/testFromWebXML to exploit web.xml you should make following changes :

<servlet-mapping>
    <servlet-name>OnlinePostListener</servlet-name>
    <url-pattern>/OnlinePostListener/testFromWebXML</url-pattern>
</servlet-mapping>
KNU
  • 2,560
  • 5
  • 26
  • 39