15

I am using Eclipse Juno 4.2, Java 1.7 and Tomcat 7. But in my system when I create servlet the web.xml file doesn't create automatically, but another system it's create automatically web.xml file. I am totally confused, is there anything to configure?

I also add web.xml file when I am going to create a dynamic project.

halfer
  • 19,824
  • 17
  • 99
  • 186
Chintamani
  • 1,076
  • 7
  • 23
  • 47

2 Answers2

47

Tomcat 7 is a Servlet 3.0 compatible container. Since Servlet 3.0, the servlets can be configured by @WebServlet annotation on the class without the need for a web.xml configuration entry. Look closer at the servlet class you just created, there's a @WebServlet annotation on it containing all information you specified in New Servlet wizard.

Effectively, this new way of configuring servlets

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {}

does exactly the same as this legacy way of configuring servlets

<servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

If you still want Eclipse to create a web.xml entry for some reason, then you should change the Dynamic Web Module version back from 3.0 to 2.5 in Project Facets section of project's properties.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • But that annotation does not work without further tweaks on tomcat 7. See http://stackoverflow.com/questions/11669507/embedded-tomcat-7-servlet-3-0-annotations-not-working – arun Aug 12 '14 at 04:19
  • 1
    @arun Please don't confuse "Embedded Tomcat" with "Tomcat". The current question is about Tomcat, the question you linked is about Embedded Tomcat which is an entirely different thing. – BalusC Aug 12 '14 at 05:17
  • will the `@WebServlet` tag work even when multiple servlets are being used? – scottysseus Sep 23 '15 at 17:36
  • @BalusC, Thanks, the explanation helped. However, is it possible to configure Eclipse - to create web.xml and to add Servlet entries as response to new `@WebServlet` annotations - for backward compatibility? (In case I want to deploy the application with Servlet 2.5) – NurShomik Jan 12 '16 at 03:51
  • @NShomik: Just set dynamic web project facet version to 2.5. – BalusC Jan 12 '16 at 07:13
  • @BalusC: Thanks. I guess this is going to the solution for me. For some reason though my Eclipse (Mars) is not allowing it. – NurShomik Jan 12 '16 at 08:22
2

If you use the Servlet 2.5 version instead of the 3.0 then web.xml will automatically be updated to contain the servlets you created.

Majda
  • 629
  • 7
  • 8