如何仅使用注释(无 web.xml)设置 JAX-RS 应用程序? [英] How to set up JAX-RS Application using annotations only (no web.xml)?

查看:32
本文介绍了如何仅使用注释(无 web.xml)设置 JAX-RS 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅使用注释来设置 JAX-RS 应用程序?(使用 Servlet 3.0 和 JAX-RS Jersey 1.1.0)

Is it possible to set up a JAX-RS application using annotations only? (using Servlet 3.0 and JAX-RS Jersey 1.1.0)

我尝试过,但没有运气.似乎需要使用一些 web.xml.

I tried and had no luck. Using some web.xml seems required.

配置 A(有效,但有 web.xml 配置)

web.xml

   ...
   <servlet>
      <servlet-name>org.foo.rest.MyApplication</servlet-name>
   </servlet>
   <servlet-mapping>
       <servlet-name>org.foo.rest.MyApplication</servlet-name>
       <url-pattern>/*</url-pattern>
   </servlet-mapping>
   ...

Java

@ApplicationPath("/")
public class MyApplication extends Application {
    ...
}

<小时>

配置 B(不工作,抛出异常)

@ApplicationPath("/")
@WebServlet("/*") // <-- 
public class MyApplication extends Application {
    ...
}

后者似乎坚持应用程序将是 Servlet 的子类(例外情况无需猜测)

The latter seems to insist that the Application will be a subclass of Servlet (the exception leaves no guesswork)

java.lang.ClassCastException: org.foo.rest.MyApplication cannot be cast to javax.servlet.Servlet

<小时>

问题

  1. 为什么 web.xml 定义有效而注解无效?有什么区别?

  1. Why the web.xml definition worked but the annotation didn't? What's the difference?

有没有办法让它起作用,例如有没有 web.xml 的 JAX-RS 应用程序?

Is there a way to have it worked, e.g. have a JAX-RS Application with no web.xml?

推荐答案

看来我需要做的就是这个(Servlet 3.0 及以上)

It seems that all I needed to do is this (Servlet 3.0 and above)

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/*")
public class MyApplication extends Application {
    ...
}

显然不需要 web.xml 配置(在 Tomcat 7 上试过)

And no web.xml configuration was apparently needed (tried on Tomcat 7)

这篇关于如何仅使用注释(无 web.xml)设置 JAX-RS 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