A brief summary of the webservice framework jersey

More need to use webservice in the project, specifically the use of jersey. So first of all, you need to understand the relationship between jersey and webservice, and follow the various implementations of the webservice framework. By consulting related blogs, I personally summarize the structure diagram of webservice as follows:

 

 

 

Through the above picture, you can probably understand the relationship between webservice and jersey, and then we need to understand what RESTful is, and we are not very clear, so you can read this blog address: REST introduction: http://redhacker.iteye.com/ blog/1923226

Then, knowing some conceptual definitions, you can use jersey specifically, and make a jerseyDemo to briefly describe the use of the name jersey. In addition, the version of jersey1.X is an independent jar package provided by sun company. In version 2.X, jersey has been placed under glassfish. At the same time, Java also supports jersey's webservice, and the packages that support webservice's annotations are all in the javax.ws.rs.* package.

jersey common annotations explain:                                                                             

 

Annotation effect illustrate
@GET query request Equivalent to database query data operations
@POST insert request Equivalent to database insert data operation
@PUT update request Equivalent to database update data operation
@DELETE delete request It is equivalent to the delete data operation of the data
@Path uri road diameter Define the access path of the resource, through which the client accesses the resource. For example: @Path("user")
@Produces Specifies the return MIME format The resource is returned according to the data format, and the available values ​​are: MediaType.APPLICATION_XXX. For example: @Produces(MediaType.APPLICATION_XML)
@Consumes Accept the specified MIME format Only requests that match this parameter setting can access this resource. For example @Consumes("application/x-www-form-urlencoded")
@PathParam uri path parameter Write it in the parameters of the method to get the request path parameters. For example: @PathParam("username") String userName
@QueryParam uri path request parameter Write it in the parameters of the method to get the parameters attached to the request path. For example: @QueryParam("desc") String desc
@DefaultValue Set the default value of the @QueryParam parameter If @QueryParam does not receive a value, the default value is used. For example: @DefaultValue("description") @QueryParam("desc") String desc
@FormParam Parameters passed by form Accept the parameters passed by the form. For example: @FormParam("name") String userName
@BeanParam Pass parameters in the form of Bena Accept the parameters of the bean type passed by the client, and the bean can be configured with @FormParam on the property to solve the problem of inconsistency between the client's property name and the bean's property name. For example: @BeanParam User user
@Context Get some system environment information The following information can be obtained through @Context: UriInfo, ServletConfig, ServletContext, HttpServletRequest, HttpServletResponse, and HttpHeaders, etc.
@XmlRootElement convert bean to xml This annotation is required if the bean is to be returned in xml or json format. for example:

@XmlRootElement

public class User{...}

@XmlElements    
@XmlElement    

Jersey usage example:

 

1. Add Maven dependencies or import jar packages

<!--jersey -->

<dependency>

<groupId>org.glassfish.jersey.containers</groupId>

<artifactId>jersey-container-servlet-core</artifactId>

<version>2.13</version>

</dependency>

 

<!--JAXB API -->

<dependency>

<groupId>javax.xml.ws</groupId>

<artifactId>jaxws-api</artifactId>

<version>2.1</version>

</dependency>

 

<!-- Json support-->

<dependency>

<groupId>org.codehaus.jackson</groupId>

<artifactId>jackson-core-asl</artifactId>

<version>1.9.12</version>

</dependency>

<dependency>

<groupId>org.codehaus.jackson</groupId>

<artifactId>jackson-mapper-asl</artifactId>

<version>1.9.12</version>

</dependency>

<dependency>

<groupId>org.codehaus.jackson</groupId>

<artifactId>jackson-jaxrs</artifactId>

<version>1.9.12</version>

</dependency>

<!-- Compilation needs, there is --> in tomcat

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>2.5</version>

<scope>provided</scope>

</dependency>

<!-- Compilation needs, there is --> in tomcat

 

If you don't use Maven, download the corresponding jar package yourself and put it on the classpath.

2. Modify web.xml and configure jerseyServlet

<servlet>

<servlet-name>JerseyServlet</servlet-name>

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

<!-- Configure your own resource loading class to load resources -->

<init-param>

<param-name>javax.ws.rs.Application</param-name>

<param-value>com.cisdi.jersey.api.ApplicationAPI</param-value>

</init-param>

<!-- Configure the default resource bundle path and use the default configuration class to load resources-->

<!-- <init-param> -->

<!-- <param-name>jersey.config.server.provider.packages</param-name> -->

<!-- <param-value>com.cisdi.jersey.api</param-value> -->

<!-- </init-param> -->

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>JerseyServlet</servlet-name>

