How to write Web Service in Java Spring

In this post, you will get to know how to build RESTful Web Service using Java Spring. RESTful Web Service is a type of application that gets an HTTP request and returns a JSON response. You can use it to get data from your application, database etc via a simple HTTP request.

First, we need to create a new project or just add libraries to your existing project. I’m using Gradle, so if you too, you can copy entire build.gradle file from me.

Example

We need some data to work on, so in this example, we will have a simple Person class with parameter id, name, lastName.

PersonController

Now, we have a PersonController class where all the magic happen. Look at the code:

First, look at the first line, this annotation tells to the compiler that this is class that will be used as RESTful Web Service. We have AtomicLong to generate unique ids for our Person objects. Finally, we have method person with annotation RequestMapping in the parameter we will give string that will be part of request URL. Then, in method parameters, we create RequestParams, we need set value – the name of the parameter and default value to this variable. You can add more parameters if you need. In the method body, we return a new Person object.

In the end, we need a main class that will launch the Spring Boot Application.

Now you can build and run this code and make request to your Web Service.

For example, first, make the request without any parameters http://localhost:8080/whoareyou Web Service will return JSON with default parameters.

Let’s add first parameter http://localhost:8080/whoareyou?name=Tom, now, we create an object with name Tom and default last name.

In the end, let’s test the last scenario http://localhost:8080/whoareyou?name=Tom&lastname=Page, Web Service return JSON object with a name and last name given in URL.

You just build Web Service using Java Spring. This is a very simple example, you can add more scenarios to this code, integrate database etc. There are so many possibilities and scenarios to create and use Web Services.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.