更改URL以访问我的Servlet

时间:2014-02-08 12:33:45

标签: java servlets servlet-3.0

我有一个servlet,它基本上是hello world种......

课程是:

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

通过以下方式启动它时效果很好:

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

但是,我可以将net.jgp.baseapp.validation.tomcat更改为:

  1. 没什么,基本上它应该像http://localhost:8081一样运行?
  2. 更简单的网址http://localhost:8081/toto
  3. 到目前为止,我的web.xml实际上是空的(Eclipse生成的默认设置):

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

    我看了很多东西,我必须承认我疯了:)...

    谢谢!

    PS:我知道:

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

    在某种程度上等于:

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

1 个答案:

答案 0 :(得分:1)

这里有两件事。

如果您希望servlet提供根URL,则必须执行两项操作

1 - 您必须将您的webapp上下文设置为root,如此

enter image description here

2 - 然后你必须将你的servlet上下文设置为root

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();
    }

}

那是因为您的servlet提供的URL就像这样

http://yourserver:port/yourapp/yourservlet

其中yourapp由#1

定义

和yourservlet由#2

定义 像这样

enter image description here