Você está na página 1de 12

Getting Started with JAX-WS Web Services

Java API for XML Web Services (JAX-WS), JSR 224, is an important part of the Java EE platform. A follow-up to the
release of Java API for XML-based RPC 1.1(JAX-RPC), JAX-WS simplifies the task of developing web services using
Java technology. It addresses some of the issues in JAX-RPC 1.1 by providing support for multiple protocols such as
SOAP 1.1, SOAP 1.2, XML, and by providing a facility for supporting additional protocols along with HTTP. JAX-WS
uses JAXB 2.0 for data binding and supports customizations to control generated service endpoint interfaces. With its
support for annotations, JAX-WS simplifies web service development and reduces the size of runtime JAR files.
This document demonstrates the basics of using the IDE to develop a JAX-WS web service. After you create the web
service, you write three different web service clients that use the web service over a network, which is called
"consuming" a web service.

To follow this tutorial, you need the following software and resources.

Software or Resource

Version Required

NetBeans IDE

Java EE download bundle

Java Development Kit (JDK)

JDK 7 or JDK 8

Java EE-compliant web or application server Tomcat Server

Enabling Access to External Schema


You need to enable the IDE and the Tomcat Server to access external schema to parse the WSDL file of the web
service. To enable access you need to modify the configuration files of the IDE and the Tomcat Server.

Configuring the IDE


To generate a web service client in the IDE from a web service or WSDL file you need to modify the IDE configuration
file (netbeans.conf) to add the following switch to netbeans_default_options.

-J-Djavax.xml.accessExternalSchema=all
For more about locating and modifying the netbeans.conf configuration file, see Netbeans Conf FAQ.

Creating a Web Service


The goal of this exercise is to create a project appropriate to the deployment container that you decide to use. Once
you have a project, you will create a web service in it.

Choosing a Container
You can either deploy your web service in a web container or in an EJB container. This depends on your choice of
implementation. If you are creating a Java EE application, use a web container in any case, because you can put
EJBs directly in a web application. For example, if you plan to deploy to the Tomcat Web Server, which only has a
web container, create a web application, not an EJB module.
1. Choose File > New Project (Ctrl-Shift-N on Linux and Windows, -Shift-N on MacOS). Select Web
Application from the Java Web category or EJB Module from the Java EE category.

Note. You can create a JAX-WS web service in a Maven project. Choose File > New Project (Ctrl-Shift-N on
Linux and Windows, -Shift-N on MacOS) and then Maven Web Application or Maven EJB module from the
Maven category. If you haven't used Maven with NetBeans before, see Maven Best Practices.
2.

Name the project SOAPWebService. Select a location for the project. Click Next.

3.

Select your server and Java EE version and click Finish.

Creating a Web Service from a Java Class


1.

Right-click the SOAPWebService node and choose New > Web Service.

2.

Name the web service PatientRepository and type com.code.util in Package. Leave Create
Web Service from Scratch selected.

3.

If you are creating a Java EE project on GlassFish or WebLogic, select Implement Web Service as a
Stateless Session Bean.

4.

Click Finish. The Projects window displays the structure of the new web service and the source code is
shown in the editor area.

Adding an Operation to the Web Service


The goal of this exercise is to add to the web service an operation that adds two numbers received from a client. The
NetBeans IDE provides a dialog for adding an operation to a web service. You can open this dialog either in the web
service visual designer or in the web service context menu.
Warning: The visual designer is not available in Maven projects.
To add an operation to the web service:
1.

Either:

Change to the Design view in the editor.


Or:

Find the web service's node in the Projects window. Right-click that node. A context menu opens.

2.

Click Add Operation in either the visual designer or the context menu. The Add Operation dialog opens.

3.

In the upper part of the Add Operation dialog box, type save and type getByName in Name and
type Patient in the Return Type drop-down list.

4. In the lower part of the Add Operation dialog box, click Add and create a parameter of type Patient
named p.
5.

Click Source and view the code that you generated in the previous steps. It differs whether you created the
service as an Java EE stateless bean or not. Can you see the difference in the screenshots below? (A Java
EE 6 or Java EE 7 service that is not implemented as a stateless bean resembles a Java EE 5 service.)

* To change this template, choose Tools | Templates


* and open the template in the editor.
*/
package com.code.util;
import
import
import
import
import
import
import
import
import
import

com.code.model.Patient;
java.sql.Connection;
java.sql.PreparedStatement;
java.sql.ResultSet;
java.sql.SQLException;
java.util.ArrayList;
java.util.List;
javax.jws.WebMethod;
javax.jws.WebParam;
javax.jws.WebService;

