简体   繁体   中英

WebServlet maps multiple paths to /

I am developing a school project where I am using Tomcat7, Thymeleaf and javax.servlet with MAven as package manager.

My file IndexServlet.java is called even when I don't call the path

package com.barnacle.travel.web;

import com.barnacle.travel.config.TemplateEngineUtil;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

@WebServlet("/")
public class IndexServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        System.out.println(request.getRequestURI());

        TemplateEngine engine = TemplateEngineUtil.getTemplateEngine(request.getServletContext());
        WebContext context = new WebContext(request, response, request.getServletContext());
        context.setVariable("recipient", name);
        engine.process("index.html", context, response.getWriter());
    }

}

The configuration section for the tomcat7 plugin is:

        <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
          <artifactId>tomcat7-maven-plugin</artifactId>
          <version>2.2</version>
          <configuration>
            <path>/</path>
          </configuration>
        </plugin>
   

Every request gets mapped to the the servlet even though I want the index or / to be mapped only. What should be changed?

As suggested by @rickz in comment and from Change default homepage in root path to servlet with doGet editing the code annotation to:

@WebServlet("")       //empty string

solves the issue. This is due to the fact mentioned here Difference between / and /* in servlet mapping url pattern regarding the / pattern in web servlets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM