【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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM