使用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!";
    }
}

 运行结果
使用jersey构建J2SE及J2EE实现RESTful接口_第1张图片
 

 

 

 

 

你可能感兴趣的:(使用jersey构建J2SE及J2EE实现RESTful接口)