2KB项目,专业的源码交易网站 帮助 收藏 每日签到

使用 NetBean 7、Jersey 构建 REST 服务并返回 JSON 数据

  • 时间:2019-01-23 18:43 编辑:2KB 来源:2KB.COM 阅读:355
  • 扫一扫,手机访问
  • 分享
摘要: 英文原文:Bui
英文原文:Build a REST service with Netbeans 7, Java, and Jersey that returns JSON

Jersey 最强的地方就是用来构建 REST 服务,本文将使用 NetBeans 内置的 Maven 支持来构建一个简单的 REST 服务,该服务返回 JSON 数据。

首先我们创建一个新的 Maven Web Application 名为 RestJson

你可以删除默认创建的 index.jsp 文件,然后右击 Dependencies 选择添加 jersey-server-linking 作为 jersey-json.

这里是完整的 POM 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.giantflyingsaucer</groupId>
    <artifactId>RestJson</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
 
    <name>RestJson</name>
 
    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server-linking</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
 
</project>


接下来是创建一个扩展自 PackagesResourceConfig 的类,在本项目中我们无需 web.xml

创建一个新类名为 RestJsonApplication 包名是 com.giantflyingsaucer.restjson

RestJsonApplication.java 源码如下:

packagecom.giantflyingsaucer.restjson;
 
importcom.sun.jersey.api.core.PackagesResourceConfig;
importjavax.ws.rs.ApplicationPath;
 
 
@ApplicationPath("/")
publicclassRestJsonApplicationextendsPackagesResourceConfig {
 
    publicRestJsonApplication() {
        super("com.giantflyingsaucer.restjson.v1.resources.impl");
    }
}

接下来我们再创建一个新类 Item 使用包名:com.giantflyingsaucer.restjson.v1.resources

v1 是什么呢?无所谓,只是便于识别的版本。

Item.java 源码如下:

packagecom.giantflyingsaucer.restjson.v1.resources;
 
importjavax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
publicclassItem {
     
    privateintid;
    privateString name;
    privateString description;
     
    publicItem() {}
     
    publicItem(intid, String name, String description) {
        this.id = id;
        this.name  = name;
        this.description = description;
    }
 
    publicString getDescription() {
        returndescription;
    }
 
    publicvoidsetDescription(String description) {
        this.description = description;
    }
 
    publicintgetId() {
        returnid;
    }
 
    publicvoidsetId(intid) {
        this.id = id;
    }
 
    publicString getName() {
        returnname;
    }
 
    publicvoidsetName(String name) {
        this.name = name;
    }
}

在同一个包下添加另外一个类 ItemResource

package com.giantflyingsaucer.restjson.v1.resources;
 
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
public interface ItemResource {
    // Example: Returning more than one Item
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    List<Item> getItems();
}

这是服务定义接口。

接续创建一个接口的实现类 ItemResourceImpl ,包名是 com.giantflyingsaucer.restjson.v1.resources.impl

ItemResourceImpl.java 源码如下:

packagecom.giantflyingsaucer.restjson.v1.resources.impl;
 
importcom.giantflyingsaucer.restjson.v1.resources.Item;
importcom.giantflyingsaucer.restjson.v1.resources.ItemResource;
importjava.util.ArrayList;
importjava.util.List;
importjavax.ws.rs.Path;
 
// Set the path, version 1 of API
@Path("/v1/item")
publicclassItemResourceImplimplementsItemResource{
 
    @Override
    publicListgetItems() {
        Listitems =newArrayList();
        items.add(newItem(100,"Widget","A basic widget"));
        items.add(newItem(200,"SuperWidget","A super widget"));
        items.add(newItem(300,"UberSuperWidget","A uber super widget"));
         
        returnitems;
    }
}

为了简单,我们固定返回一些数值,并自动转换为 JSON 格式。

使用 Netbeans 7 内置对 Maven 的支持,执行 Clean and Build 操作(右击项目),然后发布 WAR 包到 Tomcat 7 中,因为需要 Servlet 3.0 的支持。

好了,试试访问:

http://localhost:8080/RestJson-1.0-SNAPSHOT/v1/item

得到的结果是

 Results:
{ "item" : [ { "description" : "A basic widget",
        "id" : "100",
        "name" : "Widget"
      },
      { "description" : "A super widget",
        "id" : "200",
        "name" : "SuperWidget"
      },
      { "description" : "A uber super widget",
        "id" : "300",
        "name" : "UberSuperWidget"
      }
    ] }

你可以从这里获取整个项目的源码。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。 2KB翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。


2KB项目(www.2kb.com,源码交易平台),提供担保交易、源码交易、虚拟商品、在家创业、在线创业、任务交易、网站设计、软件设计、网络兼职、站长交易、域名交易、链接买卖、网站交易、广告买卖、站长培训、建站美工等服务

  • 全部评论(0)
资讯详情页最新发布上方横幅
最新发布的资讯信息
【计算机/互联网|】Nginx出现502错误(2020-01-20 21:02)
【计算机/互联网|】网站运营全智能软手V0.1版发布(2020-01-20 12:16)
【计算机/互联网|】淘宝这是怎么了?(2020-01-19 19:15)
【行业动态|】谷歌关闭小米智能摄像头,因为窃听器显示了陌生人家中的照片(2020-01-15 09:42)
【行业动态|】据报道谷歌新闻终止了数字杂志,退还主动订阅(2020-01-15 09:39)
【行业动态|】康佳将OLED电视带到美国与LG和索尼竞争(2020-01-15 09:38)
【行业动态|】2020年最佳AV接收机(2020-01-15 09:35)
【行业动态|】2020年最佳流媒体设备:Roku,Apple TV,Firebar,Chromecast等(2020-01-15 09:31)
【行业动态|】CES 2020预览:更多的流媒体服务和订阅即将到来(2020-01-08 21:41)
【行业动态|】从埃隆·马斯克到杰夫·贝佐斯,这30位人物定义了2010年代(2020-01-01 15:14)
联系我们

Q Q: 7090832

电话:400-0011-990

邮箱:7090832@qq.com

时间:9:00-23:00

联系客服
商家入住 服务咨询 投拆建议 联系客服
0577-67068160
手机版

扫一扫进手机版
返回顶部