<url-pattern>/api/*</url-pattern>

</servlet-mapping>

There are two ways to load resources above. One is to use your own resource loader to load resources, and you need to give the location of your own resource loader. The other is to use the default resource loader to load, you need to give the package where the resource is located. Personally, the first one is to write your own resource loader to load the resources you want to load, which makes it feel more controllable. Next, I will introduce how to write this resource loader.

3. Write your own resource loader

public class ApplicationAPI extends ResourceConfig {

public ApplicationAPI() {

// load resources

register(HelloResource.class);

register(UserResource.class);

 

// register the data converter

register(JacksonJsonProvider.class);

 

// register log

register(LoggingFilter.class);

 

}

}

This class is to load various resources and expose them to the client. As mentioned earlier, the strong controllability of using your own resource loader is that in addition to loading business resources, you can also load days and other tool resources that need some tools. Or if a resource under the package does not want to be exposed, just don't load it.

4. Write your own resources

First got a simple resource, HelloResource

@Path("/hello")

public class HelloResource {

@GET

@Produces(MediaType.TEXT_PLAIN)

public String sayHello() {

return "hello jersey!";

}

}

Then you can get a complex object resource, UserResource

@XmlRootElement

public class User {

private int id;

@FormParam("name")

private String userName;

@FormParam("desc")

private String desc;

        

        Setter/Getter...

}

The following are the various methods of UserResource

@Path("user")

public class UserResource {

     //The methods of this class are all below
}

//This method mainly introduces the use of @GET, @Path, @Produces, @PathParam, @DefaultValue, @QueryParam annotations

@GET

@Path("{username}")

@Produces(MediaType.APPLICATION_XML)

// @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })

public User getUser(@PathParam("username") String userName, @DefaultValue("description") @QueryParam("desc") String desc) {

User user = new User();

user.setId(new Random().nextInt());

user.setUserName(userName);

user.setDesc(desc);

return user;

}

//Access path: {host}:{port}/{serviceName}/api/user/username?desc=xxx ;username can be written casually

//This method mainly introduces the use of @POST, @Consumes, @FormParam annotations

@POST

@Path("updateUser")

@Consumes("application/x-www-form-urlencoded")

public void updateUser(@FormParam("name") String userName, @FormParam("desc") String desc) {

User user = new User();

user.setId(1);

user.setUserName(userName);

user.setDesc(desc);

System.out.println(user);

}

//Access path: {host}:{port}/{serviceName}/api/user/updateUser; this is accessed by submitting the form

//This method mainly introduces the use of @BeanParam       

@POST

@Path("updateUser1")

@Produces(MediaType.APPLICATION_XML)

@Consumes("application/x-www-form-urlencoded")

public User updateUser1(@BeanParam User user) {

//Note that this method needs to be annotated with @FromParam in the User bean

System.out.println(user);

return user;

}

//Access path: {host}:{port}/{serviceName}/api/user/updateUser1; this is accessed by submitting the form

 

//This method mainly introduces the use of @Context annotation

@Context

HttpServletRequest request;

 

@Context

HttpServletResponse response;

 

@Context

ServletConfig servletConfig;

 

@Context

ServletContext servletContext;

 

@Context

HttpHeaders header;

 

@Context

UriInfo info;

 

@GET

@Path("/test/{param}")

@Produces(MediaType.APPLICATION_XML)

public User getContext() {

MultivaluedMap<String, String> queryParameters = info.getQueryParameters();

MultivaluedMap<String, String> pathParameters = info.getPathParameters();

 

System.out.println(queryParameters);

System.out.println(pathParameters);

 

System.out.println(this.request);

System.out.println(this.response);

System.out.println(this.servletConfig);

System.out.println(this.servletContext);

System.out.println(this.header);

System.out.println(this.info);

 

return new User(1, "gusi");

 

}

//Access path: {host}:{port}/{serviceName}/api/user/test/xxx?xxx=xxx&xxx=xxx;xxx can be scribbled

Description: Using this method has a great effect. When we do not know the parameter names passed by the client, or the parameters passed by the client change frequently,

Then we can use this method to dynamically obtain the parameters passed to the service, and then perform subsequent processing.

5. Access the webservice through the client program

Above we can directly access the webservice through the address of the browser, and also through a special client program, the program is as follows:

public class UserClient {

private static String serverURI = "http://localhost:8080/jerseyDemo/api/user";

 

public static void getContext() {

Client client = ClientBuilder.newClient();

WebTarget target = client.target(serverURI + "/test/context?one='abc'&two=2");

Response response = target.request().get();

response.close();

}

 

public static void addUser() {

User user1 = new User(1, "name1", "desc1");

User user2 = new User(2, "name2", "desc2");

Client client = ClientBuilder.newClient();

WebTarget target = client.target(serverURI + "");

Response response = null;

target.request().buildPost(Entity.entity(user1, MediaType.APPLICATION_XML)).invoke();

response = target.request().buildPost(Entity.entity(user2, MediaType.APPLICATION_XML)).invoke();

response.close();

}

 

public static void deleteUser() {

Client client = ClientBuilder.newClient();

WebTarget target = client.target(serverURI + "/1");

Response response = target.request().delete();

response.close();

}

 

public static void updateUser() {

User user = new User(1, "nameA", "descA");

Client client = ClientBuilder.newClient();

WebTarget target = client.target(serverURI + "");

Response response = target.request().buildPut(Entity.entity(user, MediaType.APPLICATION_XML)).invoke();

response.close();

}

 

public static void getUserById() {

Client client = ClientBuilder.newClient();

// client.register(JacksonJsonProvider.class);

WebTarget target = client.target(serverURI + "/1");

Response response = target.request().get();

User user = response.readEntity(User.class);

System.out.println(user);

response.close();

}

 

public static void getAllUser() {

Client client = ClientBuilder.newClient();

WebTarget target = client.target(serverURI + "");

Response response = target.request().get();

String value = response.readEntity(String.class);

System.out.println(value);

response.close();

}

}

The above demonstrates the sending of POST, PUT, DELETE, and GET requests to the Service through the Client program.

6. Test

Use junit unit tests to test sending different requests separately

public class UserClientTest {

 

@Test

public void testContext() {

UserClient.getContext();

}

 

@Test

public void testAddUser() {

UserClient.addUser();

}

 

@Test

public void testDeleteUser() {

UserClient.deleteUser();

}

 

@Test

public void testUpdateUser() {

UserClient.updateUser();

}

 

@Test

public void testGetUser() {

UserClient.getUserById();

 

}

 

@Test

public void testGetAllUser() {

UserClient.getAllUser();

}

 

}

​通过上面的6个步骤,就可一简单的实现webservice的基本使用。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326563129&siteId=291194637