REST-style API development practice: Based on Idea+maven+jersey__rest

Source: Internet
Author: User
Tags http post glassfish

In application development, a large number of CRUD operations are performed on resources, and crud refers to Creation (create), get (Read), update (update), and Destroy (DELETE). 2000 Roy Fielding in his Ph. D. thesis "Architectural Styles and the design of network-based Software architectures" Architecture and web-based Software architecture Design "Rest" is proposed. REST representational The abbreviation of the state Transfer (general Chinese translation is a descriptive status transfer). Everything in rest is considered a resource. Each resource has a URI and corresponds to it. Use a unified interface to process resources in rest. As with database crud operations (Create, Read, Update, and delete), you can use post, get, put, and delete to process rest resources.
The Jersey RESTful Framework is an Open-source RESTful framework that implements the Jax-rs (JSR 311 & JSR 339) specification. It expands the Jax-rs reference implementation, provides additional features and tools to further simplify RESTful service and client development, similar to struts, and can be consolidated with hibernate,spring frameworks.

This article uses Idea+maven+jersey to develop the rest-style interface (API). I. Practical environment and Objectives

1, through Maven to protect jersey dependency integrity

2, development environment for idea, the real operation of the database, using the simulation method

4, the operating environment for Tomcat

3, through practice to complete the rest-style crud operations.
second, the project constructs

1. Create the project

Create a new model inside idea, choose Java Enterprise, SDK uses Java 1.7, application server is TOMCAT7. Application Framework to check WEB application 3.1

After Next, enter the project name in the model name Restapi

2. Project configuration

After the project is created, we also need to add MAVEN support, and of course you can download the Jersey Library yourself, and the benefit of MAVEN is that the integrity tool itself will be automatically completed. Right click on Project name, pop-up menu, select Add Framework Support:

Select MAVEN on the new pop-up interface and click OK.

Configure artifacts to complete the compilation and Release configuration. The practice is, through the Build menu, open build Artifacts->edit open artifacts, available elements inside, under their own model (RESTAPI), select Maven began a dependent library, right-click , choose put Int/web-inf/lib

Once the processing is complete, the following figure shows the configuration

The overall engineering structure is shown in the following illustration:

third, the development of coding

1. Configure Maven

Edit Maven's profile Pom.xml with the following code:

<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "HTT" P://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apach E.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> &LT;GROUPID&GT;COM.STUDY.RESTFUL&L t;/groupid> <artifactId>RestApi</artifactId> <version>1.0-SNAPSHOT</version> <d
            Ependencies> <dependency> <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId> <version>2.17</version>
            </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.17</version> </ Dependency>;d ependency> <groupId>org.glassfish.jersey.media</groupId> <artifactid>jersey -media-json-jackson</artifactid> <version>2.17</version> </dependency> &L T;/dependencies> </project>
After editing, you will be prompted to error, because there is no configuration of the content, the implementation of the correction, MAVEN will automatically download the dependent dependencies, download completed will not prompt error.

