Domanda

I have a servlet which is basically a hello world kind of...

The class is:

package net.jgp.baseapp.validation.tomcat;
[...]
@WebServlet(name = "tv", description = "...", urlPatterns = {"/TomcatValidator", "/" })
    public class TomcatValidator extends HttpServlet {
    [...]
    }
}

It works great when I launch it through:

http://localhost:8081/net.jgp.baseapp.validation.tomcat/tv
http://localhost:8081/net.jgp.baseapp.validation.tomcat/qwe?test=89

etc.

However, can I change the net.jgp.baseapp.validation.tomcat to:

  1. Nothing, basically it should run like http://localhost:8081?
  2. A simpler URL http://localhost:8081/toto?

So far, my web.xml is really empty (the default from Eclipse generation):

<?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">

<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>

I've looked at a lot of things, and I must admit I am getting crazy :)...

Thanks!

PS: I know that:

@WebServlet(name = "tv", description = "...", urlPatterns = {"/TomcatValidator", "/" })

is somehow equal to:

@WebServlet(name = "tv", description = "...", urlPatterns = {"/" })
È stato utile?

Soluzione

Two things here.

If you want your servlet to serve the root URL, you have to do two things

1 - you have to set your webapp context to root, like this

enter image description here

2 - then you have to set your servlet context to root too

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

@WebServlet("/")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public MyServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("OK");
        response.getWriter().flush();
    }

}

that's because the URL your servlet serve is like this

http://yourserver:port/yourapp/yourservlet

where yourapp is defined by #1

and yourservlet is defined by #2

like this

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top