/**
*
* @author
*/
@WebService
public class PatientRepository {
private DBManager dBManager = new DBManager();
@WebMethod(operationName = "save")
public void savePatient(@WebParam Patient p) {
try {
Connection con = dBManager.getConnection();
String SQL = "INSERT INTO patient(name,age,history) values(?,?,?)";
PreparedStatement pstmt = con.prepareStatement(SQL);
pstmt.setString(1, p.getName());
pstmt.setInt(2, p.getAge());
pstmt.setString(3, p.getHistory());
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
@WebMethod(operationName = "getByName")
public Patient findByName(@WebParam(name = "name") String name) {
Patient pt = null;
try {
String QRY = "SELECT * FROM patient WHERE name=?";
Connection con = dBManager.getConnection();
PreparedStatement pstmt = con.prepareStatement(QRY);
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
pt=new Patient();
pt.setId(rs.getInt("id"));
pt.setHistory(rs.getString("history"));
pt.setAge(rs.getInt("age"));
pt.setName(rs.getString("name"));
}
pstmt.close();
} catch (SQLException se) {
System.out.println(se);
}
return pt;
}

Note. In NetBeans IDE 7.3 and 7.4 you will notice that in the generated @WebService annotation the service name
is specified explicitly:
@WebService(serviceName = "save").

As you can see from the preceding code, the web service simply receives two numbers and then returns their sum. In
the next section, you use the IDE to test the web service.

Deploying and Testing the Web Service


After you deploy a web service to a server, you can use the IDE to open the server's test client, if the server has a
test client. The GlassFish and WebLogic servers provide test clients.
If you are using the Tomcat Web Server, there is no test client. You can only run the project and see if the Tomcat
Web Services page opens. In this case, before you run the project, you need to make the web service the entry point
to your application. To make the web service the entry point to your application, right-click the SOAPWebService
project node and choose Properties. Open the Run properties and type /PatientRepository in the Relative
URL field. Click OK. To run the project, right-click the project node again and select Run.
To test successful deployment to a GlassFish or WebLogic server:
1.

Right-click the project and choose Deploy. The IDE starts the application server, builds the application, and
deploys the application to the server. You can follow the progress of these operations in the
SOAPWebService (run-deploy) and the GlassFish server or Tomcat tabs in the Output view.

2.

In the IDE's Projects tab, expand the Web Services node of the SOAPWebService project. Right-click the
PatientRepository node, and choose Test Web Service.

The IDE opens the tester page in your browser, if you deployed a web application to the GlassFish server.
For the Tomcat Web Server and deployment of EJB modules, the situation is different:

Samples
You can open a complete Java EE stateless bean version of the SOAPWebService service by choosing File >
New Project (Ctrl-Shift-N on Linux and Windows, -Shift-N on MacOS) and navigating to Samples > Web Services >

SOAPWebService (EE6).
A Maven Calculator Service and a Maven WebServiceClient are available in Samples > Maven.

Consuming the Web Service


After you deploy the Project before, you can use a web service over a network, which is called "consuming" a web
service, you need to create a web service client. For the creation of web service clients, NetBeans IDE provides a
client creation facility, which is the Web Service Client wizard that generates code for looking up a web service. It also
provides facilities for developing the created web service client, a work area consisting of nodes in the Projects
window. These facilities are part of the EE bundle of the NetBeans IDE installation. They are available straight out of
the box and no plug-ins are needed.

Creating the Client


In this section, you use a wizard to generate Java objects from the web service's WSDL file.
1. Choose File > New Project (Ctrl-Shift-N on Windows and Linux, -Shift-N on MacOS). Under Categories,
choose Java Web. Under Projects, choose Web Application. Click Next. Name the
project WebServiceClient and make sure that you specify an appropriate server as your target server.
Leave all other options at default and click Finish.

2.

In the Projects window, right-click the WebServiceClient project node and choose New > Other and
select Web Service Client in the Web Services category in the New File wizard. Click Next.

3.

Select WSDL URL and specify the following URL for the web service:
http://localhost:8080/ SOAPWebService/PatientRepository?wsdl
If you are behind a firewall, you might need to specify a proxy serverotherwise the WSDL file cannot be
downloaded. To specify the proxy server, click Set Proxy in the wizard. The IDE's Options window opens,
where you can set the proxy universally for the IDE.

4.

Leave the package name blank. By default the client class package name is taken from the WSDL. In this
case iscom.code.utility. Click Finish.

5.

In the Projects window, within the Web Service References node.

The Projects window shows that a web service called patientRepository has made a number of

save and getByName operations available to your application.


Within the Generated Sources node, you see the client stubs that were generated by the JAX-WS
Web Service Client wizard.
The URL of the WSDL that you used to create the client is mapped to the local copy of the WSDL in jax-

ws-catalog.xml. Mapping to a local copy has several advantages. The remote copy of the WSDL does
not have to be available for the client to run. The client is faster, because it does not need to parse a remote
WSDL file. Lastly, portability is easier.

Developing the Client


There are many ways to implement a web service client. The web service's WSDL file restricts the type of information
that you can send to the web service, and it restricts the type of information you receive in return. However, the
WSDL file lays no restrictions on how you pass the information it needs, nor on what the user interface consists of.
The client implementation you build below consists of a web page which allows the user to enter text to be checked
and a servlet which passes the text to the web service and then produces a report containing the result.

Coding the Web Page


The web page will consist of a text area, where the user will enter text, and a button for sending the text to the web
service. Depending on the version of the server that you chose as the target server, the IDE generated
either index.html or index.jsp as the index page for the application.
1.

In the Projects window, expand the Web Pages node of the WebServiceClient project and double-click
the index page (index.html or index.jsp) to open the file in the Source Editor.

2.

Create the following code in the index page:

<%-Document : index
Created on : Dec 25, 2014, 9:41:28 PM
Author :
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>JSP Page</title>
<script>
$(document).ready(function() {
$('#message-button').click(function() {
var name = $('#patient').val();
$.get('/WebServiceClient/MyServlet?patient=' + name, function(responseText) {
$('#message').empty().append(responseText);
});
});
});
</script>
</head>
<body>
Patient Name : <input id="patient" type="text" />
<button id="message-button">Search</button><br> <!-- Ajax call initiates once this button is clicked -->
<a href="add.jsp">Add New Patient</a>
<div id="message">
</div>
</body>
</html>
The previously listed code specifies that when the submit button is clicked, the content of the <div

id=message></div> is posted to MyServlet with ajax in method GET and return your data from
database with web service in your servlet.
3.

Create the file with named add.jsp, and create the following code in the add page:

<%-Document
: add
Created on : Dec 26, 2014, 10:29:31 AM
Author
:
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
if (request.getAttribute("status") != null) {
out.print(request.getAttribute("status").toString()+"<br>");
}
%>
<form action="MyServlet" method="post">
<table>
<tr>
<td>
Patient Name

</td>
<td>
<input type="text" name="namee"/>
</td>
</tr>
<tr>
<td>
Patient Age
</td>
<td>
<input type="text" name="age"/>
</td>
</tr>
<tr>
<td>
Medical History
</td>
<td>
<textarea name="history"></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td>
<button type="submit">Save</button>
<button type="reset">Clear</button>
</td>
</tr>
</table>
</form>
</body>
</html>

The previously listed code specifies that when the submit button is clicked, the content of the form will send to
MyServlet in method POST and it will be saved to database with web service in servlet.

Creating and Coding the Servlet


In this section you create a servlet that will interact with the web service. However, the code that performs the
interaction will be provided by the IDE. As a result, you only need to deal with the business logic, that is, the
preparation of the text to be sent and the processing of the result.
1. Right-click the WebServiceClient project node in the Projects window, choose New > Other and then
choose Web > Servlet. Click Next to open the New Servlet wizard.
2.

Name the servlet MyServlet and type clientservlet in the Package drop-down. Click Next.

3.

In the Configure Servlet Deployment panel, note that the URL mapping for this servlet is /MyServlet.
Accept the defaults and click Finish. The servlet opens in the Source Editor.

4.

Put your cursor inside the Source Editor, inside the get method body of MyServlet.java, and add
some new lines right at the top of the method.

5.

Right-click in the space that you created in the previous step, and choose Insert Code > Call Web Service
Operation. Click the PatientRepository.getByName operation in the "Select Operation to Invoke"
dialog box and click OK.

Note: You can also drag and drop the operation node directly from the Projects window into the editor, instead of
calling up the dialog.
At the end of the MyServlet class, you see a private method for calling the getByName service and returning

com.code.model.Patient object .
private static Patient getByName(java.lang.String name) {
com.code.servlet.PatientRepositoryService service = new
com.code.servlet.PatientRepositoryService();
com.code.servlet.PatientRepository port =
service.getPatientRepositoryPort();
return port.getByName(name);
}
6.

Put your cursor inside the Source Editor, inside the post method body of MyServlet.java, and add
some new lines right at the top of the method.

7.

Right-click in the space that you created in the previous step, and choose Insert Code > Call Web Service
Operation. Click the PatientRepository.save operation in the "Select Operation to Invoke" dialog
box and click OK.

Note: You can also drag and drop the operation node directly from the Projects window into the editor, instead of
calling up the dialog.
At the end of the MyServlet class, you see a private method for calling the save service for save your object to
database.

private static void save(com.code.servlet.Patient arg0) {


com.code.servlet.PatientRepositoryService service = new
com.code.servlet.PatientRepositoryService();
com.code.servlet.PatientRepository port =
service.getPatientRepositoryPort();
port.save(arg0);
}
}
8.

And finally, this is a code for your servlet. The in-line comments throughout the code below explain the
purpose of each line.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.code.servlet;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

java.io.IOException;
java.io.PrintWriter;
javax.servlet.ServletException;
javax.servlet.annotation.WebServlet;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.xml.namespace.QName;
javax.xml.transform.Source;
javax.xml.ws.Dispatch;
javax.xml.transform.stream.StreamSource;
javax.xml.ws.Service;
java.io.StringReader;
java.sql.SQLException;
java.util.List;

/**
*
* @author
*/
@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet MyServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet MyServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on
the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response header
response.setContentType("text/html;UTF-8");
// Set response body content. response body is returned as Ajax Response Text
String name = request.getParameter("patient");
Patient p = getByName(name);//get patient object with getByNameService
String ajax = "";
PrintWriter writer = response.getWriter();//create object PrinWriter for ajax
if (p != null) {
ajax = "<hr>"
+ "Patient Name
: " + p.getName() + "<br>"
+ "Patient Age
: " + p.getAge() + "<br>"
+ "Medical History : " + p.getHistory() + "<br>"
+ "<hr>";
} else {
ajax = "<hr>Patient not found!<hr>";
}
writer.write(ajax);

writer.close();
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("namee");
Integer age = Integer.parseInt(request.getParameter("age"));
String history = request.getParameter("history");
Patient p = new Patient();
p.setAge(age);
p.setHistory(history);
p.setName(name);
try {
save(p);//save object to your database with save service
response.sendRedirect("/WebServiceClient");//if saved is success, file will redirect
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("status", "Save patient failed!");
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
//this is a service from WSDL
private static Patient getByName(java.lang.String name) {
com.code.servlet.PatientRepositoryService service = new
com.code.servlet.PatientRepositoryService();
com.code.servlet.PatientRepository port = service.getPatientRepositoryPort();
return port.getByName(name);
}
private static void save(com.code.servlet.Patient arg0) {
com.code.servlet.PatientRepositoryService service = new
com.code.servlet.PatientRepositoryService();
com.code.servlet.PatientRepository port = service.getPatientRepositoryPort();
port.save(arg0);
}
}

Deploying the Client


The IDE uses an Ant build script to build and run your application. The IDE generates the build script based on the
options you entered when creating the project. You can fine tune these options in the project's Project Properties
dialog box (right-click the project node in the Projects window and choose Properties).
1.

Right-click the project node and choose Run. After a while, the application deploys and displays the web
page that you coded in the previous section.

2.

Enter some text in textfield and click search for searching medical history of patient in database.

3.

If the patient not found in database, page will displayed not found alert, you can create new patient with add
new patient link.

4.

Create new patient data for save the medical history of patient:

If you have finished insert patient data, click the save button for saving medical history of patient to
database.

Asynchronous Web Service Clients


By default, JAX-WS clients created by the NetBeans IDE are synchronous. Synchronous clients invoke a request on
a service and then suspend their processing while they wait for a response. However, in some cases you want the
client to continue with some other processing rather than wait for the response. For example, in some cases it may
take a significant amount of time for the service to process the request. Web service clients that continue processing
without waiting for the service response are called "asynchronous".
Asynchronous clients initiate a request to a service and then resume their processing without waiting for a response.
The service handles the client request and returns a response at some later point, at which time the client retrieves
the response and proceeds with its processing.
Asynchronous clients consume web services either through the "polling" approach or the "callback" approach. In the
"polling" approach, you invoke a web service method and repeatedly ask for the result. Polling is a blocking operation
because it blocks the calling thread, which is why you do not want to use it in a GUI application. In the "callback"
approach you pass a callback handler during the web service method invocation. The
handler's handleResponse() method is called when the result is available. This approach is suitable to GUI
applications because you do not have to wait for the response. For example, you make a call from a GUI event
handler and return control immediately, keeping the user interface responsive. The drawback of the polling approach
is that, even though the response is consumed after it is caught, you have to poll for it to find out that it has been
caught.
In NetBeans IDE, you add support for asynchronous clients to a web service client application by ticking a box in the
Edit Web Service Attributes GUI of the web service references. All other aspects of developing the client are the
same as for synchronous clients, except for the presence of methods to poll the web service or pass a callback
handler and await the result.

Você também pode gostar