Escolar Documentos
Profissional Documentos
Cultura Documentos
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
JDK 7 or JDK 8
-J-Djavax.xml.accessExternalSchema=all
For more about locating and modifying the netbeans.conf configuration file, see Netbeans Conf FAQ.
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.
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.
Either:
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.)
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.
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.
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.
The Projects window shows that a web service called patientRepository has made a number of
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.
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.
<%-Document : index
Created on : Dec 25, 2014, 9:41:28 PM
Author :
--%>
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.
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.
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);
}
}
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.