restlet中如何获取post方式提交的表单值

来源:互联网 发布:koala for mac 下载 编辑:程序博客网 时间:2024/05/18 03:26

1.建立工程,项目结构如下:


2.编写资源超处理类:(FirstServerResource.java)

FirstServerResource.java代码如下:

package test;import org.restlet.data.Form;import org.restlet.representation.Representation;import org.restlet.resource.ServerResource; //定义一个资源public class FirstServerResource extends ServerResource {         @Override      //处理post请求    protected Representation post(Representation entity) {      //获取表单值:        Form form = new Form(entity);          String name = form.getFirstValue("name");          String sex = form.getFirstValue("sex");         System.out.println(name + ";" + sex);        return null;      }  }

2.编写服务应用类:ServerApplication.java

ServerApplication.java代码如下:

package test;import org.restlet.Application;import org.restlet.Context;import org.restlet.Restlet;import org.restlet.Server;import org.restlet.data.Protocol;import org.restlet.routing.Router; //为资源配置路径public class ServerApplication extends Application {    public static void main(String[] args) throws Exception {    //开启web服务,端口号为8182        new Server(Context.getCurrent(), Protocol.HTTP, 8182, FirstServerResource.class).start();    }         public ServerApplication(Context context) {        super(context);    }        @Override    public Restlet createInboundRoot() {        Router router = new Router(this.getContext());      //绑定资源路径"hello"到对应的处理资源类(FirstServerResource)        router.attach("/hello", FirstServerResource.class);        return router;    }     }

3.编写测试客户端:Client.java:

Client.java代码如下:

package test;import java.io.IOException;import org.restlet.data.Form;import org.restlet.representation.Representation;import org.restlet.resource.ClientResource;import org.restlet.resource.ResourceException; public class Client {    public static void main(String[] args) throws ResourceException, IOException {        String url = "http://localhost:8182/hello";     ClientResource client = new ClientResource(url);    //创建表单     Form form = new Form();           form.add("name", "zhuxun");           form.add("sex", "M");           //以post方式提交表单     Representation representation = client.post(form);     System.out.println(representation.getText());    }}


4.启动服务器(ServerApplication.java)

5.启动测试客户端(Client.java),可以看到资源处理类FirstServerResource.java接受到了客户端提交的表单值,并输出,结果如下:



原创粉丝点击