This tutorial will show you how to develop an app using the ** Jersey Java RESTful API ** on an ** Alibaba Cloud Elastic Compute Service ** instance.
By Aditya, Alibaba Cloud Tech Share Author. Tech Share , An Alibaba Cloud incentive program that encourages sharing of technical knowledge and best practices within the cloud community.
With the proliferation of digital technology, the same applications are becoming available on a variety of devices, including laptops, mobile phones, and televisions. Most of the applications that are being built or are being built are multi-tiered. In multi-tier applications, there is a clear distinction between what each type can achieve. This makes sense from a business perspective, as it saves a lot of money. However, to meet the different needs of having the same data available across different applications, you need a common place where you can access your data with good security rules.
From a developer's point of view, the growing need for data to be replicated between different devices and technology shifts are happening very rapidly. You can't afford to bring the entire system down just for a simple upgrade to change the backend. We also need to be able to adapt to new technologies without the hassle of development. Taking all these conditions into account, the REST framework provides a clear abstraction between other layers of how data can be accessed with different technologies, such as mobile (Android and IOS) and Web JavaScript technologies. You can see that it will do it.
Deploying the REST API on an on-premises server is inefficient and time consuming. Instead, let's see how to use Alibaba Cloud Elastic Compute Service to deploy the Java REST API and publish the service to the Internet. Let's do it. But before you can deploy your API to the cloud, you first need to create it. Here we'll see how to create a simple jersey-based Java REST API and test it with tools.
REST means "Representational State Transfer". REST was intended to create a decoupling between the server and the client to maintain reusable components and allow them to be replaced at any time. Since REST is stateless, you can improve performance and efficiency by implementing a cache on your server.
Now let's create a simple API to get & record employee details.
Below is the complete tool I am using for development.
Eclipse IDE for JAVA EE developers --Latest Maven --Apache Tomcat Web Server 7 --Insomnia REST Client --ECS instance setup
** After logging in to Alibaba Cloud Console, select Elastic Compute Instance from Product. ** **
Create an instance, preferably in the nearest region. Follow the steps below. For my server, I have selected the "Pay-as-you-go" model with the following configuration.
I plan to use Windows 2016 Data Center Image for my ECS Instances (https://www.alibabacloud.com/en/product/ecs). I have set the networking, system configuration, and other values to default. Click Create Instance to continue.
Once the instance is created, it will look like this on the console.
Click the ECS instance name and select Security Group> Configure Rule> Add Security Group Rule. Enter the following information:
Please note that 8080 is where my tomcat is deployed. You need to change it to the location where Apache Tomcat is actually located.
Connect the ECS instance via the RDP protocol and proceed with development using the created windows VM.
Download and install the latest "Eclipse IDE for JAVA EE Developers".
Install the latest version of the JDK and set the installation path to "JAVA_HOME" and the environment variable "Path". You also need to install maven. It's very easy, you need to download and unzip the latest binary distribution .zip and set the installation path to the environment variables "M2_HOME" and "Path". For the purposes of this article, the code is provided as a zip file. Download the project and import it into your eclipse workspace.
Download the code repository here: https://alicloud-common.oss-ap-southeast-1.aliyuncs.com/RESTCodeRepo.zip
Import the code from File> Import and select General in the dialog box.
Let's take a look at the imported code. Eclipse has the following project structure.
Looking at what's in the deployment descriptor for the complete project, "pom.xml", it holds the project dependencies.
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.aditya.restapi</groupId>
<artifactId>RESTfulExample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>RESTfulExample Maven WebApplication</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
</dependencies>
<build>
<finalName>RESTfulExample</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Model-version: The current pom compliant version, which is 4.0.0 to support maven 3.
Artifact Id, packaging, groupID, version, name: These are used during packaging and to describe the project during deployment.
Repository: Used during packaging and describes the project during deployment. This tag consists of all the repositories that the dependency pulls. You can specify multiple repositories under this.
Dependencies: This tag consists of all the dependencies needed for your project. I use jersey related jars for API, and I also use JUNIT jars.
Build: The build tag contains complete information about how the application will be packaged in WAR format, the name and what version of the maven assembly plugin will be used for packaging.
We need a model to hold the data we receive and send, so we created an Employee.java model to hold the name, age, salary, and company.
package com.aditya.model;
public class Employee {
private String name;
private String age;
private int salary;
private String company;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + ", salary=" + salary + ", company=" + company + "]";
}
}
This model consists of getters, setters, and toString () methods for retrieving, storing, and displaying information.
It is in the "com.aditya.rest" package of "JSONService.java" which has the full code of the REST API.
package com.aditya.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.aditya.model.Employee;
@Path("/json/empservice")
public class JSONService {
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Employee getEmpDetails() {
Employee emp = new Employee();
emp.setName("Aditya");
emp.setCompany("ABC Corporation");
emp.setAge("31");
emp.setSalary(1000);
return emp;
}
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createEmpInJSON(Employee emp) {
String result = "Employee saved : " + emp.toString();
return Response.status(201).entity(result).build();
}
}
We have the package declaration first & we also notice that all imports & annotations are imported from the jersey jar.
The initial path maps the map and class, and the method is identified by @GET / @POST.
@GET:
Make sure @GET is mapped to getEmpDetails () which returns information about the hardcoded data. This will automatically unmarshall (convert JAVA object to JSON). This is the advantage of Jersey Servlet. Let's see how.
@POST:
@POST is mapped to createEMPInJSON () which receives the marshalled Object from the request to the Jersey Servlet into the emp object. The response is created with the result in status 201 (Created).
Web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</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.aditya.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
This is the API deployment descriptor. The display-name is obvious because it consists of the name of the application. It consists of the Servlet name we use, and the Servlet class consists of the fully qualified name of the Servlet.
In addition, param-name and param-value specify the functions required for the web application.
com.sun.jersey.api.json.POJOMappingFeature provides the ability to map JSON to java objects.
Servlet mapping maps Servlet functionality to specific URL patterns.
Apache Tomcat 7: Download the Windows installer from the official link. https://tomcat.apache.org/download-70.cgi
Execute Tomcat7.exe and specify the folder where you want to install Tomcat7.
Right-click on the server section and select "New> Server".
Select Tomcat 7 Server and then Next.
Select Browse and specify the tomcat installation folder to create the server.
Right-click on the project and select "Run as"> "Run on server". When the API is deployed, it will be in the following state.
Select Browse and specify the tomcat installation folder to create the server.
Right-click on the project and select "Run as"> "Run on server". When the API is deployed, it will be in the following state.
Install the Insomnia Client, make a new request and use the following URI:
GET : http://localhost:8080/RESTfulExample/rest/json/empservice/get
POST : http://localhost:8080/RESTfulExample/rest/json/empservice/post
The following reactions can be seen.
You can also use the public IP of your ECS instance to access the same API, but changing it does not change the API URL.
GET - http://:8080/RESTfulExample/rest/json/empservice/get
POST - http://:8080/RESTfulExample/rest/json/empservice/post
In a production environment, you can save money by using a version 1709 Windows server image that provides console-based access only, but ECS Instances You can reduce a lot of software on ja / product / ecs) and improve performance.
You also need to use a server load balancer for the API we are planning to scale it up with multiple ECS images.
To prevent abuse and increase security, you can introduce OAuth-like authentication in your API.
Also, in order to improve the security function of API, Alibaba Cloud DNS and [Anti-DDOS Pro](https://www. You can consider using alibabacloud.com/en/product/ddos-pro).
Recommended Posts