How to ensure that a Servlet is Deployed in Tomcat 7 using Servlet Container 3.0?

Asked

Viewed 377 times

3

I am developing an application that uses the Servlet API 3.0 via Annotations and porting does not need WEB-INF/web.xml file

The problem that sometimes when I deploy in Tomcat 7 the Servlet is not available and I receive error 404. No error message appears in LOG.

In short, I would like to force Tomcat to view my Servlet, preferably programmatically so you don’t need to edit JEE descriptors in XML.

NOTE: The Servlet was available and apparently without modification started to accuse error 404 when I made a new Application Deploy.

I’m declaring the Servlet with the Note @WebServlet where I only use the attributes name and urlPatterns

This is the correct approach ? Some notes are missing ? I need to use the Interface javax.servlet.ServletRegistration ?

  • Which version of Tomcat are you using? Tried to use version 8?

  • I’m using the version 7.0.52 but I have already tested in 7.0.47 also. According to the Documentation in this Link Servlet API 3.0 is supported since version 7.0

1 answer

2

If you use the Tomcat Embedded may force Tomcat to view your Servlet programmatically and not need to edit JEE descriptors in XML.

Here’s an example below where you don’t need to use the annotation @WebServlet :

Main method

// Para tratar o CTRL-C
final Tomcat tomcat = new Tomcat();
Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        try {
            tomcat.stop();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
});

// inicio
tomcat.setPort(Integer.valueOf(args[0]));
Log containerLogger = context.getLogger();

try {
    Context context = tomcat.addWebapp("/",
            new File(".").getAbsolutePath());

    containerLogger.info("*** INICIANDO ***");

    containerLogger.info("*** iniciando o Tomcat com o servlet "
            + MyDynServlet.class.getSimpleName());

    tomcat.start();

    String myDynServletName = MyDynServlet.class.getSimpleName()
            .toLowerCase();
    Wrapper myDynServlet = context.createWrapper();
    myDynServlet.setName(myDynServletName);
    myDynServlet.setServletClass(MyDynServlet.class.getCanonicalName());
    myDynServlet.addInitParameter("debug", "0");
    myDynServlet.addInitParameter("listings", "false");
    myDynServlet.setLoadOnStartup(1);
    context.addChild(myDynServlet);
    // O mapping do Servlet pode vir de qualquer fonte. 
    // Abaixo está hard-coded
    context.addServletMapping("/mydynservlet", myDynServletName);
    // Para ajudar na resolução de problemas listo os mappings
    String[] servletMappings = context.findServletMappings();
    for (String mapping : servletMappings) {
        containerLogger.info("*** ServletMapping " + mapping);
    }
} catch (ServletException | LifecycleException e) {
    e.printStackTrace();
}

int CINCO_SEGUNDOS = 5 * 1000;
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        // Wait until a proper shutdown command is received, then
        // cancel timer thread.
        containerLogger.info("***  AWAIT Server");

        tomcat.getServer().await();

        containerLogger.info("***  Server Shutdown Complete ***");
        containerLogger.info("***  Cancelando Timer Thread  ***");
        timer.cancel();
    }
}, CINCO_SEGUNDOS);

// Você pode desejar fazer algo depois de carregar o Tomcat em outra Thread.

Note that a Timer Task has been created only to not block the current Thread. This is optional.

Dependencências Maven:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <tomcat-embed.version>7.0.52</tomcat-embed.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
        <version>${tomcat-embed.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-api</artifactId>
        <version>${tomcat-embed.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-logging-juli</artifactId>
        <version>${tomcat-embed.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>${tomcat-embed.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat7-websocket</artifactId>
        <version>${tomcat-embed.version}</version>
    </dependency>
</dependencies>

Dependency with Websocket is optional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.