繁体   English   中英

使用Javax和Jersey Servlet调度程序的Java RESTful服务入门

[英]Getting started with Java RESTful service using javax, and Jersey Servlet dispatcher

我是Web服务的新手,正在尝试配置简单的REST服务。 我正在关注教程http://www.vogella.com/tutorials/REST/article.html

我的TestClass是

package com.test.servlettest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class TestRestService {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
       return "Hello Jersey";
    }
}

和web.xml是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
     <display-name>ServletTest</display-name>
     <servlet>
        <servlet-name>TestRestService</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.test.servlettest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestRestService</servlet-name>
        <url-pattern>/test/*</url-pattern>
    </servlet-mapping>
</web-app>

我到达网址时得到404

http://localhost:8080/ServletTest
http://localhost:8080/ServletTest/test
http://localhost:8080/ServletTest/test/hello

这里缺少什么,我不明白。

我可以理解,Jersey以某种方式提供了自己的Servlet实现,因此我不需要扩展HttpServlet。 但是应该重用此类,因为本教程说<param-value>说那里的服务包

编辑

部署了应用程序,我通过将Servlet类添加到同一包中来对其进行了验证

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse res) throws     ServletException, IOException {
     res.setContentType("text/html");
    PrintWriter out=res.getWriter();
    out.println("<html><body>Hello World</body></html>");

    }
 }     

现在,点击URL,

localhost:8080/ServletTest/TestServlet

给了我预期的结果

谢谢

最初我使用的是从下载的jar

Java2s链接,用于下载jar

我用jersey bundle 1.17asm 3.3.1代替了它。 当时有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM