Jersey Java RESTful API on an Alibaba Cloud ECS Instance

本文涉及的产品
云服务器 ECS,每月免费额度280元 3个月
云服务器ECS,u1 2核4GB 1个月
简介: This tutorial describes how to develop apps with Jersey Java RESTful API on an Alibaba Cloud Elastic Compute Service instance.

By Aditya, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

With the increased adoption of digital technology, we see that same applications are typically available across different devices, notably on laptops, mobile phones, and TV. Most of the applications built or being built today are multi-tier. In a multi-tier application, you have clear distinctions of what each type can achieve. This makes sense from a business prospective as it significantly reduces costs. However, to cater to the different needs of the same data being available across different applications, we need to have a common place where we can access data with proper security rules.

From a developer's perspective, the increase need of data being replicated across different devices and the technology shift is happening very rapidly. We can't afford to take down the entire system just for a simple upgrade for a backend change. We should also be able to adapt to the newer technologies without much development effort. Taking all these conditions into account, we see that the REST framework gives us a clear abstraction between the other layers of how the data can be accessed across a different technology, such as mobile (Android and IOS) and web JavaScript Technologies.

Deploying a REST API onto an on-premises server is inefficient and time-consuming. Instead, we'll see how we can leverage Alibaba Cloud Elastic Compute Service to deploy our Java REST API and expose the service to internet. But before we even talk about deploying our API on to the cloud, we need to create one first. We will see how to create a Simple Jersey based Java REST API and test the API with selected tools.

Creating JAVA REST API

REST means "Representational State Transfer". REST was intended to create a decoupling between the server and the client, maintain reusable components, and can be replaced at any time. REST is stateless and you can implement cache on the server to improve performance and efficiency.

Now we will create a simple API which fetches the Employee Details & records the employee details.

Below are the complete tools I use for development.

  • Eclipse IDE for JAVA EE Developers
  • Latest Maven
  • Apache Tomcat web server 7
  • Insomnia REST Client

Setting Up the ECS Instance

Select Elastic Compute Instance from Products after logging into the Alibaba Cloud Console.

Create an Instance, preferably at the region closest to you. The following are the steps. For my server, I have selected the "Pay-as-you-go" model with the below configuration.

1

I will be using the Windows 2016 Data Center Image for my ECS instance. I have set the Networking, System Configurations, and other values to default. Click on Create Instance to continue.

Once the instance is created you will see something like this in your console.

2

Click on the ECS instance name and select security groups > configure rules > Add security group rules. Fill in the following information

3

Please note here that the 8080 is where my tomcat is deployed. You should change it to where your Apache Tomcat is actually deployed.

Connect the ECS Instance via RDP Protocol & we will do the further development using the windows VM Created.

Creating the API:

Download the latest "Eclipse IDE for JAVA EE Developers" and install.

  • You need to install the latest version of JDK & set the installation path to "JAVA_HOME" & also to the "Path" environment variables
  • You also need to install maven. It is so simple you need to download the latest binary distribution .zip and extract it & set the installation path to the "M2_HOME" & "Path" environment variables.

For the purpose of this article the code is provided as a zip file. Please download and import the project onto your eclipse workspace.

Download the Code Repository here: https://alicloud-common.oss-ap-southeast-1.aliyuncs.com/RESTCodeRepo.

You can import the code via "File > Import" and select "General" in the Dialog box.

Let’s see the imported code. You will see the below project structure in Eclipse.

4

We see the what included in the "pom.xml" the deployment descriptor for our complete project, holds the dependencies for our project.

<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 : This is the version which the current pom complies to, to support maven 3 we make the version to 4.0.0

Artifact Id, packaging, groupID, version, name : These are used while packaging and to describe the project while deployment.

Repositories : This tag consists of all the repositories the dependencies to pull from. You can specify multiple repositories under this. Here we specified the central public repository for java

Dependencies : This tag consists of all the dependencies which are needed for the project. We used jersey related jars for our API and a JUNIT jar

Build: the build tag contains the complete information of how the application will be packaged into the WAR format, naming & which version of maven assembly plugin will be used for packaging

We need a model to hold the data we receive and send, we have created a Employee.java model which holds the name, age, salary, 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 the getters, setters & toString() method for the getting, storing & display the information.

In the package "com.aditya.rest" for "JSONService.java" which has the complete code for 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 initially has the package declaration & we also notice that all the imports & annotations are imported from the Jersey jars.

The initial path maps the class with the map & methods are identified by @GET / @POST

@GET:

If we see the @GET is mapped to getEmpDetails() which returns an information of hardcoded data. The unmarshalling (JAVA Object to JSON) will happen automatically . This is one of the advantage of Jersey Servlet. We will see how.

@POST:

The @POST is mapped createEMPInJSON() which receives the marshalled Object from the request to Jersey Servlet to the emp object. The response is created with status 201 (Created) along with the result.

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 deployment descriptor of the API. The display-name is obvious as it consists of the name of the application. This consists of the servlet-name we use, servlet-class consists of the fully qualified name of the servlet.

We also created the param-name & param-value gives the features we needed for the web application.

com.sun.jersey.api.json.POJOMappingFeature gives the capability of mapping the JSON to the java object.

The servlet-mapping maps the servlet feature with a specific URL Pattern.

Apache Tomcat 7:

Download the Windows installer at the official link
http://www-us.apache.org/dist/tomcat/tomcat-7/v7.0.85/bin/apache-tomcat-7.0.85.exe

execute the Tomcat7.exe and point the folder where you want the tomcat 7 to be installed.

Deploying and Testing the API:

5

Right Click on the servers section, select "New > Server"

6

Select "Tomcat 7 Server" select "Next"

