mini'CHEN

导航

javaEE REST 基于第三方框架Restlet

郭晨 软件151 1531610114 

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

}
复制代码

 

运行

posted on 2017-06-29 11:00  mini'CHEN  阅读(681)  评论(0编辑  收藏  举报