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

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

restlet中如何获取post方式提交的表单值_第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接受到了客户端提交的表单值,并输出,结果如下:



你可能感兴趣的:(restlet)