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