JAX-WS + Tomcat Example

JAX-WS Web integration

In previous examples we done the JAX-WS simple example with publisher and client. In this example we are going to integrate JAX-WS with web application and one web application client. One of our previous example we done this same stuff which is using Apache Axis api.

Goals

1. Create a web application which publish web services
2. Create a web application client

Software used

1. Eclipse
2. Java 1.7
3. JAX-WS API
4. Tomcat service
5. JAX-WS RI

1. Create a web application which publish web service

In this example we are using Eclipse so create a new dynamic web project from file new and create a web service class which define our example function (Web service to get State name upon passing state code)

package com.pretech;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class StateProvider {
    @WebMethod
    public String getStateName(String name) {

        String stateName = null;
        if (name.equals("KL")) {
            stateName = "KERALA";
        }
        if (name.equals("KA")) {
            stateName = "KARNATAKA";
        }
        return stateName;
    }

}
 

2.Add JAX-WS RI libraries into WEB-INF/lib folder

Download JAX-WS RI jars from https://jax-ws.java.net/2.2.8/  and place into WEB-INF/lib folder

3. Create sun-jaxws.xml file and place in to WEB-INF directory

<?xml version="1.0" encoding="UTF-8"?>
<endpoints
 xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
 version="2.0">
  <endpoint
     name="StateWs"
     implementation="com.pretech.StateProvider"
     url-pattern="/state"/>
</endpoints>

4. Modify web.xml file (Add web service context listener and servlet)

<listener>
    <listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>
com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

5. Deploy Web application in tomcat server and check the wsdl file

Once the server started check our wsdl file using below url http://localhost:8080/JAXWS-Tomcat-Publisher/state?wsdl

Create a web application client

1.Generate artifacts

Use wsimport tool and generate artifacts, use below command to generate client required artifacts

wsimport -d . -keep http://localhost:8080/JAXWS-Tomcat-Publisher/state?wsdl

2.Create a Client Web application

Create a new web application project and copy all artifacts in to web application source folder

image

3.Create a jsp page to consume web service

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
    <%@ page import="com.pretech.*" %>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>

        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>State Consumer Example</title>
        </head>

        <body>
            <%

StateProviderService service = new StateProviderService();
StateProvider hservice=service.getStateProviderPort();
if(request.getParameter("code")!=null)
{
String code=request.getParameter("code");
if(!code.equals(""))
{
out.println(hservice.getStateName(code));
}
}
%>
                <form action="/JAX-WS-Tomcat-Client/StateConsumer.jsp" method="get">
                    Enter state code
                    <input type="text" name="code">
                    <input type="submit" value="submit">

                </form>

        </body>

        </html>

4. Deploy application and hit the consumer


The role of elements in WSDL

Elements in WSDL

Here are the major elements of Web service Description Language (WSDL)

  1. <definitions> = Root WSDL Elements
  2. <types> = What data type will be transmitted?
  3. <message> = What exact information is expected
  4. <portType> = What operations will be supported
  5. <binding> = How will the message will be transmitted on the wire ? What SOAP specific details are there
  6. <service> = Define the collection of ports that make up the services and where is service located.
See more about WSDL

Reference WIKI

JAX-WS Web services Example

JAX-WS stands for Java API for XML Web Services. JAX-WS is a technology for building web services and clients that communicate using XML. JAX-WS allows developers to write message-oriented as well as RPC-oriented web services.
See more about JAX-WS

Steps

1. Create a Java class to implementing Web service method
2. Create a Java class to Publish Web services
3. Start Web service
4. Check the generated WSDL
5. Use wsimport tool to generate web service artifacts needed to connect to the service.
6. Create a client class to call web services

1. Create a Java class to implement Web service

package com.pretech;

import javax.jws.WebService;

@WebService
public class StateWebService {

    public String getState(String statecode) {
        String stateName;
        if (statecode.equals("KL")) {
            stateName = "Kerala";
        } else {
            stateName = "Not avaiable";
        }

        return stateName;
    }
}

