Java Web services – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 07 Sep 2021 18:11:16 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java Web services – Java2Blog https://java2blog.com 32 32 Web Service Tutorial https://java2blog.com/web-service-tutorial/?utm_source=rss&utm_medium=rss&utm_campaign=web-service-tutorial https://java2blog.com/web-service-tutorial/#comments Fri, 29 Mar 2013 05:45:00 +0000 http://www.java2blog.com/?p=390

In this web service tutorial, we will see the introduction of webservices in java and some jargons of web services.

Webservices in java are used everywhere nowadays. When human interacts with any web page, it involves request and response via HTML. When you interact with the webpage, browser sends a request and then renders response and shows in form of HTML. Similarly, web services also involve request and response but in the form of XML or JSON or plain text. It generally used for other applications or programs to consume and make use of information.

For example:
You are creating a website which shows weather information of important cities in the world. You can actually consume already exposed web services and get the data for the cities. You will get the response in form of XML or JSON, you can parse it and show it on your website.

Let’s go to more formal definition now:

Web service is a way of communication that allows interoperability between different applications on different platforms, for example, a Java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.Web services are browsers and operating system independent service, which means it can run on any browser without the need of making any changes. Web Services take Web-applications to the Next Level.

The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”
Let’s say, you are a Java developer and you can publish your functions on internet or LAN through java web service so any other developer(let’s say .Net developer) can access your function.

You can go through web services interview questions for interview questions on webservices in java.

Why you need to learn web services:

Reuse already developed(old) functionality into new software:

Let’s understand with the very simple example.Let’s say you are developing a finance software for a company on java and you have old .net software which manages salary of employees.So rather than developing new software for employee part, you can use old software and for other parts like infrastructure, you can develop your own functionalities.

Usability :

Web Services allow the business logic of many different systems to be exposed over the Web. This gives your applications the freedom to chose the Web Services that they need. Instead of re-inventing the wheel for each client, you need only include additional application-specific business logic on the client-side. This allows you to develop services and/or client-side code using the languages and tools that you want.

Interoperability :

This is the most important benefit of Web Services. Web Services typically work outside of private networks, offering developers a non-proprietary route to their solutions.Web Services also let developers use their preferred programming languages. In addition, thanks to the use of standards-based communications methods, Web Services are virtually platform-independent.

Loosely Coupled:

Each service exists independently of the other services that make up the application. Individual pieces of the application to be modified without impacting unrelated areas.

Ease of Integration:

Data is isolated between applications creating ’silos’. Web Services act as glue between these and enable easier communications within and across organizations.

Deployability :

Web Services are deployed over standard Internet technologies. This makes it possible to deploy Web Services even over the firewall to servers running on the Internet on the other side of the globe. Also thanks to the use of proven community standards, underlying security (such as SSL) is already built-in.

Some jargons used in Webservices in java:

Simple Object Access Protocol(SOAP):

SOAP is a protocol specification for exchanging structured information in the implementation of Web services in computer networks. It relies on XML as its message format.

Web Service Description Language(WSDL):

WSDL stands for Web Service Description Language. It is an XML file that describes
the technical details of how to implement a web service, more specifically the URI,
port, method names, arguments, and data types. Since WSDL is XML, it is both
human-readable and machine-consumable, which aids in the ability to call and bind to
services dynamically.

Elements of WSDL are:

Description:
It is the root element of a WSDL 2.0 file. It usually contains a set of namespace declarations which are used throughout the WSDL file. 

Types:
The WSDL types element describes the data types used by your web service.Data types are usually specified by XML schema.It can be described in any language as long as your web services API supports it.

Binding:
The WSDL binding element describes how your web service is bound to a protocol. In other words, how your web service is accessible. To be accessible, the web service must be reachable using some network protocol. This is called “binding” the web service to the protocol.

Interface:
The WSDL interface element describes the operations supported by your web service.It is similar to methods in programming language.The client can only call one operation per request.

Service:
It describes the endpoint of your web service. In other words, the address where the web service can be reached.

Endpoint:
The endpoint element describes the address of the web service. The endpoint binding attribute describes what binding element this endpoint uses.i.e. protocol with which you will access web service. The address attribute describes the URI at which you can access the service.

Message:
The message element describes the data being exchanged between the Web service providers and consumers.

Sample WSDL file:

   
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://webservices.javapostsforlearning.arpit.org" xmlns:intf="http://webservices.javapostsforlearning.arpit.org" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->
 <wsdl:types>
  <schema elementFormDefault="qualified" targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns="http://www.w3.org/2001/XMLSchema">
   <element name="sayHelloWorld">
    <complexType>
     <sequence>
      <element name="name" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
   <element name="sayHelloWorldResponse">
    <complexType>
     <sequence>
      <element name="sayHelloWorldReturn" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
  </schema>
 </wsdl:types>
   <wsdl:message name="sayHelloWorldRequest">
      <wsdl:part element="impl:sayHelloWorld" name="parameters"/>
   </wsdl:message>
   <wsdl:message name="sayHelloWorldResponse">
      <wsdl:part element="impl:sayHelloWorldResponse" name="parameters"/>
   </wsdl:message>
   <wsdl:portType name="HelloWorld">
      <wsdl:operation name="sayHelloWorld">
         <wsdl:input message="impl:sayHelloWorldRequest" name="sayHelloWorldRequest"/>
         <wsdl:output message="impl:sayHelloWorldResponse" name="sayHelloWorldResponse"/>
      </wsdl:operation>
   </wsdl:portType>
   <wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">
      <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <wsdl:operation name="sayHelloWorld">
         <wsdlsoap:operation soapaction="proxy.php?url="/>
         <wsdl:input name="sayHelloWorldRequest">
            <wsdlsoap:body use="literal"/>
         </wsdl:input>
         <wsdl:output name="sayHelloWorldResponse">
            <wsdlsoap:body use="literal"/>
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>
   <wsdl:service name="HelloWorldService">
      <wsdl:port binding="impl:HelloWorldSoapBinding" name="HelloWorld">
         <wsdlsoap:address location="http://localhost:8080/SimpleSOAPExample/services/HelloWorld"/>
      </wsdl:port>
   </wsdl:service>
</wsdl:definitions>

Universal Description, Discovery and Integration(UDDI):

UDDI stands for Universal Description, Discovery, and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery

Web service design approaches:

