【问题标题】:Simple JAX-RS with Tomcat - 404 Not Found (No web.xml)带有 Tomcat 的简单 JAX-RS - 404 未找到(无 web.xml)
【发布时间】:2020-02-24 08:52:01
【问题描述】:

服务

    @Path("/rest")
    public class JustService {

        @GET
        @Produces("text/plain")
        @Path("sayhi")
        public String sayhi(){
            return "Hi";
        }
     }

应用程序配置

@ApplicationPath("/*")
public class ApplicationConfig extends Application {

}

Tomcat 在端口 8080 上运行,这是我发送的 Postman 请求: localhost:8080/rest/sayhi
回复

"status": 404,
    "error": "Not Found",
    "message": "No message available",

这是 POM.XML

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

修复 任何遇到这个问题的人都可以解决这个问题->正如@cassiomolin所建议的那样 在您的ApplicationConfig 中将扩展类从Application 更改为-> ResourceConfig,然后添加:

@Component
public class JerseyConfig() extends ResourceConfig{
    // I also changed the name of class to JerseyConfig (this is optional of course )

     public JerseyConfig() {
         register(JustService.class);
     }
     //change JustService to your service class and add as many register's as service classes you have.
    // you can add @ApplicationPath annotation to this class if you need to

【问题讨论】:

    标签: java tomcat jersey jax-rs


    【解决方案1】:

    删除 spring-boot-starter-web 依赖项并仅使用 spring-boot-starter-jersey 依赖项。然后用@Component注释JustService类:

    @Component
    @Path("/rest")
    public class JustService {
        ...
    }
    

    最后将以下类添加到您的应用程序中:

    @Component
    public class JerseyConfig extends ResourceConfig {
    
        public JerseyConfig() {
            register(JustService.class);
        }
    }
    

    更多详情请参考Spring Bootdocumentation

    【讨论】:

    • 嘿,成功了!谢谢,但我很困惑,我的 ApplicationConfig.java 似乎并没有做任何事情,我设置了 ApplicationPath("/jaxrs") 并创建了你的 JerseyConfig,url 必须类似于 - localhost:8080/jaxrs/rest/sayhi ,但它仅在 url 路径中没有 jaxrs 时有效。 ://
    • @TornikeShelia 将@ApplicationPath 注释添加到JerseyConfig。并删除您的 ApplicationConfig 课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2012-09-18
    • 2018-08-16
    • 2016-09-11
    相关资源
    最近更新 更多