Progress-servis55.ru

Новости из мира ПК
7 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Web services java

Реализуем RESTful Web Service на java

Добрый день всем хаброжителям!

Поводом к написанию статьи послужило, то что к моему большому удивлению на хабре я не нашёл статьи о реализации RESTful Web Service на Java, может, конечно, плохо искал. Да написано про RESTful web services очень много, но как то вот так, чтобы простенько с примерами кода, рабочий сервис, не так уж и легко найти и не только на хабре…

Вообще с REST я познакомился совсем недавно, не больше месяца назад. Так что буду очень благодарен за советы, поправки и критику!

Разобраться было и так вообщем то не сложно, но я думаю аналогичный пост мне бы очень помог и сильно бы ускорил процесс обучения! Тем более, если вы начинающий разработчик и о многом только слышали, а руками никогда не трогали.

По моему первому впечатлению: действительно вещь очень удобная, а главное очень простая, ещё и если использовать JSON, а не XML, ну по крайней мере мне так показалось после опыта работы с SOAP и WSDL. Ну, да об этом я думаю и так все знают, кто хоть немного работал с веб сервисами.

Так что, кто заинтересовался реализацией, прошу под кат

Сразу оговоримся:

1. весь код, конечно, в статье не выложишь и о нём не расскажешь;
2. версия проектика, конечно, не финальная и, как я уже говорил выше — буду очень благодарен за замечания и советы;
3. конечно же, есть баги.

И так, начнём по порядку:

ПО выбиралось по очень простому принципу — чем проще, тем лучше. Да, вместо MySQL для нагруженных сервисов без необходимости делать сложные запросы в базу, очень хорошо использовать MongoDB, ну, по крайней мере по этому поводу много написанно, да и опять же удобнее её использовать так как на входе тот же JSON.

2. В принципе что будет делать наш сервис — тут всё очень банально: сервис будет работать с одной табличкой в БД — сосбственно вставлять, апдейтать, удалять, ну и, конечно же, получать записи списком или по Id. Конечно же, хотелось бы иметь возможность параметризированного запроса на получение списка записей, не плохо было бы сделать «красивый» урл к сервису, прикрутить какой-нибудь интерсептор, чтобы, например, проверять права пользователя на доступ к сервису, или что-нибудь другое делать перед запуском сервиса, ну и как-то централизованно управлять кодами ошибок в ответах от сервера.

4 стандартных статуса, которые мы будем дополнительно обрабатывать (например, добавлять версию наших веб сервисов в ответ и при ошибке — наш код ошибки):

200 — Successful;
401 — Not Authorized;
404 — Not Found;
500 — Server error during operation.

3. Реализация (код на гитхабе тут):

Да, код, минимально комментировал, описание аннотаций тут.

Сами веб сервисы:

Всё достаточно просто — 4 веб сервиса в зависимости от URI и метода которым этот URI дёргается, есть объект DAO, который подключается в beans.xml и доступ к заголовкам запроса, чтобы доставать для примера кастомный заголовок «version».

Штука, которая отрабатывает перед тем как вызывается сервис:

Здесь в методе validate() можно проверять какие-то пред условия, чисто для теста добавлена проверка кастомного заголовка в запросе идентификатор сессии «ss_id», ну, и с первого раза даже с этим заголовком будет падать 401.

Общий обработчик exceptions:

Что-то уже многовато кода для поста, есть ещё вспомогательный класс для формирования ответа серверу и глобальный enum для хранения наших кодов ошибок. Да, дескриптор развёртывания и beans.xml всё таки приведу тут:

Тут основной интерес представляет подключение экшн сервлета от Apache — CXFServlet и стандартного спрингового ContextLoaderListener.

Здесь, собственно, задали нужные конфигурационные файлики для CXF, подключили DAO объект, наш предобработчик и обработчик исключительных ситуаций, конечно же, сам бин с сервисами и задали корень для сервисов.