Contract last or Bottom-up approach:
When using contract last approach, you first write your Java code then you create web service contract(WSDL).There are various kinds of tools which can generate WSDL on the basis of Java code.
Contract first or Top Down Approach:
It is reverse of contract first.Here you first define web service contract.You define all the elements of WSDL first then after that you create your java logic.

Types of webservices in java:

There are mainly two types of web services.

You can read about differences and usage of REST and SOAP web services.

That’s all about the webservices in java.

]]>
https://java2blog.com/web-service-tutorial/feed/ 58
Spring Restful web services xml example https://java2blog.com/spring-restful-web-services-xml-example/?utm_source=rss&utm_medium=rss&utm_campaign=spring-restful-web-services-xml-example https://java2blog.com/spring-restful-web-services-xml-example/#comments Thu, 04 Aug 2016 18:21:00 +0000 http://www.java2blog.com/?p=157
This post is in continuation with web service tutorial (Part -10). In this tutorial,we are going to see Spring Restful web services xml example.

Web service Tutorial Content:

In previous post, we have created a very simple Spring Restful web services  which returns json. In this post, we will see Spring Restful web services which will return xml as example.

Here are steps to create a simple Spring Restful web services which will return xml.

1) Create a dynamic web project using maven in eclipse.

2) For XML support, we just need to make sure JAXB jar is available in classpath.

pom.xml will be as follows:
pom.xml

<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.arpit.java2blog</groupId>
  <artifactId>SpringRestfulWebServicesWithJSONExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>

 </dependencies>
 <build>
  <finalName>SpringRestfulWebServicesWithJSONExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring application configuration:

3) Change web.xml as below:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
 <servlet-name>springrest</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>springrest</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />

</beans>

Create bean class

5) Create a bean name “Country.java” in org.arpit.java2blog.bean.

package org.arpit.java2blog.bean;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="country")
public class Country{

    private int id;
    private String countryName;

    public Country() {

    }
    public Country(int i, String countryName) {
        super();
        this.id = i;
        this.countryName = countryName;
    }

    @XmlElement
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @XmlElement
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

We need to annotate bean class with @XmlRootElement and @XmlElement to support for xml. As you can see we have annotated Country class with
JAXB annotation but if you want to have support for list, we can not edit ArrayList class, so we can create another class called CountryList  and we can annotate with JAXB annotation in that class to support xml output.
CountryList.java

package org.arpit.java2blog.bean;

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "country-list")
public class CountryList {

    ListlistOfCountries;

    public CountryList() {
        super();
    }
    public CountryList(ListlistOfCountries) {
        this.listOfCountries=listOfCountries;
    }
    public ListgetListOfCountries() {
        return listOfCountries;
    }

    @XmlElement(name = "country")
    public void setListOfCountries(ListlistOfCountries) {
        this.listOfCountries = listOfCountries;
    }

}

Create controller

6) Create a controller named “CountryController.java”

package org.arpit.java2blog.controller;

import java.util.ArrayList;
import java.util.List;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.bean.CountryList;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CountryController {

    @RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/xml")
    public CountryList getCountries()
    {
        CountryList countryList=createCountryList();
        return countryList;
    }

    @RequestMapping(value = "/country/{id}", method = RequestMethod.GET)
    public Country getCountryById(@PathVariable int id)
    {
        ListlistOfCountries = new ArrayList();
        CountryList countryList=createCountryList();
        listOfCountries=countryList.getListOfCountries();
        for (Country country: listOfCountries) {
            if(country.getId()==id)
                return country;
        }

        return null;
    }

    /// Utiliy method to create country list.
    public CountryList createCountryList()
    {
        Country indiaCountry=new Country(1, "India");
        Country chinaCountry=new Country(4, "China");
        Country nepalCountry=new Country(3, "Nepal");
        Country bhutanCountry=new Country(2, "Bhutan");

        ListlistOfCountries = new ArrayList();
        listOfCountries.add(indiaCountry);
        listOfCountries.add(chinaCountry);
        listOfCountries.add(nepalCountry);
        listOfCountries.add(bhutanCountry);
        return new CountryList(listOfCountries);
    }
}

@PathVariable: Used to inject values from the URL into a method parameter.This way you inject id in getCountryById method .

We are not providing any view information in springrest-servlet.xml as we do in Spring MVC. If we need to directly get resource from controller, we need to return @ResponseBody as per Spring 3 but with Spring 4, we can use @RestController for that.
In spring 4.0, we can use @RestController which is combination of @Controller + @ResponseBody.

@RestController = @Controller + @ResponseBody

6) It ‘s time to do maven build.

Right click on project ->Run as ->Maven build
7) Provide goals as clean install (given below) and click on run

 

Run the application

8) Right click on project ->run as ->run on server
Select apache tomcat and click on finish

 

When you run the application, you might get this kind of warning

Mar 26, 2016 1:45:51 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringRestfulWebServicesWithXMLExample/] in DispatcherServlet with name 'SpringRestfulWebServicesWithJSONExample'

Please ignore above warning. When you start application, you have below URL if you have not provided start page:
http://localhost:8080/SpringRestfulWebServicesWithXMLExample/ 

As we have used DispatcherServlet in web.xml, this request goes to spring DispatcherServlet and it did not find corresponding mapping in controller , hence you get that warning.

9) Test your REST service under: “http://localhost:8080/SpringRestfulWebServicesWithXMLExample/countries”.

You will get following output:

Spring Rest XML list example

 

10) Now pass country id as a parameter to url.
“http://localhost:8080/SpringRestfulWebServicesWithXMLExample/country/2”.

 

click to begin
20KB .zip
We are done with Spring Restful web services xml example. If you are still facing any issue, please comment.

That’s all about Spring Restful web services xml example.

]]>
https://java2blog.com/spring-restful-web-services-xml-example/feed/ 3
Difference between SOAP and REST web services in java https://java2blog.com/difference-between-soap-and-rest-web-services/?utm_source=rss&utm_medium=rss&utm_campaign=difference-between-soap-and-rest-web-services https://java2blog.com/difference-between-soap-and-rest-web-services/#comments Sun, 26 Jun 2016 17:30:00 +0000 http://www.java2blog.com/?p=182

We have already seen SOAP web services and RESTful web services in detail before. In this post, we are going to see differences between SOAP and REST web services.

SOAP vs REST web services

Parameter
SOAP
REST
Acronym
SOAP stands for simple object access protocol
REST stands for REpresentational State Transfer
Protocol vs Architectural style
 SOAP is a standard protocol to create web services
