@Path没有响应Eclipse Tomcat中Java servlet中的基本@GET请求

问题描述 投票:0回答:2

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

java eclipse servlets tomcat9
2个回答
1
投票

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


0
投票

在web.xml中检查servlet的servlet映射,并确保你的web url像http://localhost:8080/test/attempt一样

© www.soinside.com 2019 - 2024. All rights reserved.