7

You select "Browse" and point to the tomcat installation folder & the server will be created.

Right click on the project select "Run as " > "Run on server". Once your API is deployed, you will see the following status

8

Install the Insomnia Client, and create 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

You will see the following response

9

10

You can also access the same API using the public IP of the ECS Instance, There will no change with the API URL if we change that, The resultant URL will be

GET – http://:8080/RESTfulExample/rest/json/empservice/get

POST – http://:8080/RESTfulExample/rest/json/empservice/post

Additional Steps:

1.In Production, you can reduce the cost by using the Version 1709 Windows server Image which only gives the console based access, But it cuts a lot of software on your ECS Instance increasing the performance.

2.You should also use server load balancer for the API of we are planning to scale it up using multiple ECS images.

3.You can better have authentication in place like OAuth for the API to prevent abuse and better security.

4.You can also consider using Alibaba Cloud DNS and Anti-DDOS Pro for better security features for your API.

相关实践学习
一小时快速掌握 SQL 语法
本实验带您学习SQL的基础语法,快速入门SQL。
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情:&nbsp;https://www.aliyun.com/product/ecs
目录
相关文章
|
1天前
|
安全 Java API
RESTful API设计与实现:Java后台开发指南
【4月更文挑战第15天】本文介绍了如何使用Java开发RESTful API,重点是Spring Boot框架和Spring MVC。遵循无状态、统一接口、资源标识和JSON数据格式的设计原则,通过创建控制器处理HTTP请求,如示例中的用户管理操作。此外,文章还提及数据绑定、验证、异常处理和跨域支持。最后,提出了版本控制、安全性、文档测试以及限流和缓存的最佳实践,以确保API的稳定、安全和高效。
|
4天前
|
存储 Java 关系型数据库
掌握Java 8 Stream API的艺术:详解流式编程(一)
掌握Java 8 Stream API的艺术:详解流式编程
21 1
|
9天前
|
Java BI API
SAP Cloud for Customer 里如何通过 ABSL 二次开发方式消费 SAP S/4HANA 系统的 API
SAP Cloud for Customer 里如何通过 ABSL 二次开发方式消费 SAP S/4HANA 系统的 API
12 0
|
13天前
|
前端开发 Java API
构建RESTful API:Java中的RESTful服务开发
【4月更文挑战第3天】本文介绍了在Java环境中构建RESTful API的重要性及方法。遵循REST原则,利用HTTP方法处理资源,实现CRUD操作。在Java中,常用框架如Spring MVC简化了RESTful服务开发,包括定义资源、设计表示层、实现CRUD、考虑安全性、文档和测试。通过Spring MVC示例展示了创建RESTful服务的步骤,强调了其在现代Web服务开发中的关键角色,有助于提升互操作性和用户体验。
构建RESTful API:Java中的RESTful服务开发
|
17天前
|
XML JSON 安全
谈谈你对RESTful API设计的理解和实践。
RESTful API是基于HTTP协议的接口设计,通过URI标识资源,利用GET、POST、PUT、DELETE等方法操作资源。设计注重无状态、一致性、分层、错误处理、版本控制、文档、安全和测试,确保易用、可扩展和安全。例如,`/users/{id}`用于用户管理,使用JSON或XML交换数据,提升系统互操作性和可维护性。
14 4
|
23天前
|
Java 数据库连接 API
Java 学习路线:基础知识、数据类型、条件语句、函数、循环、异常处理、数据结构、面向对象编程、包、文件和 API
Java 是一种广泛使用的、面向对象的编程语言,始于1995年,以其跨平台性、安全性和可靠性著称,应用于从移动设备到数据中心的各种场景。基础概念包括变量(如局部、实例和静态变量)、数据类型(原始和非原始)、条件语句(if、else、switch等)、函数、循环、异常处理、数据结构(如数组、链表)和面向对象编程(类、接口、继承等)。深入学习还包括包、内存管理、集合框架、序列化、网络套接字、泛型、流、JVM、垃圾回收和线程。构建工具如Gradle、Maven和Ant简化了开发流程,Web框架如Spring和Spring Boot支持Web应用开发。ORM工具如JPA、Hibernate处理对象与数
88 3
|
24天前
|
分布式计算 Java 程序员
Java 8新特性之Lambda表达式与Stream API
本文将详细介绍Java 8中的两个重要新特性:Lambda表达式和Stream API。Lambda表达式是Java 8中引入的一种简洁、匿名的函数表示方法,它允许我们将函数作为参数传递给其他方法。而Stream API则是一种新的数据处理方式,它允许我们以声明式的方式处理数据,从而提高代码的可读性和可维护性。通过本文的学习,你将能够掌握Lambda表达式和Stream API的基本用法,以及如何在项目中应用这两个新特性。
28 10
|
24天前
|
Java API 数据处理
Java 8新特性之Lambda表达式与Stream API
本文将介绍Java 8中的两个重要特性:Lambda表达式和Stream API。Lambda表达式是一种新的语法结构,允许我们将函数作为参数传递给方法。而Stream API则是一种处理数据的新方式,它允许我们对数据进行更简洁、更高效的操作。通过学习这两个特性,我们可以编写出更简洁、更易读的Java代码。
|
25天前
|
Java API Maven
email api java编辑方法?一文教你学会配置步骤
在Java开发中,Email API是简化邮件功能的关键工具。本文指导如何配置和使用Email API Java:首先,在项目中添加javax.mail-api和javax.mail依赖;接着,配置SMTP服务器和端口;然后,创建邮件,设定收件人、发件人、主题和正文;最后,使用Transport.send()发送邮件。借助Email API Java,可为应用添加高效邮件功能。
|
弹性计算 Linux API