Rest is architectural style to create web services.
Contract
Client and Server are bind with WSDL contract
There is no contract between client and Server.
Format Support
SOAP supports only XML format
REST web services supports XML, json and plain text etc.
Maintainability
SOAP web services are hard to maintain as if we do any changes in WSDL , we need to create client stub again
REST web services are generally easy to maintain.
Service interfaces vs URI
SOAP uses Service interfaces to expose business logic
Rest uses URI to expose business logic
Security
SOAP has its own security : WS-security
Rest inherits its security from underlying transport layer.
Bandwidth
SOAP requires more bandwidth and resources as it uses XML messages to exchange information
REST requires less bandwith and resources. It can use JSON also.
Learning curve
SOAP web services are hard to learn as you need to understand WSDL , client stub
REST web services are easy to understand as you need to annotate plain java class with JAX-RS annotations to use various HTTP methods.

This is all about Difference between SOAP and REST web services in java. If you find more differences, please comment, so that I can include them in post.

]]>
https://java2blog.com/difference-between-soap-and-rest-web-services/feed/ 3
Top 20 Web services interview questions https://java2blog.com/web-services-interview-questions/?utm_source=rss&utm_medium=rss&utm_campaign=web-services-interview-questions https://java2blog.com/web-services-interview-questions/#comments Fri, 24 Jun 2016 21:01:00 +0000 http://www.java2blog.com/?p=183 Web services interview questions are most asked questions if you are applying for software developer role.
In this post, we will see multiple web services interview questions.

1. What are web services?

Web services are ways of communication between two application over network. It allows you to expose business logic using API.
For example:
Lets say you are java developer, you can create web service and expose API over internet and any other developer (lets say .net developer ) can access it.

2. What are features of web services?

  • Interoperability
  • Reuse already developed(old) functionality into new software:
  • Loosely Coupled
  • Extensibility

3. What are different types of web services?

  • SOAP
  • Restful web services

4. What is SOAP?

SOAP stands for Simple object access protocol. It is protocol to exchange information using request and response in XML format over transport protocol such as HTTP, SMTP etc.

5. What are important components for SOAP?

  • Simple access object protocol (SOAP)
  • Web Services Description Language (WSDL)
  • Universal Description, Discovery and Integration(UDDI)

6. What is WSDL?

WSDL stands for Web Service Description Language. It is an XML file that describes the technical details of how to implement a web service, more specifically the URI, port, method names, arguments, and data types. You can understand following details using WSDL

  •     Port / Endpoint – URL of the web service
  •     Input message format
  •     Output message format
  •     Security protocol that needs to be followed
  •     Which protocol the web service uses

7. What is UDDI?

UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web service provider can register themselves with a UDDI and make themselves available through it for discovery.

8. What is JAX-WS?

JAX-WS stands for Java API for XML Web Services. JAX-WS is standard XML based Java API which is used to create SOAP web services.

9. What are some important annotations for JAX-WS?

  • @WebService
  • @WebMethod
  • @SOAPBinding

10. What do you mean by end point in terms of SOAP?

End point is nothing but URL which other application can use to access it.

for example:
end  point:http://localhost:8080/WS/HelloWorld

11. How can you access WSDL for web service?

You just need to put ?wsdl at the end of end point URL.
for example:
end  point:http://localhost:8080/WS/HelloWorld
WSDL url: http://localhost:8080/WS/HelloWorld?wsdl

12. What is wsimport?

wsimport is utility which generates java classes from WSDL. It is part of JDK 6.

13.What is sun-jaxws.xml file?

This file provides endpoint details about JAX-WS web service which is deployed on tomcat.It is available at WEB-INF directory.
For example:

<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
  <endpoint
     name="HelloWorldWS"
     implementation="org.arpit.javapostsforlearning.webservice.HelloWorldImpl"
     url-pattern="/HelloWorldWS"/>
</endpoints> 

14. What are Restful web services?

In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web services client uses that URI to access the resource.

15.What are HTTP methods that can be used with Restful web services?

Mainly used HTTP methods are GET, POST, PUT, DELETE, HEAD and OPTIONS

16. What is JAX-RS?

Java API for RESTful Web Services (JAX-RS), is a set if APIs to create web service which supports REST architecture. JAX-RS is part of the Java EE6, and help developers to create REST web application easily.

17. What are some important annotations which you use to create Restful web services?

Some of important annotations which are used for creating web services are:

@Path : This is used to set path for URI at class level or method level
@GET,@POST,@PUT,@DELETE  : There are annotations corresponds to HTTP methods
@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method
@PathParam: Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Cosumes defines which MIME type will be consumed by the method .

18.  What are ways to test SOAP web services?

For testing SOAP :
SOAPUI
For testing Restful web services:

  • Postman for chrome browser
  • poster for firefox

19. How to choose between REST and SOAP web services?

  • If you want to implement web services in less time, go with REST
  • If you know your client beforehand , then you can choose SOAP. If you are not aware about clients then go with REST.
  • If you want to work with different format other than XML, go with REST. SOAP only supports XML format.

20. What are differences between SOAP and REST web services?

You can refer to difference between SOAP and REST web services for more details.

That’s all about Web services interview questions.

You may also like:

]]>
https://java2blog.com/web-services-interview-questions/feed/ 2
Restful web services interview questions https://java2blog.com/restful-web-services-interview-questions/?utm_source=rss&utm_medium=rss&utm_campaign=restful-web-services-interview-questions https://java2blog.com/restful-web-services-interview-questions/#comments Wed, 22 Jun 2016 19:29:00 +0000 http://www.java2blog.com/?p=184 Restful web services are very popular now a days because it is very simple to implement and less time consuming. In this post, we are going to see restful web services interview questions with answers.

1. What is REST?

REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis.

In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.REST isn’t protocol specific, but when people talk about REST they usually mean REST over HTTP.

2. What are Restful web services?

In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web services client uses that URI to access the resource.
It consists of two components REST server which provides access to the resources and a REST client which accesses and modify the REST resources.

3. What are important features of Restful web services?

Some important features of Restful web services are:
Resource identification through URI:Resources are identified by their URIs (typically links on internet). So, a client can directly access a RESTful Web Services using the URIs of the resources (same as you put a website address in the browser’s address bar and get some representation as response).
Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE.
Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.
Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
Named resources – the system is comprised of resources which are named using a URL.
Interconnected resource representations – the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
Layered components – intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.

4. What are HTTP methods that can be used in Restful web services?

