【JavaEE REST】基于第三方框架Restlet

准备工作:

< 下载

下载:http://www.restlet.org/downloads/stable

Edition for JavaEE -> Zip Archive

解压缩

< 添加JAR文件

将restlet/libs/目录下:org.restlet.jar文件和org.restlet.ext.servlet.jar文件添加项目Class Build Path

1、修改web.xml文件

添加URL模式(<url-pattern>)到Servlet的映射关系

设置Servlet的初始化参数(<init-param>),参数名(<param-name>)为org.restlet.application,参数值(<param-value>)为Application子类

示例:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>RESTServer</display-name>
  <servlet>
      <servlet-name>helloworld</servlet-name>
      <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
      <init-param>
          <param-name>org.restlet.application</param-name>
          <param-value>com.example.HelloWorldApplication</param-value>
      </init-param>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>helloworld</servlet-name>
      <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

2、新建Application子类和ServerResource子类

< 新建Application子类

重写public Restlet createInboundRoot()方法,设置URL模式路由规则

示例:

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

public class HelloWorldApplication extends Application {

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

}

< 新建ServerResource子类

新建public方法,标记@Get 等HTTP方法

示例:

package com.example;

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


public class HiResource extends ServerResource {
    
    @Get
    public String getHi() {
        return "Hi!";
    }

}

运行

测试地址:

http://localhost:8080/<project-name>/hi

参考:http://web.archive.org/web/20120120070051/http://wiki.restlet.org/docs_2.1/13-restlet/275-restlet/312-restlet.html

转载于:https://www.cnblogs.com/dyingbleed/archive/2013/01/22/2871228.html

猜你喜欢

转载自blog.csdn.net/weixin_33982670/article/details/93301845