首页 > 解决方案 > @Path 没有响应 Eclipse Tomcat 中 Java servlet 中的基本 @GET 请求

问题描述

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

我用路径和获取注释配置的类是默认的(未命名的打包),如下所示:

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 而不是预期的:“知道了!”

标签: javaeclipseservletstomcat9

解决方案


您的类 TestAttempt 不是 servlet,因为它不扩展 HttpServlet。你能做这个改变,然后再试一次。


推荐阅读