RESTful web services use HTTP protocol methods for the operations they perform.
Some important Methods are:
GET : It defines a reading access of the resource without side-effects.This operation is idempotent i.e.they can be applied multiple times without changing the result
PUT : It is generally used for updating resource. It must also be idempotent.
DELETE : It removes the resources. The operations are idempotent i.e. they can get repeated without leading to different results.
POST : It is used for creating a new resource. It is not idempotent.

5. What do you mean by Idempotent and which HTTP methods are idempotent?

Idempotent means result of multiple successful request will not change state of resource after initial application
For example : Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted. Get, put and delete are HTTP Idempotent methods.

6. What are differences between Post and Put Http methods?

POST :It is used for creating a new resource. It is not idempotent.
PUT : It is generally used for updating resource. It is idempotent.
Idempotent means result of multiple successful request will not change state of resource after initial application

7. What happens if resources are shared by multiple clients? Do you need to make it thread safe explicitly?

New resource instance is created for each request, so you don’t need to implement thread safety or synchronization aid. It is by default thread safe.

8. What is JAX-RS?

Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

9. What are REST frameworks that you are aware of and which can be used to create Restful webservices?

There are multiple Rest framework that can be used to create Restful web services such as

  • Jersey
  • RestEasy
  • Restlet
  • CFX
  • Spring Rest webservices

10. What are some important annotations which you use to create Restful web services?

Some of important annotations which are used for creating web services are:

@Path : This is used to set path for URI at class level or method level
@GET,@POST,@PUT,@DELETE  : There are annotations corresponds to HTTP methods
@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method
@PathParam: Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Cosumes defines which MIME type will be consumed by the method .

11. Can you use get method to create Resources rather than post?

No, Get should be used only for resource retrieval and not for resource creation.

12.  What are ways to test Restful web services?

You require a restful client to test restful web services. You can use:

  • Postman for chrome browser
  • poster for firefox

You may also like:

]]>
https://java2blog.com/restful-web-services-interview-questions/feed/ 1
Spring Restful web services CRUD example https://java2blog.com/spring-restful-web-services-crud-example/?utm_source=rss&utm_medium=rss&utm_campaign=spring-restful-web-services-crud-example https://java2blog.com/spring-restful-web-services-crud-example/#comments Fri, 15 Apr 2016 18:13:00 +0000 http://www.java2blog.com/?p=243
In this post, we are going see Spring Restful web services CRUD example.

Web service Tutorial Content:

In previous post, we have already seen Spring Restful web services which returns json as response.In this post, we will extend same example and create Restful web services which will provide CRUD(Create, read, update and delete) operation example.If you want complete integration with hibernate and mysql, you can go through Spring Restful hibernate mysql example.

We will use following annotations for CRUD operation.

Method
Description
Get
It is used to read resource
Post
It is used to create new resource.
It is not idempotent method
Put
It is generally used to update resource.It is idempotent method
Delete
It is used to delete resource

Idempotent means result of multiple successful request will not change state of resource after initial application
For example :
Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted.

Post is not idempotent method because when you use post to create resource , it will keep creating resource for each new request, so result of multiple successful request will not be same.

Source code:

Here are steps to create a Spring Restful web services  which will provide CRUD opertion.

1) Create a dynamic web project using maven in eclipse named “SpringRestfulWebServicesCRUDExample”

Maven dependencies

2) We need to add Jackson json utility in the classpath.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
 </dependency>
Spring will load Jackson2JsonMessageConverter into its application context automatically. Whenever you request resource as json with accept headers=”Accept=application/json”, then Jackson2JsonMessageConverter comes into picture and convert resource to json format.

Now change pom.xml as follows:
pom.xml

<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.arpit.java2blog</groupId>
  <artifactId>SpringRestfulWebServicesWithJSONExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
        </dependency>
 </dependencies>
 <build>
  <finalName>SpringRestfulWebServicesWithJSONExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring application configuration:

3) Change web.xml as below:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
 <servlet-name>springrest</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>springrest</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />

</beans>

Create bean class

4) Create a bean name “Country.java” in org.arpit.java2blog.bean.

package org.arpit.java2blog.bean;

public class Country{

    int id;
    String countryName;
    long population;

    public Country() {
        super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

}

Create Controller

5) Create a controller named “CountryController.java” in package org.arpit.java2blog.controller

package org.arpit.java2blog.controller;

import java.util.List;
import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CountryController {

    CountryService countryService = new CountryService();

    @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
    public List getCountries() {
        List listOfCountries = countryService.getAllCountries();
        return listOfCountries;
    }

    @RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    public Country getCountryById(@PathVariable int id) {
        return countryService.getCountry(id);
    }

    @RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
    public Country addCountry(@RequestBody Country country) {
        return countryService.addCountry(country);
    }

    @RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
    public Country updateCountry(@RequestBody Country country) {
        return countryService.updateCountry(country);

    }

    @RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public void deleteCountry(@PathVariable("id") int id) {
        countryService.deleteCountry(id);

    }
}

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is just a helper class which should be replaced by database implementation. It is not very well written class, it is just used for demonstration.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.arpit.java2blog.bean.Country;

/*
 * It is just a helper class which should be replaced by database implementation.
 * It is not very well written class, it is just used for demonstration.
 */
public class CountryService {

    static HashMap<Integer,Country> countryIdMap=getCountryIdMap();

    public CountryService() {
        super();

        if(countryIdMap==null)
        {
            countryIdMap=new HashMap<Integer,Country>();
            // Creating some objects of Country while initializing
            Country indiaCountry=new Country(1, "India",10000);
            Country chinaCountry=new Country(4, "China",20000);
            Country nepalCountry=new Country(3, "Nepal",8000);
            Country bhutanCountry=new Country(2, "Bhutan",7000);

            countryIdMap.put(1,indiaCountry);
            countryIdMap.put(4,chinaCountry);
            countryIdMap.put(3,nepalCountry);
            countryIdMap.put(2,bhutanCountry);
        }
    }

    public List getAllCountries()
    {
        List countries = new ArrayList(countryIdMap.values());
        return countries;
    }

    public Country getCountry(int id)
    {
        Country country= countryIdMap.get(id);
        return country;
    }
    public Country addCountry(Country country)
    {
        country.setId(getMaxId()+1);
        countryIdMap.put(country.getId(), country);
        return country;
    }

    public Country updateCountry(Country country)
    {
        if(country.getId()<=0)
            return null;
        countryIdMap.put(country.getId(), country);
        return country;

    }
    public void deleteCountry(int id)
    {
        countryIdMap.remove(id);
    }

