【问题标题】:@Path not responding for basic @GET request in Java servlet in Eclipse Tomcat@Path 没有响应 Eclipse Tomcat 中 Java servlet 中的基本 @GET 请求
【发布时间】:2019-08-02 10:06:52
【问题描述】:

我是 Eclipse 和 Apache Tomcat 的新手,正在尝试完成一个基本的 get 请求。我成功安装了 Apache Tomcat 并启动了服务器,但是当我转到配置的路由时,我收到 404 错误。据我了解,我已经正确配置了类和 web.xml 文件。如何在 Eclipse 中成功完成获取请求并返回预期的资源?

我用路径和get注解配置的类是默认的(未命名打包),如下:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/attempt")
public class TestAttempt {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {     
        System.out.println("not working");      
        return "Got it!";
    }       
}

而我的 web.xml 文件是:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>Test3</display-name>

 <servlet>
     <servlet-name>helloServlet</servlet-name>
     <servlet-class>TestAttempt</servlet-class>
      <load-on-startup>1</load-on-startup>
 </servlet>

<servlet-mapping>
  <servlet-name>helloServlet</servlet-name>
  <url-pattern>/test/*</url-pattern>
</servlet-mapping>

  <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>
</web-app>

然后我转到 localhost:8080/test/attempt 并收到 404 而不是预期的:“知道了!”

【问题讨论】:

  • 您的代码实际部署了吗?检查下面tomcat/webapps
  • 我在本地运行它
  • 我了解到您在 Eclipse 中运行 Tomcat,但它仍然被部署。
  • 那在哪里?我只有一个 WebContent 文件

标签: java eclipse servlets tomcat9


【解决方案1】:

检查 web.xml 中 servlet 的 servlet-mapping 并确保您的 web url 像 http://localhost:8080/test/attempt

【讨论】:

  • 我已经试过很多次了。你可以看到上面的 web.xml 文件。 doGet 请求有效,但不是使用 Get 和 Path 注释配置的路径
【解决方案2】:

您的 TestAttempt 类不是 servlet,因为它没有扩展 HttpServlet。您能否进行此更改并重试。

【讨论】:

  • 即使在扩展 HttpServlet 之后它仍然给我一个 404
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 2021-08-01
相关资源
最近更新 更多