Create a RESTful Web service using Java (GO)

Source: Internet
Author: User
Tags representational state transfer java se

Rest is the abbreviation for the Representational state transfer (the general Chinese translation is the representational status transfer). 2000 Dr. Roy Fielding in his doctoral dissertation "Architectural Styles and the Design of network-based software Architectures" Rest is proposed in architecture and web-based software architecture design.

Rest is an architecture. HTTP is a protocol that contains the properties of a rest schema.

Rest Basic Concepts

    • Everything in rest is considered a resource. Each resource has a URI and it corresponds.
    • Use the unified interface to process resources in rest. As with database crud operations (Create, Read, Update, and delete), rest resources can be processed with post, GET, put, and delete.
    • Each rest request is orphaned, and the request contains all the information needed. The rest service side does not store state.
    • Rest supports different communication data formats, such as XML, JSON.

RESTful Web Services

RESTful Web Services, which are widely used because of their simplicity, are much simpler than soap. This article focuses on how to create restful Web Services using the Jersey framework. The jersey framework implements the Jax-rs interface. The sample code in this article was written using Eclipse and Java SE 6.

Create a RESTful WEB service server

    • Create a Dynamic Web project in Eclipse, with the project name set to "RESTFULWS".

    • Download jersey from here. The sample code uses Jersey 1.17.1. First unzip the jersey to the "jersey-archive-1.17.1" folder. Then copy the jar file under the Lib folder into the project directory, Web-inf. lib. They are then added to the build path.
  1. Asm-3.1.jar
  2. Jersey-client-1.17.1.jar
  3. Jersey-core-1.17.1.jar
  4. Jersey-server-1.17.1.jar
  5. Jersey-servlet-1.17.1.jar
  6. Jsr311-api-1.1.1.jar
    • Create the "Com.eviac.blog.restws" package in the project Java Resources, SRC, and create the "UserInfo" class in it. Finally, copy the Web. XML to the Web-inf directory.

Userinfo.java

1234567891011121314151617181920212223242526272829303132333435363738394041 package com.eviac.blog.restws;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;/*** * @author pavithra* */// 这里@Path定义了类的层次路径。 // 指定了资源类提供服务的URI路径。@Path("UserInfoService")public class UserInfo {// @GET表示方法会处理HTTP GET请求@GET// 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。@Path("/name/{i}")// @Produces定义了资源类方法会生成的媒体类型。@Produces(MediaType.TEXT_XML)// @PathParam向@Path定义的表达式注入URI参数值。public String userName(@PathParam("i") String i) {String name = i;return "<User>" + "<Name>" + name + "</Name>" + "</User>";}@GET@Path("/age/{j}") @Produces(MediaType.TEXT_XML)public String userAge(@PathParam("j") int j) {int age = j;return "<User>" + "<Age>" + age + "</Age>" + "</User>";}}

Xml

1234567891011121314151617 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee <a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"</a> id="WebApp_ID" version="2.5"> <display-name>RESTfulWS</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.eviac.blog.restws</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
    • Copy this URL to the browser address bar to run:
  1. Http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra

The output results are as follows:

Create Client

Create a "com.eviac.blog.restclient" package, and then new "Userinfoclient" class.

Userinfoclient.java

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66 package com.eviac.blog.restclient;import javax.ws.rs.core.MediaType;import com.sun.jersey.api.client.Client;import com.sun.jersey.api.client.ClientResponse;import com.sun.jersey.api.client.WebResource;import com.sun.jersey.api.client.config.ClientConfig;import com.sun.jersey.api.client.config.DefaultClientConfig;/*** * @author pavithra* */public class UserInfoClient {public static final String BASE_URI = "http://localhost:8080/RESTfulWS";public static final String PATH_NAME = "/UserInfoService/name/";public static final String PATH_AGE = "/UserInfoService/age/";public static void main(String[] args) {String name = "Pavithra";int age = 25;ClientConfig config = new DefaultClientConfig();Client client = Client.create(config);WebResource resource = client.resource(BASE_URI);WebResource nameResource = resource.path("rest").path(PATH_NAME + name);System.out.println("Client Response \n"+ getClientResponse(nameResource));System.out.println("Response \n" + getResponse(nameResource) + "\n\n"); WebResource ageResource = resource.path("rest").path(PATH_AGE + age);System.out.println("Client Response \n"+ getClientResponse(ageResource));System.out.println("Response \n" + getResponse(ageResource));}/*** 返回客户端请求。* 例如:* GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra * 返回请求结果状态“200 OK”。** @param service* @return*/private static String getClientResponse(WebResource resource) {return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();}/*** 返回请求结果XML* 例如:<User><Name>Pavithra</Name></User> * * @param service* @return*/private static String getResponse(WebResource resource) {return resource.accept(MediaType.TEXT_XML).get(String.class);}}
    • After you run the client program, you can see the following output:
123456789 Client Response GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OKResponse <User><Name>Pavithra</Name></User>Client Response GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OKResponse <User><Age>25</Age></User>

Try it:)

Http://www.importnew.com/7336.html

Create a RESTful Web service using Java (GO)

Related Article

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.