    public static HashMap<Integer, Country> getCountryIdMap() {
        return countryIdMap;
    }

    // Utility method to get max id
    public static int getMaxId()
    { int max=0;
    for (int id:countryIdMap.keySet()) {
        if(max<=id)
            max=id;

    }
    return max;
    }
}

7) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

Maven build in eclipse
8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

10) We will test this application in  postman , UI based client for testing restful web applications. It is chrome plugin. Launch postman.If you want java based client, then you can also use how to send get or post request in java.

Get method

11) Test your get method Spring REST service
URL :“http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries”.

You will get following output:

Get operation in Spring Rest CRUD

Post method

12) Post method is used to create new resource. Here we are adding new Country England to country list, so you can see we have used new country json in post body.
URL: “http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries”.

Put operation in Spring Rest CRUD

Use get method to check if above country have been added to country list.

Get operation in Spring Rest CRUD

Put Method

13) Put method is used to update resource. Here will update population of nepal using put method.
We will update country json in body of request.
URL : “http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries”

Get operation in Spring Rest CRUD

Use get method to check population of nepal.

Get operation in Spring Rest CRUD

Delete method

14) Delete method is used to delete resource.We will pass id of country which needs to be deleted as PathParam. We are going delete id:4 i.e. china to demonstrate delete method.

URL : “http://localhost:8080/SpringRestfulWebServicesCRUDExample/country/4”

Delete operation in Spring Rest CRUD

Use get method to check country list.

Get operation in Spring Rest CRUD

As you can see, we have deleted country with id 4 i.e. china

Project structure:


We are done with Spring Restful web services json CRUD example. If you are still facing any issue, please comment.

]]>
https://java2blog.com/spring-restful-web-services-crud-example/feed/ 20
RESTful web services JAXRS CRUD example using jersey https://java2blog.com/restful-web-services-jaxrs-crud-example/?utm_source=rss&utm_medium=rss&utm_campaign=restful-web-services-jaxrs-crud-example https://java2blog.com/restful-web-services-jaxrs-crud-example/#comments Tue, 29 Mar 2016 13:45:00 +0000 http://www.java2blog.com/?p=263
This post is in continuation with web service tutorial (Part -8).

In previous post, we have already seen simple Restful web services(JAXWS)  which returns json as response.In this post, we will extend same example and create Restful web services(JAXWS) using jersey which will provide CRUD(Create, read, update and delete) operation example.

We will use following annotations for CRUD operation.

Method
Description
Get
It is used to read resource
Post
It is used to create new resource.
It is not idempotent method
Put
It is generally used to update resource.It is idempotent method
Delete
It is used to delete resource

Idempotent means result of multiple successful request will not change state of resource after initial application
For example :
Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted.

Post is not idempotent method because when you use post to create resource , it will keep creating resource for each new request, so result of multiple successful request will not be same.

Source code:

click to begin
20KB .zip

Here are steps to create a simple Restful web services(JAXWS)  using jersey which will provide CRUD opertion.
1) Create a dynamic web project using maven in eclipse named “JAXRSJsonCRUDExample”

Maven dependencies

2) We need to add jersey jars utility in the classpath.

 
 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
 </dependency>
 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
 </dependency>
Jersey internally uses Jackson for Json Handling, so it will be used to marshal pojo objects to JSON.

Now create pom.xml as follows:
pom.xml

<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.arpit.java2blog</groupId>
 <artifactId>JAXRSJsonExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>JAXRSJsonExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
   <properties>
        <jersey.version>1.18.3</jersey.version>
    </properties>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
  </dependency>

  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>JAXRSJsonExample</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

Application configuration:

3) create web.xml as below:

<?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"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created 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>org.arpit.java2blog.controller</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>

Please change initParam “com.sun.jersey.config.property.package” property to provide correct controller package name if you are not using same package.

Create bean class

4) Create a bean name “Country.java” in org.arpit.java2blog.bean.

package org.arpit.java2blog.bean;

public class Country{

 int id;
 String countryName; 
 long population;

 public Country() {
 super();
 }
 public Country(int i, String countryName,long population) {
 super();
 this.id = i;
 this.countryName = countryName;
 this.population=population;
 }
 public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 public String getCountryName() {
 return countryName;
 }
 public void setCountryName(String countryName) {
 this.countryName = countryName;
 }
 public long getPopulation() {
 return population;
 }
 public void setPopulation(long population) {
 this.population = population;
 } 

}

Create Controller

5) Create a controller named “CountryController.java” in package org.arpit.java2blog.controller

package org.arpit.java2blog.controller;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;

@Path("/countries")
public class CountryController {

 CountryService countryService=new CountryService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
 public List getCountries()
 {

  List listOfCountries=countryService.getAllCountries();
  return listOfCountries;
 }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
 public Country getCountryById(@PathParam("id") int id)
 {
  return countryService.getCountry(id);
 }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
 public Country addCountry(Country country)
 {
  return countryService.addCountry(country);
 }

    @PUT
    @Produces(MediaType.APPLICATION_JSON)
 public Country updateCountry(Country country)
 {
  return countryService.updateCountry(country);

 }

    @DELETE
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
 public void deleteCountry(@PathParam("id") int id)
 {
   countryService.deleteCountry(id);

 }

}

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml” configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.APPLICATION_JSON[, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text (“text/json”) is produced.

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is just a helper class which should be replaced by database implementation. It is not very well written class, it is just used for demonstration.
package org.arpit.java2blog.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.arpit.java2blog.bean.Country;

/*
 * It is just a helper class which should be replaced by database implementation.
 * It is not very well written class, it is just used for demonstration.
 */
public class CountryService {

 static HashMap<Integer,Country> countryIdMap=getCountryIdMap();

 public CountryService() {
  super();

  if(countryIdMap==null)
  {
   countryIdMap=new HashMap<Integer,Country>();
  // Creating some objects of Country while initializing
   Country indiaCountry=new Country(1, "India",10000);
   Country chinaCountry=new Country(4, "China",20000);
   Country nepalCountry=new Country(3, "Nepal",8000);
   Country bhutanCountry=new Country(2, "Bhutan",7000);

   countryIdMap.put(1,indiaCountry);
   countryIdMap.put(4,chinaCountry);
   countryIdMap.put(3,nepalCountry);
   countryIdMap.put(2,bhutanCountry);
  }
 }

 public List getAllCountries()
 {
  List countries = new ArrayList(countryIdMap.values());
  return countries;
 }

 public Country getCountry(int id)
 {
  Country country= countryIdMap.get(id);
  return country;
 }
 public Country addCountry(Country country)
 {
  country.setId(countryIdMap.size()+1);
  countryIdMap.put(country.getId(), country);
  return country;
 }

 public Country updateCountry(Country country)
 {
  if(country.getId()<=0)
   return null;
  countryIdMap.put(country.getId(), country);
  return country;

 }
 public void deleteCountry(int id)
 {
  countryIdMap.remove(id);
 }

 public static HashMap<Integer, Country> getCountryIdMap() {
  return countryIdMap;
 }
}

7) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build
Jersey maven build

