`
嵇海波
  • 浏览: 13663 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

使用jersey构建J2SE及J2EE实现RESTful接口

 
阅读更多

       RESTful接口规范是一种类似于AJXA,使用现有技术实现的编码规范,可以理解为RESTful使用HTTP+URI+XML等技术实现的一套规范。目前RESTful的实现有很多种,比如apache的CXF、glassflash的jersey等实现。

       下面使用maven+jersey实现RESTful接口

        1.J2SE

         使用maven可以快速构建jersey项目并引入相关依赖。

package zxyjhb.jerseyDemo;

import com.sun.jersey.api.container.grizzly2.GrizzlyWebContainerFactory;
import org.glassfish.grizzly.http.server.HttpServer;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.UriBuilder;


public class Main {

    private static int getPort(int defaultPort) {
        //grab port from environment, otherwise fall back to default port 9998
        String httpPort = System.getProperty("jersey.test.port");
        if (null != httpPort) {
            try {
                return Integer.parseInt(httpPort);
            } catch (NumberFormatException e) {
            }
        }
        return defaultPort;
    }

    //初始化端口
    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://localhost/").port(getPort(9998)).build();
    }

    public static final URI BASE_URI = getBaseURI();
    //启动服务
    protected static HttpServer startServer() throws IOException {
        final Map<String, String> initParams = new HashMap<String, String>();
        //扫描包下的依赖
        initParams.put("com.sun.jersey.config.property.packages", "zxyjhb.jerseyDemo");

        System.out.println("Starting grizzly2...");
        return GrizzlyWebContainerFactory.create(BASE_URI, initParams);
    }
    
    public static void main(String[] args) throws IOException {
        // Grizzly 2 initialization
        HttpServer httpServer = 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();
        httpServer.stop();
    }    
}

具体资源类

package zxyjhb.jerseyDemo;

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

// The Java class will be hosted at the URI path "/myresource"
@Path("/myresource")
public class MyResource {

    // TODO: update the class to suit your needs
    
    // The Java method will process HTTP GET requests
    @GET 
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getIt() {
        return "Got it!";
    }
}

 

package zxyjhb.jerseyDemo;

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


import zxyjhb.jerseyDemo.dao.DeviceDao;
import zxyjhb.jerseyDemo.demain.Device;

@Path("/device")
public class DeviceResource {
	
	private DeviceDao deviceDao ;

	public DeviceDao getDeviceDao() {
		return deviceDao;
	}

	public void setDeviceDao(DeviceDao deviceDao) {
		this.deviceDao = deviceDao;
	}
	
	public DeviceResource(){
		deviceDao = new DeviceDao();
	}

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

  

运行结果

Starting grizzly2...
2015-9-11 14:11:02 org.glassfish.grizzly.http.server.NetworkListener start
信息: Started listener bound to [localhost:9998]
2015-9-11 14:11:02 org.glassfish.grizzly.http.server.HttpServer start
信息: [HttpServer] Started.
Jersey app started with WADL available at http://localhost:9998/application.wadl
Hit enter to stop it...

 查看WADL

<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.9-ea04 08/05/2011 10:08 AM"/>
<grammars/>
<resources base="http://localhost:9998/">
<resource path="/device">
<method name="GET" id="get">
<request>
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" type="xs:string" style="query" name="ip"/>
</request>
<response>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</response>
</method>
<method name="PUT" id="put">
<request>
<representation mediaType="*/*"/>
</request>
<response>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</response>
</method>
</resource>
<resource path="/myresource">
<method name="GET" id="getIt">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
</resources>
</application>

 test接口:

package zxyjhb.jerseyDemo;
import org.glassfish.grizzly.http.server.HttpServer;
import zxyjhb.jerseyDemo.demain.Device;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import junit.framework.TestCase;

/*
 * jersey 1.9 写法
 * 
 */

public class DeviceTest extends TestCase {

    private HttpServer httpServer;
    
    private WebResource r;

    public DeviceTest(String testName) {
        super(testName);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        
        //start the Grizzly2 web container 
        httpServer = Main.startServer();

        // create the client
        Client c = Client.create();
        r = c.resource(Main.BASE_URI);
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();

        httpServer.stop();
    }

 
    public void testGetDevice() {
    	final String deviceIp = "127.0.0.1";
    	Device device = r.path("device").queryParam("ip", deviceIp).get(Device.class);
        System.out.println(device.toString());
    }
  
    public void testPutDevice() {
    	final Device device = new Device("127.0.0.1","test2");
    	Device result = r.path("device").put(Device.class, device);
        System.out.println(result.toString());
    }

}

 运行结果:

Starting grizzly2...
2015-9-11 14:13:30 org.glassfish.grizzly.http.server.NetworkListener start
信息: Started listener bound to [localhost:9998]
2015-9-11 14:13:30 org.glassfish.grizzly.http.server.HttpServer start
信息: [HttpServer] Started.
Device [deviceIp=127.0.0.1, deviceStatus=connect]
2015-9-11 14:13:31 org.glassfish.grizzly.http.server.NetworkListener stop
信息: Stopped listener bound to [localhost:9998]
Starting grizzly2...
2015-9-11 14:13:31 org.glassfish.grizzly.http.server.NetworkListener start
信息: Started listener bound to [localhost:9998]
2015-9-11 14:13:31 org.glassfish.grizzly.http.server.HttpServer start
信息: [HttpServer-1] Started.
Device [deviceIp=127.0.0.1, deviceStatus=test2]
2015-9-11 14:13:31 org.glassfish.grizzly.http.server.NetworkListener stop
信息: Stopped listener bound to [localhost:9998]

 2.J2EE实现

     使用maven构建jersey的webapp项目

     生成的web.xml文件,在web.xml文件中配置application

    

<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container, 
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e194 -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</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>zxyjhb.jersey_webapp</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webresources/*</url-pattern>
    </servlet-mapping>
</web-app>

  具体的资源类

  

package zxyjhb.jersey_webapp;

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

/** Example resource class hosted at the URI path "/myresource"
 */
@Path("/myresource")
public class MyResource {
    
    /** Method processing HTTP GET requests, producing "text/plain" MIME media
     * type.
     * @return String that will be send back as a response of type "text/plain".
     */
    @GET 
    @Produces("text/plain")
    public String getIt() {
        return "Hi there!";
    }
}

 运行结果

 

 

 

 

 

  • 大小: 27.9 KB
分享到:
评论

相关推荐

    Java-J2se、J2ee开发全程视频教程和源码(87集)

    资源名称:Java-J2se、J2ee开发全程视频教程和源码(87集)资源目录:【】Java-J2se-J2ee全程教程(01-10)【】Java-J2se-J2ee全程教程(11-20)【】Java-J2se-J2ee全程教程(21-30)【】Java-J2se-J2ee全程教程(31...

    J2SE,J2EE学习笔记

    Java技术体系主要包括三个主要部分:J2SE(Java 2 Platform, Standard Edition)、J2EE(Java 2 Platform, Enterprise Edition)和J2ME(Java 2 Platform, Micro Edition)。J2SE是Java平台的基础,提供了用于开发和...

    J2SE_J2EE帮助文档

    J2SE是Java开发的基础,提供了运行Java应用程序所需的环境,而J2EE则是一个用于构建企业级应用的平台,它基于J2SE并增加了许多高级服务,如多层架构、分布式计算、事务处理、安全性和资源管理等。 J2SE是Java的核心...

    J2SE 和 J2EE api 帮助文档

    Java平台由多个组件构成,其中J2SE(Java 2 Platform, Standard Edition)和J2EE(Java 2 Platform, Enterprise Edition)是两个关键部分,它们都提供了丰富的API供开发者使用。本文将深入探讨这两个平台及其API,...

    J2SE+J2EE知识点

    J2SE+J2EE所有知识点汇总,简单而不失详细。是复习和预习的重要参考资料。

    很全的Java 面试题。J2SE+J2EE+JAVAWEB

    面试官可能会问及如何使用这些技术构建动态网页,以及它们之间的交互方式。 **面试题**:这类资源通常包含各种编程挑战、概念理解、最佳实践和设计模式的问题。面试者应该准备回答关于异常处理、内存管理(垃圾回收...

    JAVA_API.rar_JAVA_API_j2se j2EE api_j2se api j2ee api_j2se j2ee

    Java API是Java编程语言的核心组成部分,它为开发者提供了丰富的类库和接口,使得开发者能够构建高效、可移植的软件应用。这个"JAVA_API.rar"压缩包包含的是JAVA_API的中文帮助文档,特别是针对j2se(Java 2 ...

    j2se和j2ee帮助文档

    学习如何使用J2SE中的类库来解决常见问题,如文件操作、网络通信、并发处理等,将为后续的J2EE学习打下坚实基础。 J2EE的学习则需要对Web开发有深入的理解,包括HTTP协议、动态网页生成以及服务器端编程。Servlet是...

    Java学习笔记(从j2se到j2ee都有)

    不好意思,两个笔记是一样的,是上传的时候没注意,见谅。 分要的非常高,觉得有必要再下. 二年以上Java经验请不要下载. 二年以下应该能从中得到一些东西的,因为是比较全面的. 不管怎么样,觉得有必要才去下,下了又要...

    浅析J2EE,J2SE,J2ME

    分析对比J2EE,J2SE,J2ME,比较简单移动,挺不错一个期刊

    韩顺平 java 课堂笔记(超全 jsp,j2se,j2ee)

    韩顺平 java 课堂笔记(超全 jsp,j2se,j2ee)

    J2SE和J2EE的API文档

    Java平台由一系列技术组成,其中J2SE(Java 2 Platform, ...通过深入学习J2SE和J2EE的API,开发者可以构建出高效、可扩展且可靠的软件系统。在实际项目中,理解并熟练运用这些API是提升开发效率和代码质量的关键。

    J2SE和J2EE的开发API

    Java平台由多个版本组成,其中J2SE(Java 2 Platform, Standard Edition)和J2EE(Java 2 Platform, Enterprise Edition)是两个关键部分,它们提供了广泛的API用于开发不同类型的Java应用程序。J2SE是Java的基础,...

    java培训课件(j2se+j2ee)

    "java培训课件(j2se+j2ee)"标题表明这是一份涵盖了Java标准版(J2SE)和企业版(J2EE)的教程资料。J2SE是Java的核心部分,提供了构建桌面应用和网络服务的基础;而J2EE则是为了开发和部署分布式企业级应用而设计...

    Java(J2SE、J2EE)学习小结

    本文将围绕Java的基础知识、进阶概念以及一些常见面试题进行探讨,帮助读者深入理解Java J2SE(Java标准版)和J2EE(Java企业版)的学习要点。 1. 面向对象思想:面向对象编程(OOP)是Java的核心,它强调通过对象...

    J2SE,J2EE, java自学之路

    Java分为几个主要的版本,如J2SE(Java Standard Edition)、J2EE(Java Enterprise Edition)和J2ME(Java Micro Edition)。每个版本都有其特定的应用场景和学习路径。 首先,J2SE是Java的基础,涵盖了面向对象...

    java面试宝典(J2SE+J2EE+DB+EJB+算法)

    几乎涵盖所有的知识点,希望对你有所帮助.

    j2se,j2ee,html,js,jquery,Oracle等基本开发手册

    Java 2 Platform Enterprise Edition (J2EE) 是一个用于构建企业级分布式应用的平台,它包含了服务器端组件模型、事务管理、安全性和数据库连接等功能。J2EE 提供了Servlet、JSP(JavaServer Pages)、EJB...

    J2SE J2EE api chm

    《J2SE J2EE API CHM》是一个包含Java开发重要参考资料的压缩包,主要针对Java平台的两个重要部分:Java Standard Edition (J2SE) 和 Java Enterprise Edition (J2EE)。这些API文档通常以CHM(Compiled Help Manual...

Global site tag (gtag.js) - Google Analytics