Search code examples
javajspservletsservlet-container

Confused about servlet mapping


I configured a servlet as the default servlet in web.xml.

<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

When I requested for JSP like requesting http://localhost:8080/abc.jsp, I got the correct response with correct html content, and the servlet did not serve for this request.

But when I requested for HTML like requesting http://localhost:8080/abc.html, I couldn't get the abc.html file, and the service() method of my servlet was invoked.

Why do servlet containers act this way?

If I configure my servlet this way, does it mean I have to serve requests for static files in my servlet?

Update

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     id="WebApp_ID" version="3.0">
    <display-name>Servlet test</display-name>

    <servlet>
        <servlet-name>myServlet</servlet-name>
        <servlet-class>com.test.MyServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>myServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

MyServlet.java

package com.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {

    private static Logger LOG = LoggerFactory.getLogger(MyServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        LOG.info("Served");
    }
}

Solution

  • If you use <url-pattern>/</url-pattern> this doesn't override the default servlet and the JSP servlet of the container. You should use <url-pattern>/*</url-pattern> if you want that all the request be processed by your MyServlet.

    Difference between / and /* in servlet mapping url pattern