8) Provide goals as clean install (given below) and click on run

Jersey maven clean install

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

Running Project

10) We will test this application in  postman , UI based client for testing restful web applications. It is chrome plugin. Launch postman. If you want java based client, then you can also use how to send get or post request in java.

Get method

11) Test your get method REST service
URL :“http://localhost:8080/JAXRSJsonCRUDExample/rest/countries”.

You will get following output:

Get all countries

Post method

12) Post method is used to create new resource. Here we are adding new Country England to country list, so you can see we have used new country json in post body.
URL: “http://localhost:8080/JAXRSJsonCRUDExample/rest/countries”.

Post method

Use get method to check if above country have been added to country list.

Post method result

Put Method

13) Put method is used to update resource. Here will update population of nepal using put method.
We will update country json in body of request.
URL : “http://localhost:8080/JAXRSJsonCRUDExample/rest/countries”
Put method
Use get method to check population of nepal.
Put method result

Delete method

14) Delete method is used to delete resource.We will pass id of country which needs to be deleted as PathParam. We are going delete id:4 i.e. china to demonstrate delete method.

URL : “http://localhost:8080/JAXRSJsonCRUDExample/rest/countries/4”
Delete method
Use get method to check country list.
Delete method result
As you can see, we have deleted country with id 4 i.e. china

Project structure:

Project Structure CRUD

We are done with Restful web services json CRUD example using jersey. If you are still facing any issue, please comment.

]]>
https://java2blog.com/restful-web-services-jaxrs-crud-example/feed/ 8
AngularJS Restful web service example using $http https://java2blog.com/angularjs-restful-web-service-example/?utm_source=rss&utm_medium=rss&utm_campaign=angularjs-restful-web-service-example https://java2blog.com/angularjs-restful-web-service-example/#comments Mon, 28 Mar 2016 18:46:00 +0000 http://www.java2blog.com/?p=258
This post is in continuation with AngularJS web services tutorial

In previous post, we have already seen Restful web services CRUD example. In this post, we will use AngularJS to call rest CRUD APIs. So we are going to create a view and then perform CRUD operations on the basis of button clicks.

Source code:

click to begin
20KB .zip

Here are steps to create a simple Restful web services(JAXWS)  using jersey which will provide CRUD opertion.

1) Create a dynamic web project using maven in eclipse named “JAXRSJsonCRUDExample”

Maven dependencies

2) We need to add jersey jars utility in the classpath.

<dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
 </dependency>
 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
 </dependency>
Jersey internally uses Jackson for Json Handling, so it will be used to marshal pojo objects to JSON.

Now create pom.xml as follows:
pom.xml

<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.arpit.java2blog</groupId>
 <artifactId>JAXRSJsonExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>JAXRSJsonExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
   <properties>
        <jersey.version>1.18.3</jersey.version>
    </properties>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
  </dependency>

  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>JAXRSJsonExample</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

Application configuration:

3) create web.xml as below:

<?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"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created 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>org.arpit.java2blog.controller</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>

Please change initParam “com.sun.jersey.config.property.package” property to provide correct controller package name if you are not using same package.

Create bean class

4) Create a bean name “Country.java” in org.arpit.java2blog.bean.

package org.arpit.java2blog.bean;

public class Country{

    int id;
    String countryName;
    long population;

    public Country() {
        super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

}

Create Controller

5) Create a controller named “CountryController.java” in package org.arpit.java2blog.controller

package org.arpit.java2blog.controller;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;

@Path("/countries")
public class CountryController {

