如何仅使用注释设置JAX-RS应用程序(没有web.xml)? [英] How to set up JAX-RS Application using annotations only (no web.xml)?
问题描述
是否可以仅使用注释设置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
问题
-
为什么web.xml定义有效但注释没有?有什么区别?
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)
@ApplicationPath("/*")
public class MyApplication extends Application {
...
}
并且没有显然需要web.xml配置(在Tomcat 7上试用)
And no web.xml configuration was apparently needed (tried on Tomcat 7)
这篇关于如何仅使用注释设置JAX-RS应用程序(没有web.xml)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!