Restlet restful 学习

首先添加 Restlet 需要的Maven Dependency:

    <dependency>
      <groupId>org.restlet.jse</groupId>
      <artifactId>org.restlet</artifactId>
      <version>${restlet-version}</version>
    </dependency>
    <dependency>
      <groupId>org.restlet.jee</groupId>
      <artifactId>org.restlet.ext.servlet</artifactId>
      <version>${restlet-version}</version>
    </dependency>

Restlet的version:

<restlet-version>2.3.1</restlet-version>

还有tomcat的plugin:

      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <!-- http port -->
          <port>8080</port>
          <!-- application path always starts with / -->
          <path>/</path>
        </configuration>
      </plugin>

web.xml中配置Restlet的 servlet:

  <servlet>
    <servlet-name>RestletServlet</servlet-name>
    <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
      <!-- Application class name -->
      <param-name>org.restlet.application</param-name>
      <param-value>com.tch.test.restlet.HelloApplication</param-value>
    </init-param>
  </servlet>

  
  <servlet-mapping>
    <servlet-name>RestletServlet</servlet-name>
    <url-pattern>/restlet/*</url-pattern>
  </servlet-mapping>

Application实现类:

package com.tch.test.restlet;

import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;

import com.tch.test.restlet.restprovider.DreamoftchServerResource;
import com.tch.test.restlet.restprovider.HelloWorldServerResource;

public class HelloApplication extends Application {

	@Override
	public Restlet createInboundRoot() {
		Router router = new Router(getContext());
		router.attach("/hello", HelloWorldServerResource.class);
		return router; 
	}
}

Restful 服务provider:

package com.tch.test.restlet.restprovider;

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class HelloWorldServerResource extends ServerResource{

    @Get
    public String getHello() {
        return "Hello World, this is hello world server resource ...";
    }
    
}

OK

启动tomcat: mvn tomcat7:run

浏览器访问:

http://localhost:8080/restlet/hello

http://localhost:8080/restlet/dreamoftch

就可以看到结果了。

或者通过 Restlet的 ClientResource类:

package com.tch.test.restlet;

import java.io.IOException;

import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

public class RestletTest {

    public static void main(String[] args) throws ResourceException, IOException  {
        new ClientResource("http://localhost:8080/restlet/hello").get().write(System.out);
    }
    
}

从控制台输出可以看到结果。

OK, Finish ...

猜你喜欢

转载自dreamoftch.iteye.com/blog/2216748
今日推荐