    CountryService countryService=new CountryService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List getCountries()
    {

        List listOfCountries=countryService.getAllCountries();
        return listOfCountries;
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Country getCountryById(@PathParam("id") int id)
    {
        return countryService.getCountry(id);
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public Country addCountry(Country country)
    {
        return countryService.addCountry(country);
    }

    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    public Country updateCountry(Country country)
    {
        return countryService.updateCountry(country);

    }

    @DELETE
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public void deleteCountry(@PathParam("id") int id)
    {
        countryService.deleteCountry(id);

    }

}

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml” configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.APPLICATION_JSON[, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text (“text/json”) is produced.

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is just a helper class which should be replaced by database implementation. It is not very well written class, it is just used for demonstration.
package org.arpit.java2blog.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.exception.CountryNotFoundException;

/*
 * It is just a helper class which should be replaced by database implementation.
 * It is not very well written class, it is just used for demonstration.
 */
public class CountryService {

    static HashMap<Integer,Country> countryIdMap=getCountryIdMap();

    public CountryService() {
        super();

        if(countryIdMap==null)
        {
            countryIdMap=new HashMap<Integer,Country>();
            // Creating some object of countries while initializing
            Country indiaCountry=new Country(1, "India",10000);
            Country chinaCountry=new Country(4, "China",20000);
            Country nepalCountry=new Country(3, "Nepal",8000);
            Country bhutanCountry=new Country(2, "Bhutan",7000);

            countryIdMap.put(1,indiaCountry);
            countryIdMap.put(4,chinaCountry);
            countryIdMap.put(3,nepalCountry);
            countryIdMap.put(2,bhutanCountry);
        }
    }

    public List getAllCountries()
    {
        List countries = new ArrayList(countryIdMap.values());
        return countries;
    }

    public Country getCountry(int id)
    {
        Country country= countryIdMap.get(id);

        if(country == null)
        {
            throw new CountryNotFoundException("Country with id "+id+" not found");
        }
        return country;
    }
    public Country addCountry(Country country)
    {
        country.setId(getMaxId()+1);
        countryIdMap.put(country.getId(), country);
        return country;
    }

    public Country updateCountry(Country country)
    {
        if(country.getId()<=0)
            return null;
        countryIdMap.put(country.getId(), country);
        return country;

    }
    public void deleteCountry(int id)
    {
        countryIdMap.remove(id);
    }

    public static HashMap<Integer, Country> getCountryIdMap() {
        return countryIdMap;
    }

    // Utility method to get max id
    public static int getMaxId()
    {   int max=0;
    for (int id:countryIdMap.keySet()) {
        if(max<=id)
            max=id;

    }

    return max;
    }
}

AngularJS view

7) create angularJSCrudExample.html in WebContent folder with following content:

<html>
  <head>

  <script src="proxy.php?url=https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>

    <title>AngularJS $http Rest example</title>
 <script type="text/javascript">
            var app = angular.module("CountryManagement", []);

            //Controller Part
            app.controller("CountryController", function($scope, $http) {

                $scope.countries = [];
                $scope.countryForm = {
                    id : -1,
                    countryName : "",
                    population : ""
                };

                //Now load the data from server
                _refreshCountryData();

                //HTTP POST/PUT methods for add/edit country
                // with the help of id, we are going to find out whether it is put or post operation

                $scope.submitCountry = function() {

                    var method = "";
                    var url = "";
                    if ($scope.countryForm.id == -1) {
                        //Id is absent in form data, it is create new country operation
                        method = "POST";
                        url = 'rest/countries';
                    } else {
                        //Id is present in form data, it is edit country operation
                        method = "PUT";
                        url = 'rest/countries';
                    }

                    $http({
                        method : method,
                        url : url,
                        data : angular.toJson($scope.countryForm),
                        headers : {
                            'Content-Type' : 'application/json'
                        }
                    }).then( _success, _error );
                };

                //HTTP DELETE- delete country by Id
                $scope.deleteCountry = function(country) {
                    $http({
                        method : 'DELETE',
                        url : 'rest/countries/' + country.id
                    }).then(_success, _error);
                };

             // In case of edit, populate form fields and assign form.id with country id
                $scope.editCountry = function(country) {

                    $scope.countryForm.countryName = country.countryName;
                    $scope.countryForm.population = country.population;
                    $scope.countryForm.id = country.id;
                };

                /* Private Methods */
                //HTTP GET- get all countries collection
                function _refreshCountryData() {
                    $http({
                        method : 'GET',
                        url : 'http://localhost:8080/AngularjsJAXRSCRUDExample/rest/countries'
                    }).then(function successCallback(response) {
                        $scope.countries = response.data;
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
                }

                function _success(response) {
                    _refreshCountryData();
                    _clearFormData()
                }

                function _error(response) {
                    console.log(response.statusText);
                }

                //Clear the form
                function _clearFormData() {
                    $scope.countryForm.id = -1;
                    $scope.countryForm.countryName = "";
                    $scope.countryForm.population = "";

                };
            });
        </script>
        <style>

       .blue-button{
     background: #25A6E1;
     filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
     padding:3px 5px;
     color:#fff;
     font-family:'Helvetica Neue',sans-serif;
     font-size:12px;
     border-radius:2px;
     -moz-border-radius:2px;
     -webkit-border-radius:4px;
     border:1px solid #1A87B9
           }

       .red-button{
    background: #CD5C5C;

    padding:3px 5px;
    color:#fff;
    font-family:'Helvetica Neue',sans-serif;
    font-size:12px;
    border-radius:2px;
    -moz-border-radius:2px;
    -webkit-border-radius:4px;
    border:1px solid #CD5C5C
           }

       table {
           font-family: "Helvetica Neue", Helvetica, sans-serif;
           width: 50%;
       }

       caption {
           text-align: left;
           color: silver;
           font-weight: bold;
           text-transform: uppercase;
           padding: 5px;
       }

       th {
           background: SteelBlue;
           color: white;
       }

       tbody tr:nth-child(even) {
           background: WhiteSmoke;
       }

       tbody tr td:nth-child(2) {
           text-align:center;
       }

       tbody tr td:nth-child(3),
       tbody tr td:nth-child(4) {
           text-align: center;
           font-family: monospace;
       }

       tfoot {
           background: SeaGreen;
           color: white;
           text-align: right;
       }

       tfoot tr th:last-child {
           font-family: monospace;
       }

       td,th{
            border: 1px solid gray;
            width: 25%;
            text-align: left;
            padding: 5px 10px;
        }

        </style>
    <head>
    <body ng-app="CountryManagement" ng-controller="CountryController">
         <h1>
           AngularJS Restful web services example using $http
        </h1>
        <form ng-submit="submitCountry()">
            <table>

                <tr>
                    <th colspan="2">Add/Edit country</th>
                 </tr>
                <tr>
                    <td>Country</td>
                    <td><input type="text" ng-model="countryForm.countryName" /></td>
                </tr>
                <tr>
                    <td>Population</td>
                    <td><input type="text" ng-model="countryForm.population"  /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="Submit" class="blue-button" /></td>
                </tr>
            </table>
        </form>
        <table>
            <tr>

                <th>CountryName</th>
                <th>Population</th>
                <th>Operations</th>

            </tr>

            <tr ng-repeat="country in countries">

    <td> {{ country.countryName }}</td>
    <td >{{ country.population }}</td>

                <td><a ng-click="editCountry(country)" class="blue-button">Edit</a> | <a ng-click="deleteCountry(country)" class="red-button">Delete</a></td>
            </tr>

        </table>

  </body>
</html>

Explanation :

    • We have injected $http as we have done in ajax example through controller constructor.

app.controller("CountryController", function($scope, $http) {

                $scope.countries = [];
...

    • We have defined various methods depending on operations such as editCountry, deleteCountry, submitCountry
    • When you click on submit button on form, it actually calls POST or PUT depending on operation. If you click on edit and submit data then it will be put operation as it will be update on existing resource. If you directly submit data, then it will be POST operation to create new resource,
    • Every time you submit data, it calls refereshCountryData() to refresh country table below.
    • When you call $http, you need to pass method type and URL, it will call it according, You can either put absolute URL or relative URL with respect to context root of web application.

//HTTP GET- get all countries collection
                function _refreshCountryData() {
                    $http({
                        method : 'GET',
                        url : 'http://localhost:8080/JAXRSJsonCRUDExample/rest/countries'
                    }).then(function successCallback(response) {
                        $scope.countries = response.data;
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
                }

8) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

9) Provide goals as clean install (given below) and click on run

Run the application

10) Right click on angularJSCrudExample.html -> run as -> run on server
Select apache tomcat and click on finish
10) You should be able to see below page
URL : “http://localhost:8080/AngularjsJAXRSCRUDExample/angularJSCrudExample.html”


Lets click on delete button corresponding to Nepal and you will see below screen:

Lets add new country France with population 15000

Click on submit and you will see below screen.

Now click on edit button corresponding to India and change population from 10000 to 100000.

Click on submit and you will see below screen:



Lets check Get method for Rest API

11) Test your get method REST service
URL :“http://localhost:8080/AngularjsJAXRSCRUDExample/rest/countries/”.

You will get following output:

As you can see , all changes have been reflected in above get call.

Project structure:


We are done with Restful web services json CRUD example using jersey. If you are still facing any issue, please comment.

]]>
https://java2blog.com/angularjs-restful-web-service-example/feed/ 4
JAX-RS @MatrixParam example https://java2blog.com/jax-rs-matrixparam-example/?utm_source=rss&utm_medium=rss&utm_campaign=jax-rs-matrixparam-example https://java2blog.com/jax-rs-matrixparam-example/#respond Thu, 25 Feb 2016 18:39:00 +0000 http://www.java2blog.com/?p=264
This post is in continuation with web service tutorial (Part -10).

In previous post, we have used @QueryParam for passing parameter to URL in JAX-RS @QueryParam example and  In case of @QueryParam, we pass parameters as well as its values separated by ? but in case of @MatrixParam, key value pairs are separared by semicolon(;).
For example:

http://localhost:8080/JAXRSJsonExample/rest/countries/country;id=1;countryName=India

Here Parameter names are id,countryName and its values are 3,Nepal respectively separated by ;.

Here are steps to create a JAXRS json example which will use @MatrixParam.

1) Follow steps on RESTful Web Services json example to create simple RESTful web services which uses @PathParam.
2) Change CountryRestService.java to use @MatrixParam as below.