Для того чтобы подёргать сервисы я использовал REST Console 4.0.2 плагин для хрома — штука достаточно простая, главное задать нужные ендпоинт, кастомные заголовки (как я уже говорил без «ss_id» всегда будет падать 401) и контент тип. Для примера:

Web Service Tutorial

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.

Читать еще:  Exception class java

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 :

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):

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.

Java Web Services Tutorial

Welcome to the Java Web Services Tutorial. Here we will learn about web services, useful concepts in web services and then different types of API we have in Java to create web services.

Table of Contents

What is a Web Service

In simple words, services that can be accessed over network are called web services. So how does it differ from web application, they are also services that are accessed over network. There are few attributes that clarifies this difference.

  • Web applications are meant for users and to be accessed in browser having human readable format whereas web services are meant for applications to access data in the format of XML, JSON etc.
  • Web applications always use HTTP/HTTPS protocol whereas traditional web services use SOAP protocol. Recently REST is getting popularity that is an architecture style and almost all times run on HTTP/HTTPS protocol.
  • Web applications are not meant for reusability whereas this is one of the benefit of web services. A single web service can be used by different kinds of applications.
  • Web application can access web services to access some data or to perform some tasks, web services can’t access web applications to fetch some data.
  • Web applications are capable to maintain user session, web services are stateless.
Читать еще:  Java web приложение

I hope above differences are good enough to clear any confusion with web applications and web services. Both are different concepts and meant for different purpose.

Types of Web Services

There are two types of web services.

  1. SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard protocol for designing and developing web services. Since it’s XML based, it’s platform and language independent. So our server can be based on JAVA and client can be on .NET, PHP etc. and vice versa.
  2. REST: REST is an architectural style for developing web services. It’s getting popularity recently because it has small learning curve when compared to SOAP. Resources are core concepts of Restful web services and they are uniquely >Java Web Services

Java provides it’s own API to create both SOAP as well as REST web services.

  1. JAX-WS: JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java API to build web services server and client application.
  2. JAX-RS: Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS uses annotations to simplify the development and deployment of web services.

Both of these APIs are part of standard JDK installation, so we don’t need to add any jars to work with them. Both of these APIs use annotations very heavily.

Hello World JAX-WS Application

Let’s create a very simple Hello World JAX-WS application.

That’s it. Just run this application and our Hello World JAX-WS SOAP web service is published. Below image shows the invocation of this JAX-WS web service through SOAP UI.

That’s it for a very basic tutorial of JAX-WS web service. Below are some of the articles you should read for better understanding of SOAP web services and JAX-WS.

Hello World JAX-RS Application

Jersey is the reference implementation of JAX-RS API, it’s not part of standard JDK and we have to include all the required jars. Best way is to use Maven build, so create a simple Dynamic web project and then convert it to Maven in Eclipse.

Here is the final pom.xml file having required dependencies.

Now add Jersey servlet to our deployment descriptor web.xml as front controller.

Above two steps are required for initial setup, below is our Hello World JAX-RS service class.

Just export it as WAR file and then access it in the browser as shown in below image.

You can change the last part of URL and returned message will change accordingly.

You can see how easy it was to create RESTful web service using JAX-RS API. However there is more to it, follow below articles to learn more.

That’s all for a quick introduction of java web services, finally if you are preparing for any interview then go through Web Services Interview Questions.

Web Services Interview Questions — SOAP, RESTful

Know what are the types of Java Web Services?

When you interact with any web page, it involves request and response through an HTML page. Similarly, web services also involve request and response, but in the form of XML or JSON. Java, being a suitable language for server-side communication, allows interoperability between different applications on different platforms. In this Java Web Services tutorial, I will give you a brief insight into different types of web services.

Below topics are covered in this article:

Let’s get started!

What is a Web Service?

Web service is an appropriate medium to propagate communication between the client and server applications on the World Wide Web. It is a software module which is designed to perform a certain set of tasks as follows:

The web services can be searched for over the network and can also be invoked accordingly.

When invoked the web service would be able to provide the functionality to the client which invokes that web service.

For Example, Flipkart provides a web service that provides prices for products sold online via flipkart.com. The front end or presentation layer can be in .Net or Java but either programming language would have the ability to communicate with the web service.

