Tomcat在Eclipse中运行但无法执行GET请求

时间:2016-10-08 14:42:52

标签: java eclipse tomcat tomcat8

我在Eclipse中创建了一个动态Web项目,当我运行helloworld webapp时,我看到index.html页面没有问题截图: enter image description here

但是当我转到/HelloServlet路径时,我收到了404错误的截图: enter image description here

然而,当我转到localhost:8080时,我可以看到Tomcat正在运行屏幕截图: enter image description here

在日志中我还可以看到服务器正在运行截图: enter image description here

以下是我的服务器属性截图: enter image description here

这是HelloServlet.java的代码:

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

    /**
     * Default constructor.
     */
    public HelloServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

任何人都知道如何解决这个问题?在我的工作中,我使用Tomcat安装和配置Eclipse没有任何问题。但不知怎的,我无法让它在家里工作。

2 个答案:

答案 0 :(得分:0)

将注释@WebServlet的代码行更改为:

@WebServlet(name = "HelloServlet", urlPatterns = "/HelloServlet")

你会很开心。

为避免异常(当应用程序上下文为/时),您应该检查request.getContextPath()

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

@WebServlet(name = "HelloServlet", urlPatterns = "/HelloServlet")
public class HelloServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public HelloServlet() {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getContextPath().length() > 0) {
            response.getWriter().append("Served at: ").append(request.getContextPath());
        } else {
            response.getWriter().append("Served at: " + "/");
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

答案 1 :(得分:0)

对此链接上接受的答案的信任:HTTP Status 404 - on Eclipse with Tomcat

在Eclipse Project菜单上,我没有检查Build Automatically。之后我检查了一下。我可以调用HelloServlet类的doGet()方法。