Search code examples
servletsurl-routinghtml

Run servlet as homepage


I have a dynamic web project with a servlet (structure below).

When right-clicking HomeServlet.java --> Run as --> Run on Server --> Tomcat...
It runs fine with the URL: http://localhost:8080/JSTLTest/HomeServlet

When right-clicking JSTLTest --> Run as --> Run on Server --> Tomcat...
I get an error and this URL is used: http://localhost:8080/JSTLTest/

The problem is, i want to deploy it on a server like AWS elastic beanstalk and i guess it doesn't work because he won't use the servlet to start, like:
http://default-environment-9a5exxxd3z.elasticbeanstalk.com/HomeServlet

Is my web.xml wrong?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <display-name>JSTLTest</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Home</servlet-name>
        <servlet-class>com.journaldev.servlet.HomeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Home</servlet-name>
        <url-pattern>/HomeServlet</url-pattern>
    </servlet-mapping>
</web-app>

Structure:

enter image description here


Solution

  • Replace

    <url-pattern>/HomeServlet</url-pattern>
    

    with

    <url-pattern></url-pattern>
    

    The url pattern is the url that added to the the protocol + server + port + context (something like http://localhost:8080/myapp) can be used to access to a particular servlet.

    Note the pattern must be empty. The pattern / is the default pattern. So it match all possible patterns (also what you don't like).