1

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?

humble_barnacle
  • 460
  • 1
  • 4
  • 19
  • Maybe you could use BalusC answer at https://stackoverflow.com/questions/32020447/set-servlet-as-default-home-page-in-web-xml – rickz Mar 04 '22 at 17:51
  • 1
    That link I posted, links to https://stackoverflow.com/questions/33248473/change-default-homepage-in-root-path-to-servlet-with-doget where BalusC suggested using @WebServlet("") Yes, empty String! – rickz Mar 05 '22 at 00:52
  • @rickz thanks. will try it out and update here – humble_barnacle Mar 05 '22 at 11:54

1 Answers1

0

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.

humble_barnacle
  • 460
  • 1
  • 4
  • 19