001.Jersey框架—基于JavaSE創(chuàng)建簡單RESTful服務(wù)

說明:本筆記是在學(xué)習(xí)《Java RESTful Web Service實戰(zhàn)》一書的筆記

一、項目結(jié)構(gòu)如下圖

項目結(jié)構(gòu)

二、POM.xml如下

<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.airkisser</groupId>
    <artifactId>simple-service</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>simple-service</name>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
        </dependency>
        <!-- uncomment this to get JSON support:
         <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.airkisser.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jersey.version>2.9</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

三航邢、代碼分析

Main.java(程序入口)

package com.airkisser;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.io.IOException;
import java.net.URI;

public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8080/simple-service/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // 配置掃描包
        final ResourceConfig rc = new ResourceConfig().packages("com.airkisser.api");

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
        System.in.read();
        server.shutdownNow();
    }
}

DeviceResource.java(資源)

package com.airkisser.api;

import com.airkisser.dao.DeviceDao;
import com.airkisser.entity.Device;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("device")
public class DeviceResource {

    private final DeviceDao deviceDao;

    // 注入Dao
    public DeviceResource() {
        this.deviceDao = new DeviceDao();
    }

    @GET
    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public Device get(@QueryParam("ip") final String deviceIp){
        Device result = null;
        if(deviceIp != null){
            result = deviceDao.getDevice(deviceIp);
        }
        return result;
    }

    @PUT
    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public Device put(final Device device){
        Device result = null;
        if(device != null) {
            result = deviceDao.updateDevice(device);
        }
        return result;
    }

}

DeviceDao.java(模擬的Dao)

package com.airkisser.dao;

import com.airkisser.entity.Device;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class DeviceDao {

    private ConcurrentMap<String, Device> fakeDB = new ConcurrentHashMap<>();

    public DeviceDao() {
        fakeDB.put("10.11.58.163", new Device("10.11.58.163"));
        fakeDB.put("10.11.58.185", new Device("10.11.58.185"));
    }

    public Device getDevice(String deviceIp) {
        return fakeDB.get(deviceIp);
    }

    public Device updateDevice(Device device) {
        String ip = device.getDeviceIp();
        if (ip != null && fakeDB.containsKey(ip)) {
           fakeDB.put(ip, device);
        }
        return fakeDB.get(ip);
    }
    
}

Device.java

package com.airkisser.entity;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "device")
public class Device {

    private String deviceIp;

    private int deviceStatus;

    public Device() {
    }

    public Device(String deviceIp) {
        this.deviceIp = deviceIp;
    }

    // @XmlAttribute只能注解在get方法上载萌,不能直接注解到屬性上
    @XmlAttribute
    public String getDeviceIp() {
        return deviceIp;
    }

    public void setDeviceIp(String deviceIp) {
        this.deviceIp = deviceIp;
    }

    @XmlAttribute
    public int getDeviceStatus() {
        return deviceStatus;
    }

    public void setDeviceStatus(int deviceStatus) {
        this.deviceStatus = deviceStatus;
    }
}

四、測試

ResourceTest.java

package com.airkisser;

import com.airkisser.entity.Device;
import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import static org.junit.Assert.assertEquals;

public class ResourceTest {

    private HttpServer server;
    private WebTarget target;

    @Before
    public void setUp() throws Exception {
        // start the server
        server = Main.startServer();
        // create the client
        Client c = ClientBuilder.newClient();

        // uncomment the following line if you want to enable
        // support for JSON in the client (you also have to uncomment
        // dependency on jersey-media-json module in pom.xml and Main.startServer())
        // --
        // c.configuration().enable(new org.glassfish.jersey.media.json.JsonJaxbFeature());

        target = c.target(Main.BASE_URI);
    }

    @After
    public void tearDown() throws Exception {
        server.shutdownNow();
    }

    @Test
    public void testGetDevice() {
        final String testIp = "10.11.58.185";
        final Device device = target.path("device").queryParam("ip", testIp).request().get(Device.class);
        assertEquals(testIp, device.getDeviceIp());
    }

    @Test
    public void testPutDevice() {
        final String testIp = "10.11.58.185";
        final Device device = new Device(testIp);
        device.setDeviceStatus(1);
        Entity<Device> entity = Entity.entity(device, MediaType.APPLICATION_XML_TYPE);
        final Device result = target.path("device").request().put(entity, Device.class);
        assertEquals(1, result.getDeviceStatus());
    }
}

SoapUI工具測試

device資源的get方法測試

device資源的get方法測試

device資源的put方法測試

device資源的put方法測試

備注

啟動程序后宋税,輸入http://localhost:8080/simple-service/application.wadl可查看WADL內(nèi)容

<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.9 2014-05-22 05:12:10"/>
    <doc xmlns:jersey="http://jersey.java.net/"
         jersey:hint="This is simplified WADL with user and core resources only. To get full WADL with extended resources use the query parameter detail. Link: http://localhost:8080/simple-service/application.wadl?detail=true"/>
    <grammars>
        <include href="application.wadl/xsd0.xsd">
            <doc title="Generated" xml:lang="en"/>
        </include>
    </grammars>
    <resources base="http://localhost:8080/simple-service/">
        <resource path="device">
            <method id="put" name="PUT">
                <response>
                    <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="device"
                                        mediaType="application/json"/>
                    <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="device"
                                        mediaType="application/xml"/>
                </response>
            </method>
            <method id="get" name="GET">
                <request>
                    <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="ip" style="query" type="xs:string"/>
                </request>
                <response>
                    <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="device"
                                        mediaType="application/json"/>
                    <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="device"
                                        mediaType="application/xml"/>
                </response>
            </method>
        </resource>
    </resources>
</application>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市讼油,隨后出現(xiàn)的幾起案子弃甥,更是在濱河造成了極大的恐慌,老刑警劉巖汁讼,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件淆攻,死亡現(xiàn)場離奇詭異,居然都是意外死亡嘿架,警方通過查閱死者的電腦和手機瓶珊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來耸彪,“玉大人伞芹,你說我怎么就攤上這事〔跄龋” “怎么了唱较?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長召川。 經(jīng)常有香客問我南缓,道長,這世上最難降的妖魔是什么荧呐? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任汉形,我火速辦了婚禮,結(jié)果婚禮上倍阐,老公的妹妹穿的比我還像新娘概疆。我一直安慰自己,他們只是感情好峰搪,可當(dāng)我...
    茶點故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布岔冀。 她就那樣靜靜地躺著,像睡著了一般概耻。 火紅的嫁衣襯著肌膚如雪使套。 梳的紋絲不亂的頭發(fā)上罐呼,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天,我揣著相機與錄音童漩,去河邊找鬼。 笑死春锋,一個胖子當(dāng)著我的面吹牛矫膨,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播期奔,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼侧馅,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了呐萌?” 一聲冷哼從身側(cè)響起馁痴,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肺孤,沒想到半個月后罗晕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡赠堵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年小渊,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片茫叭。...
    茶點故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡酬屉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出揍愁,到底是詐尸還是另有隱情呐萨,我是刑警寧澤,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布莽囤,位于F島的核電站谬擦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏朽缎。R本人自食惡果不足惜怯屉,卻給世界環(huán)境...
    茶點故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望饵沧。 院中可真熱鬧锨络,春花似錦、人聲如沸狼牺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽是钥。三九已至掠归,卻和暖如春缅叠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背虏冻。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工肤粱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人厨相。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓领曼,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蛮穿。 傳聞我的和親對象是個殘疾皇子庶骄,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內(nèi)容