package org.arpit.java2blog.jaxrs;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.arpit.java2blog.bean.Country;
/*
 * author: Arpit Mandliya
 * */
@Path("/countries")
public class CountryRestService {

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public List getCountries()
 {
 List listOfCountries = new ArrayList();
 listOfCountries=createCountryList();
 return listOfCountries;
 }

 @GET
 @Path("/country")
 @Produces(MediaType.APPLICATION_JSON)
 public Country getCountryById(@MatrixParam("id") int id,@MatrixParam("countryName") String countryName)
 {
 List listOfCountries = new ArrayList();
 listOfCountries=createCountryList();

 for (Country country: listOfCountries) {
 if(country.getId()==id && country.getCountryName().equalsIgnoreCase(countryName))
 return country;
 }

 return null;
 }

// Utiliy method to create country list.
 public List createCountryList()
 {
 Country indiaCountry=new Country(1, "India");
 Country chinaCountry=new Country(4, "China");
 Country nepalCountry=new Country(3, "Nepal");
 Country bhutanCountry=new Country(2, "Bhutan");

 List listOfCountries = new ArrayList();
 listOfCountries.add(indiaCountry);
 listOfCountries.add(chinaCountry);
 listOfCountries.add(nepalCountry);
 listOfCountries.add(bhutanCountry);
 return listOfCountries;
 }
}

That’s all. We need to run the application now.

Run the application

3) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
4) Now pass country id and country name as parameters to url separated by ;.
“http://localhost:8080/JAXRSJsonExample/rest/countries/country;id=1;countryName=India”.

We are done with Restful web services json MatrixParam example. If you are still facing any issue, please comment.

]]>
https://java2blog.com/jax-rs-matrixparam-example/feed/ 0
RESTful Web Services (JAX-RS) @QueryParam Example https://java2blog.com/restful-web-services-jax-rs-queryparam/?utm_source=rss&utm_medium=rss&utm_campaign=restful-web-services-jax-rs-queryparam https://java2blog.com/restful-web-services-jax-rs-queryparam/#comments Wed, 28 Oct 2015 18:11:00 +0000 http://www.java2blog.com/?p=312
This post is in continuation with web service tutorial (Part -9).

In previous post, we have used @PathParam for passing parameter to URL in RESTful Web Services json example and we have directly passed parameter values but JAXRS @QueryParam can be used to pass query parameters. In case of @QueryParam, we pass parameters as well as its values.
For example: http://localhost:8080/JAXRSJsonExample/rest/countries/country?id=3&countryName=Nepal
Here Parameter names are id,countryName and its values are 3,Nepal respectively.

@QueryParam can be used in case of filtering . When you want show both param as well value in url.
For example: Lets say you are showing list of customers on a website and you can show 10 at a time. When user click next , he will see next 10 customers, so in this case, we can use @QueryParam may look something like this

http://localhost:8080/JAXRSJsonExample/rest/listOfCustomers?start=10&size=10

Here are steps to create a JAXRS json example which will use @QueryParam.

1) Follow steps on RESTful Web Services json example to create simple RESTful web services which uses @PathParam.
2) Change CountryRestService.java to use @QueryParam as below.

package org.arpit.java2blog.jaxrs;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.arpit.java2blog.bean.Country;
/*
 * author: Arpit Mandliya
 * */
@Path("/countries")
public class CountryRestService {

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public List getCountries()
 {
 List listOfCountries = new ArrayList();
 listOfCountries=createCountryList();
 return listOfCountries;
 }

 @GET
 @Path("/country")
 @Produces(MediaType.APPLICATION_JSON)
 public Country getCountryById(@QueryParam("id") int id,@QueryParam("countryName") String countryName)
 {
 List listOfCountries = new ArrayList();
 listOfCountries=createCountryList();

 for (Country country: listOfCountries) {
 if(country.getId()==id && country.getCountryName().equalsIgnoreCase(countryName))
 return country;
 }

 return null;
 }

// Utiliy method to create country list.
 public List createCountryList()
 {
 Country indiaCountry=new Country(1, "India");
 Country chinaCountry=new Country(4, "China");
 Country nepalCountry=new Country(3, "Nepal");
 Country bhutanCountry=new Country(2, "Bhutan");

 List listOfCountries = new ArrayList();
 listOfCountries.add(indiaCountry);
 listOfCountries.add(chinaCountry);
 listOfCountries.add(nepalCountry);
 listOfCountries.add(bhutanCountry);
 return listOfCountries;
 }
}

That’s all. We need to run the application now.

Run the application

3) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
4) Now pass country id and country name as parameter to url.
“http://localhost:8080/JAXRSJsonExample/rest/countries/country?id=3&countryName=Nepal”.

We are done with Restful web services json QueryParam example. If you are still facing any issue, please comment.

]]>
https://java2blog.com/restful-web-services-jax-rs-queryparam/feed/ 1