2, configure the project Web.xml

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" HT Tp://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" Http://xmlns.jcp.org/xml/ns/javaee HTTP://XMLNS.JCP . Org/xml/ns/javaee/web-app_3_1.xsd "version=" 3.1 "> <servlet> <servlet-name>jax-rs Se Rvlet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.servletcontainer</servlet-class
            > <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.study.restful</param-value> </init-param> <load-on-startu p>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jax-rs servlet </servlet-name> <url-pattern>/restapi/*</url-pattern> </servlet-mapping> </web-ap P>
This is the Param-value com.study.restful is the project package structure Url-pattern refers to the project after the release of the URL path to the above code as an example, the following access address: Http://localhost:8080/restapi /Service name ....

3. Write Data layer

The data layer contains entities, DAO layers, crud operations, because the CRUD operations involve specific databases, typically with Hibernate or mybaits, this project is just a practice of rest, so the crud operations of the DAO layer are just simulations.

1) Entity

Package com.study.restful.entity;

Import javax.xml.bind.annotation.XmlRootElement;
Import java.io.Serializable;

@XmlRootElement public
class User  implements Serializable {

    private static final long serialversionuid = 1L;

    private int id;
    private String name;
    Private String phone;

    public int getId () {return
        ID;
    }

    public void setId (int id) {
        this.id = ID;
    }

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    Public String Getphone () {return
        phone;
    }

    public void Setphone (String phone) {
        this.phone = phone;
    }
}
A user entity is created with attributes and actions. Note with @xmlrootelement annotations before class names, you can map entities to XML

2) DAO layer

Package Com.study.restful.dao;

Import Com.study.restful.entity.User;

    public class Userdao {user user;
        Public Userdao () {User user = new user ();
        User.setid (1);
        User.setname ("Solo");
        User.setphone ("13799008888");
    This.user = user;
    Public Userdao (user user) {this.user = user;  //crud Create public void CreateUser (int id, string name, String phone) {System.out.println ("CRUD Opt:
        Create a user ");
        User.setid (ID);
        User.setname (name);
        User.setphone (phone);

    Dboptcreate (user);
    //crud Query public User readuserbyname (String name) {return dboptquery (name); //crud Modify public void updateuser (int id, string name, String phone) {System.out.println ("CRUD Opt: Repair
        Change a user ");
        User.setid (ID);
        User.setname (name);
        User.setphone (phone);

    Dboptupdate (user); //crud Delete public void deleteuser (int ID) {System.out.println ("CRUD Opt: Delete a user");
    Dboptdelete (ID);
    //Simulate database operations private void dboptcreate (user user) {System.out.println ("database operation, create success");
    private void dboptupdate (user user) {System.out.println ("database operation, modified successfully");
    private void dboptdelete (int id) {System.out.println ("database operation, delete succeeded");
        //Analog database operation private user dboptquery (String name) {User user= new user ();
        Constructing a simulation data user.setid (1);
        User.setname (name);
        User.setphone ("13988886666");
        SYSTEM.OUT.PRINTLN ("Database operation, query Success");
    return user;
 }


}
This simulates the crud operation.

4, writing business layer

Business layer, here is reflected in the external service interface UserService, specifically see the following categories

Package com.study.restful;
Import Com.study.restful.dao.UserDao;

Import Com.study.restful.entity.User;
Import javax.ws.rs.*;

Import Javax.ws.rs.core.MediaType;
    @Path ("/userservice") public class UserService {Userdao Userdao = new Userdao ();

    String msg;
    @GET @Produces (mediatype.text_plain) public String SayHello () {return ' Hello, Service is runing '; @GET @Path ("/{username}") @Produces ("Text/plain;charset=utf-8") public String Sayhello2userbytext (@Path
    Param ("username") String username) {return "Hello" + username; }//crud @POST @Path ("/create/{id}/{username}/{phone}") @Produces ({Mediatype.application_json}) pub
        Lic string CreateUser (@PathParam ("id") int ID, @PathParam ("username") string name, @PathParam ("phone") string phone) { Userdao.
        CreateUser (ID, name, phone);
    Return "Create User:" + id+ "," +name+ "," +phone+ "sucessfully!"; @GET @Path ("/get") @ProducEs ({Mediatype.application_json}) public User readuserbyname (@QueryParam ("username") String username) {Syste
        M.OUT.PRINTLN (username);
        User user = Userdao.readuserbyname (username);
        System.out.println (User.getname ());
    return user; The//@GET the browser is a GET request @PUT @Path ("/updateuser/{id}/{username}/{phone}") @Produces (MEDIATYPE.APPLICATION_JSO N)//Modify public String UpdateUser (@PathParam ("id") int ID, @PathParam ("username") String name, @PathParam ("Phone") S

        Tring phone) {userdao.updateuser (ID, name, phone);
    Return "Update User:" + id+ "," +name+ "," +phone+ ", Run sucessfully!"; @DELETE @Path ("/deleteuser/{id}") @Produces (Mediatype.application_json) public String deleteuser (@PathP
        Aram ("id") int id) {userdao.deleteuser (ID);
    Return "Delete User:" + id+ ", Run sucessfully!";
 }



}
5. Publish and run

We've already configured artifacts, now just build and run.

Iv. Commissioning and testing

1 using the browser to test the Get Method (query)

CRUD operations, finding mapped HTTP GET
Http://localhost:8080/restapi/UserService/get?username=solo

Because the browser HTTP operation is a get call, the following operation requires a tool such as postman or Soapgui tool, otherwise there will be a 405 exception

CRUD operations, creating a mapped HTTP Post
http://localhost:8080/restapi/UserService/create/2/solo/13399991111



CRUD operations, modifying maps HTTP put
http://localhost:8080/restapi/UserService/updateUser/2/solo/13399997777


CRUD operations, removing mapped HTTP delete
Http://localhost:8080/restapi/UserService/deleteUser/2

v. Supplementary Materials

Some other restful frameworks:

Dropwizard
Jersey
Ninja Web Framework
Play Framework
Restlet
Restx
Spark Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.