With this, let’s understand the advantages of using Web Services.

Advantages of Web Services

Below pointers depicts the various advantages of Web Services.

Exposing Business Functionality on the network – A web service is a managed code unit that provides some sort of functionality to client applications or end-users. This functionality can be invoked over the HTTP protocol which means that it can also be invoked over the internet. Web services can be used anywhere on the internet and provide the necessary functionality as required.

Interoperability amongst applications – Web services allow various applications to communicate with each other and share data and services among themselves.

A standardized Protocol which everybody understands – Web services use standardized industry protocol for the communication. All four layers (Service Transport, XML Messaging, Service Description, and Service Discovery layers) uses well-defined protocols in the web services protocol stack.

Reduction in cost of communication – Web services make use of SOAP over HTTP protocol, which lets you use your existing low-cost internet for implementing web services.

Now, let’s move further and understand the various types of web services that are used for communication on a day to day basis.

Types of Web Services

Generally, there are two types of web services as follows:

  1. Soap Web Services
  2. RESTful Web Services

Let’s get into the details of these web services.

1. Soap Web Services

Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML. Communication between the web service and the client happens using XML messages. A simple web service architecture has two component: viz. Client and Service provider.

In the above figure, you can notice how the client will communicate with the service provider. So in order to communicate, the client must know information like, the Location of web services server, Functions available, signature and return types of function and input-output formats. The service provider will create a standard XML file which will have all the above information. So, if this file is given to the client then it will be able to access web service.

So that’s how it works. Now let’s move further and understand what is RESTful web services.

2. RESTful Web Services

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 URLs. It consists of two components REST server which provides access to the resources and a REST client which accesses and modify the REST resources. Take a look at the below figure for the same.

In this REST architecture style, client and server exchange the representations of the resources by using a standardized interface and protocol. REST is not a specific protocol, but when people talk about REST they usually mean REST over HTTP. The response from the server is considered as the representation of the resources. This representation can be generated from one or more number of resources. RESTful web services use HTTP protocol methods for the operations they perform. It includes methods like GET, POST, DELETE, etc.

Now that you know what are SOAP and RESTful web services, let’s move further and see how actually it works with the help of an example.

Java Web Services API

There are two main API’s defined by Java for developing web service applications.

1. JAX-WS: It is mainly for SOAP web services. There are two ways to write JAX-WS application code: by RPC style and Document style.

2. JAX-RS: It is mainly for RESTful web services. There is mainly 2 implementation currently in use for creating JAX-RS application: Jersey and RESTeasy.

Both of these Java APIs are part of standard JDK Installation, so you need not add any jars to work with them. Now, let’s get into the details of these APIs and understand how it works.

JAX-WS Example

Let’s create a simple Hello World JAX-WS application. Here, I will create a simple class file called Demo.java and write the program as shown below to display a simple message.

You can just run this application and the message of JAX-WS SOAP web service is published. That’s how you need to code a simple JAX-WS application.

Now let’s understand one more API of Java Web Services i.e. JAX-RS.

JAX-RS Example

Jersey is the reference implementation of JAX-RS API, it’s not part of standard JDK and you have to include all the required jars. The best way is to use Maven build, so create a simple Dynamic web project and then convert it to Maven in Eclipse.

In order to create a JAX-RS application, you need to follow the below-mentioned steps.

Step 1: Add the dependencies to pom.xml file as shown below:

Step 2: Now, the next step is to add Jersey servlet to our deployment descriptor web.xml as a front controller.

Step 3: After all that, now let’s create a simple JAX-RS service class.

After configuring the above file, you just have to export it as a WAR file and then access it in the browser. You will get the output as shown below .

Congratulations!

This brings us to the end of the article on Java Web Services. I hope I have thrown some light and added your knowledge on Web Services fundamentals.

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.

Got a question for us? Please mention it in the comments section of this Java Web Services tutorial and we will get back to you as soon as possible.

Ссылка на основную публикацию
Adblock
detector