2. Create a Java class to publish Web service

package com.pretech;

import javax.xml.ws.Endpoint;

public class StateWebServicePublisher {

    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/pretech/StateProvider",
                new StateWebService());
    }

}

3. Run the publisher class (StateWebServicePublisher.java)

Run the above program which we exposed the end point.

4. Check the WSDL


image 

WSDL

The Web Services Description Language is an XML-based interface definition language that is used for describing the functionality offered by a web service.
Below are the elements of a WSDL file
  • <definitions> = Root WSDL Elements
  • <types> = What data type will be transmitted?
  • <message> = What exact information is expected
  • <portType> = What operations will be supported
  • <binding> = How will the message will be transmitted on the wire ? What SOAP specific details are there
  • <service> = Define the collection of ports that make up the services and where is service located.

WSDL SOAP Binding

a WSDL SOAP binding can be either a Remote Procedure Call (RPC) style binding or a document style binding. see more about bindings here http://www.ibm.com/developerworks/library/ws-whichwsdl/
 To specify particular binding we can use the annotations over the service class as below
@WebService
@SOAPBinding(style = Style.RPC)
public class StateWebService {
   
}
Now we completed the service implementation and started the service, next we need to create the client for the service using the WSDL.

5. Generate web service artifacts needed to connect the service

1. Use command prompt and go to Java bin directory
2. Use wsimport tool to generate web service artifacts ,please see the below command 
    wsimport -d . -keep http://localhost:8080/pretech/StateProvider?wsdl
image
3. We can see the artifacts has been generated in bin\com folder
image 

6. Create a Java client to use web services

1. Create a new project and copy all the files which we generated from the previous step
2. Create a Java client to use web services
package com.pretech;
public class StateWebClient {
  public static void main(String[] args) {
        StateWebServiceService service=new StateWebServiceService();
        StateWebService ss=service.getStateWebServicePort();
        System.out.println(ss.getState("KL"));
    }
}

7.Output


Kerala
Download Source code JAX-WS-Example

JAX-RS @Path Regex based URI matching Example

Restful Web service

Representational State Transfer

REST is an architectural style which is based on web-standards and the HTTP protocol.

see more details in Wikipedia

HTTP Methods

The PUT, GET, POST and DELETE methods are typical used in REST based architectures.

see more details in Wikipedia

Java Restful Implementations

See more details Wikipedia

JAX-RS @Path Regex based URI

In complex form, we can use regular expression based parameter matching.

e.g. @Path("/{param: [0-9]+}")

In this case the web service method will accept only the number parameter, see the below example

Example

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
 
@Path("/statepatternparam")
public class PathPatternExample {
   @GET
    @Produces("application/xml")
    @Path("/{param: [0-9]+}")
    public String getMsg(@PathParam("param") String state) {
 
        String stateDetails = null;
 
        if (state.equals("13")) {
 
            stateDetails = "<State><name>KERALA</name><shortname>KL</shortname>"
                    +
 
                    "<headq>TRIVANDRUM</headq><language>MALAYALAM</language></State>";
 
        } else {
 
            stateDetails = "Data not found";
 
        }
 
        return stateDetails;
 
    }
}

 

RestFul Webservices @QueryParam Example

JAX-RS Binding values to method parameters

To call any service we need to bind the request to the resource method, in order to bind this JAX-RS has provided few parameter types, the data will be taken from these parameters by using the annotaions. Whenever JAX-RS provider receives an http request, it finds an appropriate java method  that can service this request.
Here are the parameters provided by JAX-RS API
  1. Query parameters
  2. URI path parameters
  3. Header parameters
  4. Form parameters
  5. Cookie parameters
  6. Matrix parameters
  7. Bean Parameters
In this example we will see how to use all these parameters.

1. Create a maven project using the quick start archetype and add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
2. Create a simple service which uses all these params
package com.vinod.vinod_rest_examples;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("/DataBinding")

