Java Scientia Basics: Creating restful Service with Jax-rs and Jersey

Source: Internet
Author: User

As the processing power of the server becomes stronger and the business demand accumulates, more and more companies start from single server, single service to multi-server, multi-service and fast-expanding. Traditional methods are difficult to meet and respond to changes in the growth and deployment patterns of this business volume. As a best practice for distributed services, restful service has emerged.

When it comes to restful Service, let's start by understanding his basic concept: it's an architectural way to create distributed hypertext media, and we can build a resource-oriented software architecture using standard HTTP (get,post,put,delete) operations ( resource-oriented Architecture (ROA)). It is independent of any technology or platform, so it is often called a "RESTful services" service that conforms to this practice. To be blunt, it is a way of obtaining resources through a standard HTTP operation through a prescribed access path. RESTful Service has different programming interfaces to support different programming platforms. For example, in. NET, a standard rest fulservice can be created through WCF or WEBAPI. In Java, this restful Service can be created through Jax-rs and jersey. So, what is Jax-rs and jersey?

Jax-rs: Java API interface specifically provided for restful service, which is part of Java EE6. We can use these rich interfaces to achieve the restful style of distributed services that we want.

Jersey: Open source software, an extension of the Jax-rs (JSR 311), provides a richer API interface that makes it easier for developers to create restful services.

Below we will begin our journey of creation.

Step One:

In the STS, click file->new-> Dynamic Web Project to create a Myrestfulservicedaemon project:

Once created, click the Finish button.

Step Two:

Then when the project is loaded, go to the \webcontent\web-inf\ path below to check if there is a Web. xml file, and if not, you need to right-click on the current project and choose Java EE tools–> Generate Deployment Descriptor Stub, after clicking , you will find that the Web. xml file has been generated:

Step Three:

Now, right-click on the project, click Configure, and then convert to Maven project, and turn it into MAVEN project. In the Create New Pom dialog box that pops up, we fill in the relevant information and then determine:

Step Four:

Open the Pom.xml file and add the following dependencies, respectively: Asm.jar, Jersey-bundle.jar, Json.jar, Jersey-server.jar, Jersey-core.jar.

These packages can be added manually by editing Pom.xml, or automatically via a dialog box, where we use automatic additions. Double-click Pom.xml, and then switch to the Dependencies tab to add the packages described above:

After adding the interface is this:

The contents of the Pom.xml file are as follows:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>MyRESTfulServiceDaemon</groupId> <artifactid >MyRESTfulServiceDaemon</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war </packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin > <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> &L t;configuration> <source>1.8</source> <target>1.8</target> </config uration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> &       Lt;version>2.6</version> <configuration>   <warSourceDirectory>WebContent</warSourceDirectory> <failonmissingwebxml>false</failonmis singwebxml> </configuration> </plugin> </plugins> </build> <dependencies&gt  ; <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version  >20140107</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.19</version> </dependency> <  Dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.19</version> </dependency> <dependency> <groupId>asm</groupId> <  artifactid>asm</artifactid> <version>3.3.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> &LT;ARTIFACtid>jersey-bundle</artifactid> <version>1.19</version> </dependency> </dependencies ></project>

Step Five:

Configuring the Pom.xml means that the MAVEN configuration is temporarily configured and the Maven install command will be run to automatically download the packages locally.

Now, let's open Web. XML and then copy the nonexistent servlet nodes and Servlet-mapping nodes as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee/http Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "version=" 3.1 "> <display-name>myrestfulservicedaemon</ display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file& Gt;index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file> Default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file> default.jsp</welcome-file> </welcome-file-list> <servlet><servlet-name>jersey Web application</servlet-name><servlet-class>com.sun.jersey.spi.container.servlet.servletcontainer< /servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping>< SeRvlet-name>jersey Web application</servlet-name><url-pattern>/api/*</url-pattern></ Servlet-mapping> </web-app>

Step Six:

Once configured, we now encode, create a Myservice.java class in the Java resources/src/directory, and enter the following code:

Import Javax.ws.rs.get;import javax.ws.rs.path;import javax.ws.rs.pathparam;import javax.ws.rs.Produces; @Path ("/myservice") public class MyService {@GET @produces ("Application/xml") public String Convertctof () {Double fahrenheit;double Celsius = 36.8;fahrenheit = ((Celsius * 9)/5) + 32; String result = "@Produces (\" application/xml\ ") output: \n\nc to F Converter output: \ n" + Fahrenheit;return "<ctofse Rvice> "+" <celsius> "+ Celsius +" </celsius> "+" <ctofoutput> "+ result +" </ctofoutput> "+" & Lt;/ctofservice> ";} @Path ("{c}") @GET @produces ("Application/xml") public String Convertctoffrominput (@PathParam ("C") double C) {double fahrenheit;double Celsius = C;fahrenheit = ((Celsius * 9)/5) + 32; String result = "@Produces (\" application/xml\ ") output: \n\nc to F Converter output: \ n" + Fahrenheit;return "<ctofse Rvice> "+" <celsius> "+ Celsius +" </celsius> "+" <ctofoutput> "+ result +" </ctofoutput> "+" & Lt;/ctofservice>";}} 

Once you have finished typing, create a Myservicex.java class and enter the following code:

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.response;import Org.json.jsonexception;import Org.json.JSONObject; @Path ("/myservicex") public class Myservicex {@GET @Produces ("Application/json") public Response Convertftoc () throws jsonexception {Jsonobject jsonobject = new Jsonobject ();D ouble Fahrenheit = 98.24;double Celsius;celsius = (Fahrenheit- 32) *5/9; Jsonobject.put ("F Value", Fahrenheit); Jsonobject.put ("C Value", Celsius); String result = "@Produces (\" application/json\ ") output: \n\nf to C Converter output: \ n" + Jsonobject;return RESPONSE.S  Tatus. Entity (Result). Build (); } @Path ("{f}") @GET @Produces ("Application/json") public Response Convertftocfrominput (@PathParam ("F") float f) throw s jsonexception {jsonobject jsonobject = new Jsonobject (); float Celsius;celsius = (f-32) *5/9; Jsonobject.put ("F Value" , f); Jsonobject.put ("C Value", Celsius); String result = "@Produces (\" Application/json\ ") Output: \n\nf to C Converter output: \ n" + Jsonobject;return Response.Status ($). "Entity (Result). Build  (); }}

After the code is written, we will see a lot of errors because the jar packages have not been downloaded yet. Run the following two commands in turn:

Right-click Project->maven->update Project. Right-click->run as->maven Build

Once the command is finished, we can see that the code has no error prompts. Also in the log information, you can see that our project build succeeded.

Step Seven:

Now to start running our project, right click on the project and select Run As->run on Server, in the popup dialog box, click the Finish button to open the URL http://localhost:8080/ myrestfulservicedaemon/, but the page will show a 404 error because if we want to invoke the page, we need to enter it as follows:

Visit the MyService page:

Http://localhost:8080/MyRESTfulServiceDaemon/api/myservice, we see the following results:

We then enter the parameter http://localhost:8080/MyRESTfulServiceDaemon/api/myservice/35 for it to see the changes to the content:

Finally we test myservicex:http://localhost:8080/myrestfulservicedaemon/api/myservicex/35, we can see the prompt to download the json file command, Note that our JSON data request was also successful:

End:

Here, our example is over, isn't it simple? I have to say that Maven does quite well. Need more reference knowledge, we can go to the following link to find.

How to build a RESTful Service with Java using Jax-rs and Jersey (Example)

Java Scientia Basics: Creating restful Service with Jax-rs and Jersey

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.