How to create web service client in a .jsp page?

vikram picture vikram · Apr 10, 2010 · Viewed 27.2k times · Source

I have created a WSDL for my web service. I would like to know how to call it from a jsp page from my another web application.

I would like to call the web service from the jsp.. for example considering i have very simple web service which would display back the text entered in my index.jsp page after clicking submit, how would I use the wsdl url to call the web service taking the text value when clicked submit.

/vikram

Answer

Pascal Thivent picture Pascal Thivent · Apr 10, 2010

I really do not recommend coding any kind of logic in a JSP, including calling a web service, this is not a good practice. JSP is a view technology and should be used for the presentation, not for business logic. Instead, you should submit the form to a Servlet, retrieve the submitted parameters, call the web service and then print the results in a JSP view. But let's close the parenthesis.

Since you mentioned WebLogic and Workshop in a comment, I'll assume you're using them :) WebLogic supports JAX-WS so I suggest using it for your client.

Basically, you need to generate the "client artifacts" first (i.e. the classes that you'll use to invoke the web service). One way to do this is to use the clientgen Ant task. Refer to Invoking a Web Service from a Stand-alone Client: Main Steps for details (it should be possible to generate the classes from Workshop but I can't tell you how, I don't use it).

Once the client artifacts generated, calling the web service is a piece of cake. The code will be similar to the following:

ComplexService test = new ComplexService(), 
ComplexPortType port = test.getComplexPortTypePort();

BasicStruct in = new BasicStruct();

in.setIntValue(999);
in.setStringValue("Hello Struct");

BasicStruct result = port.echoComplexType(in);
System.out.println("echoComplexType called. Result: " + result.getIntValue() + ", " + result.getStringValue());