构建第一个RESTful服务

1、导入所需要的jar包

org.restlet.jar

org.restlet.ext.servlet.jar

2、package cn.jess;

import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

public class TestResource extends ServerResource{
   
    @Get
    public String getResultGet()
    {
        return "This is my first REST";
    }
    @Post
    public String getResultPost(Representation entity)
    {
        Form form = new Form(entity);
        String first = form.getFirstValue("first");
        String second = form.getFirstValue("second");
        int a = Integer.parseInt(first);
        int b = Integer.parseInt(second);
       
        return "The result of "+a+"+"+b +" is "+(a+b);
    }
}

package cn.jess;

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

public class RouterPath extends Application {

    public RouterPath(Context parentContext) {
        super(parentContext);
        }
   
    @Override
    public Restlet createInboundRoot()
    {
        Router router = new Router(getContext());
        router.attach("/greeting", TestResource.class);
        return router;
    }
   
   
    public synchronized Restlet createRoot() {
        // Create a router Restlet that routes each call to a
        // new instance of HelloWorldResource.
         Router router =new Router(getContext());
       
        // Defines only one route
         router.attachDefault(TestResource.class);
       
        return router;
         }
}

3、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name></display-name>   
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <context-param>
      <param-name>org.restlet.application</param-name>
      <param-value>cn.jess.RouterPath</param-value>
  </context-param>
 
  <servlet>
      <servlet-name>RestletServlet</servlet-name>
      <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
      <servlet-name>RestletServlet</servlet-name>
      <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

4、输入http://ip地址:port/工程名,就可以访问了

第一个RESTful就搞好了

你可能感兴趣的:(Restful)