资源预览内容
第1页 / 共4页
第2页 / 共4页
第3页 / 共4页
第4页 / 共4页
亲,该文档总共4页全部预览完了,如果喜欢就下载吧!
资源描述
Restlet 开发指南1. Java 对象Java 对象是实际操作对象的封装,目前可以从 http 提交的 xml 格式和 Json 格式自动转换为Java 类对象。1.1. XML 转换XmlRootElement(name=”user”)public class Userprivate String name;private String sex;private int id;public void setName(String name)this.name = name;public void setId(int id)this.id = id;public void setSex(String sex)this.sex = sex;public String getName()return this.name;public String getSex()return this.sex;public int getId()return this.id;如果 http 客户端提交的数据格式是 xml,Jsonmale10001Restlet 将会自动转化成一个 User 对象。2. Resource 对象Path(“/users”)class UsersResourceGETProduces(“application/xml”,”text/xml”)public UserList getUsers() . /UserList 也必须是个可转换 xml 的对象GETPath(“/id:d+”)Produces(“application/xml”,”text/xml”)public User getUser(PathParam(“id”) int id) . POSTConsumes(“application/xml”,”text/xml”)public int addUser(User user) . POSTConsumes(“application/json”)public int addUser(Representation rep)JsonRepresentation jrep = new JsonRepresentation(rep);JSONObject jobj = jrep.getJSONObject();User user = new User();user.setName(jobj.getString(“name”);user.setSex(jobj.getString(“sex”);user.setId(jobj.getInteger(“id”);return user.getId(); PUTPath(“/id:d+”)Consumes(“application/xml”, “text/xml”)public int updateUser(PathParam(“id”) int id, User usr) . DELETEPath(“/id:d+”)public int deleteUser(PathParam(“id”) int id) . 3. Applicationpublic class TestApplication extends javax.ws.rs.core.Application public TestApplication()super();public Set getClasses()final Set classes = new HashSet();classes.add(UsersResource.class);return classes;public Set getSingletons()/final Set singleton = new HashSet();/ singleton.add(new UserResource();/ return singleton;return null;4. 内部存储在系统运行过程中,返回存储的单一实例public class UserManagerprivate UserManager singleton = new UserManager();public static UserManager get()return singleton;private Map userDB= new HashMap();private IntCounter id = new IntCounter(100);public int addUser(User user)this.userDB.put(id.incrementInt(), user);return id.get();public int updateUser(int id, User user)this.userDB.replace(id, user);return id; public int deleteUser(int id)this.userDB.remove(id);return id;public User getUser(int id)return this.userDB.get(id);5. 启动 RESTpublic class RestMainpublic static void main(String args)Component com = new Component();Server server = com.getServers();server.add(Protocol.HTTP,8184);JaxRsApplication app = new JaxRsApplication(com.getContext().createChildContext();app.add(new TestApplication();com.getDefaultHost().attach(app);com.start();System.out.println(Server started on port + server.getPort();System.out.println(Press key to stop server);System.in.read();System.out.println(Stopping server);com.stop();System.out.println(Server stopped);
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号