2
votes

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?

2

2 Answers

5
votes

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>
4
votes

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.