public class DataBinding {

/**
*http://localhost:8080/DataBinding/queryParam?name=vinod
*
*@param name
*@return
*/
@GET
@Path("queryParam")
@Produces(MediaType.APPLICATION_JSON)
public String queryParam(@QueryParam("name") String name) {
return "Hello world " + name;
}

/**
*http://localhost:8080/DataBinding/vinod/pathParam
*
*@param name
*@return
*/
@GET
@Path("{name}/pathParam")
@Produces(MediaType.APPLICATION_JSON)
public String pathParam(@PathParam("name") String name) {
return "Hello world " + name;
}

/**
*http://localhost:8080/DataBinding/headerParam
*
*@param userAgent
*@return
*/
@Path("headerParam")
@GET
@Produces(MediaType.APPLICATION_JSON)

public String headerParam(@HeaderParam("user-agent") String userAgent) {
return "Hello world " + userAgent;
}

/**
*http://localhost:8080/DataBinding/matrixParam;name=vinod;address=
* bangalore
*
*@param name
*@param address
*@return
*/
@Path("matrixParam")
@GET
@Produces(MediaType.APPLICATION_JSON)

public String matrixParam(@MatrixParam("name") String name, @MatrixParam("address") String address) {
return "Hello world " + name + " " + address;
}

/**
*http://localhost:8080/DataBinding/formParam pass the name in the form
* request
*
*@param name
*@return
*/
@Path("formParam")
@POST
public String formParam(@FormParam("name") String name) {
return "Hello world " + name;
}
}
3. Create a java class to start jetty server
package com.vinod.vinod_rest_examples;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

/**
 * Hello world!
 *
 */
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

Server jettyServer = new Server(8080);
jettyServer.setHandler(context);

ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);

// Setting pacakge name over here to load services
jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
"com.vinod.vinod_rest_examples");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
4. Hit the urls for testing

http://localhost:8080/DataBinding/queryParam?name=vinod
http://localhost:8080/DataBinding/vinod/pathParam
http://localhost:8080/DataBinding/headerParam
http://localhost:8080/DataBinding/matrixParam;name=vinod;address=bangalore
http://localhost:8080/DataBinding/formParam pass the name in the form
 
Download this example!! https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-rest-examples 

JAX-RS Multiple @PathParam example

JAX-RS @PathParam Example

To call any service we need to bind the request to the resource method, in order to bind this JAX-RS has provided few parameter types, the data will be taken from these parameters by using the annotaions. Whenever JAX-RS provider receives an http request, it finds an appropriate java method  that can service this request.
Here are the parameters provided by JAX-RS API
  1. Query parameters
  2. URI path parameters
  3. Header parameters
  4. Form parameters
  5. Cookie parameters
  6. Matrix parameters
  7. Bean Parameters
In this example we will see how to use multiple path params for a single call

1. Create a maven project using the quick start archetype and add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>

2. Create a simple service which uses all these params

package com.vinod.vinod_rest_examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/statedetails")
public class PathParamExample {
    // http://localhost:8080/statedetails/India/KL
    @GET
    @Path("{country}/{state}")
    @Produces("application/xml")
    public Response getMsg(@PathParam("country") String country, @PathParam("state") String state) {
        String stateDetails = null;
        if (country.equals("India") & state.equals("KL")) {
            stateDetails = "<State><name>KERALA</name><shortname>KL</shortname>"
                    + "<headq>TRIVANDRUM</headq><language>MALAYALAM</language></State>";
        } else {
            stateDetails = "Data not found";
        }
        return Response.ok().entity(stateDetails).build();
    }
}

3. Create a java class to start jetty server
package com.vinod.vinod_rest_examples;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

/**
 * Hello world!
 *
 */
public class App {
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

Server jettyServer = new Server(8080);
jettyServer.setHandler(context);

ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);

// Setting pacakge name over here to load services
jerseyServlet.setInitParameter("jersey.config.server.provider.packages",
"com.vinod.vinod_rest_examples");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
4. Hit the urls for testing

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts