RESTful on Play! framework

前端 未结 6 515
攒了一身酷
攒了一身酷 2020-11-28 00:16

We are planning a project primarily serving content to mobile apps, but need to have a website.

My question is whether is makes sense to use Jersey or Restlet to dev

6条回答
  •  眼角桃花
    2020-11-28 00:59

    Use Play! to do it all. Writing REST services in Play is very very easy.

    Firstly, the routes file makes it straightforward to write routes that conform to the REST approach.

    Then, you write your actions, in the controller, for each API method you want to create.

    Depending on how you want to return the result (XML, JSON etc), there are a few methods you can use. For example, using the renderJSON method, allows the results to be rendered very easily. If you want to render XML, then you can just do so in the same way as you would build an HTML document in your View.

    Here is a neat example.

    routes file

    GET     /user/{id}            Application.getUser(format:'xml')
    GET     /user/{id}/json       Application.getUserJSON
    POST    /user/                Application.createUser
    PUT     /user/{id}            Application.updateUser
    DELETE  /user/{id}            Application.deleteUser
    

    Application file

    public static void createUser(User newUser) {
        newUser.save();
        renderText("success");
    }
    
    public static void updateUser(Long id, User user) {
        User dbUser = User.findById(id);
        dbUser.updateDetails(user); // some model logic you would write to do a safe merge
        dbUser.save();
        renderText("success");
    }
    
    public static void deleteUser(Long id) {
        // first check authority
        User.findById(id).delete();
        renderText("success");
    }
    
    public static void getUser(Long id)  {
        User user = User.findById(id)
        renderJSON(user);
    }
    
    public static void getUserJSON(Long id) {
        User user = User.findById(id)
        renderJSON(user);
    }
    

    getUser.xml file

    
       ${user.name}
       ${user.dob}
       .... etc etc
    
    

提交回复
热议问题