簡體   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