利用 axis 访问webservice有两种实现方式:
1. parse -> call -> return obj -> extract
2. generate stub by wsdl2java, then uses the stub to access service.
?
下面介绍用第2种方式做一个web project:
1. install myeclipse (myeclipse 5.0 + eclipse 3.2)
2. create a web project named axis
3. create a generator to convert wsdl to stubs
?
package generator; import java.util.List; import org.apache.axis.utils.CLArgsParser; import org.apache.axis.utils.CLOption; import org.apache.axis.wsdl.WSDL2Java; public class wsdl2java { public static void main(String args[]) { args = new String[] { "http://www.deeptraining.com/webservices/weather.asmx?WSDL" }; new MyWSDL2Java().generateWSDL(args); } static class MyWSDL2Java extends WSDL2Java { public void generateWSDL(String[] args) { org.apache.axis.utils.CLArgsParser argsParser = new CLArgsParser( args, org.apache.axis.wsdl.WSDL2Java.options); List<CLOption> clOptions = argsParser.getArguments(); for (int i = 0; i < clOptions.size(); i++) { parseOption(clOptions.get(i)); } validateOptions(); try { parser.run(wsdlURI); } catch (Exception e) { e.printStackTrace(); } } } }?
run above program, stub will be generted. they are all in the package com.litwinconsulting.webservices
?
4. create business classes
package business; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; import com.litwinconsulting.webservices.WeatherLocator; import com.litwinconsulting.webservices.WeatherSoap; /** * call stub to communicate with weather service. * @author tychu */ public class WSWeather { public String getWeatherByCity(String city) throws ServiceException, RemoteException { WeatherLocator locator = new WeatherLocator(); WeatherSoap service = locator.getWeatherSoap12(); return service.getWeather(city); } }?
package business; public class ManagefacedImp implements IManageFaced { // invoked to create implementation object. public WSWeather getWeatherManage() { return new WSWeather(); } }?
package business; /** * all interface of providing services * @author tychu */ public interface IManageFaced { // get weather service public WSWeather getWeatherManage(); }?
5. create filter and servlet
?
?
package servlet; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.log4j.Logger; /** * uses filter to avoid to specify charset in every servlets * @author tychu */ public class CharacterFilter implements Filter { protected String encoding = null; protected FilterConfig filterConfig = null; protected boolean ignore = true; public void init(FilterConfig fConfig) throws ServletException { this.filterConfig = fConfig; this.encoding = fConfig.getInitParameter("encoding"); String value = fConfig.getInitParameter("ignore"); if (value == null || "true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)) this.ignore = true; else this.ignore = false; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Logger log = Logger.getLogger(CharacterFilter.class); if (ignore || (request.getCharacterEncoding() == null)) { if (encoding != null) { request.setCharacterEncoding(encoding); log.info("filter used!!!"); } } response.setContentType("text/html; charset=" + encoding); chain.doFilter(request, response); } public void destroy() { // do nothing } }?
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.rpc.ServiceException; import org.apache.log4j.Logger; import business.ManagefacedImp; import business.WSWeather; /** * servlet invokes bussiness interface * @author tychu */ public class InvokeWS extends HttpServlet { private static final long serialVersionUID = 1646431374969L; Logger logger = Logger.getLogger(InvokeWS.class.getName()); public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // PropertyConfigurator.configure("log4j.properties"); WSWeather wsw = new ManagefacedImp().getWeatherManage(); PrintWriter pw = resp.getWriter(); String city = req.getParameter("city"); // if no filter set, you will get some unrecognized characters here // logger.info("city:" + city); if (city != null && city.length() != 0) { String weatherinfo; try { weatherinfo = wsw.getWeatherByCity(city); pw.println("<font size='2' color='blue'>" + weatherinfo + "</font><br>"); } catch (ServiceException e) { e.printStackTrace(); } } else { pw.println("<font size='2' color='blue'>" + "the specified city not exists, please contact:********" + "</font><br>"); } } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }?
6. add servlet and filter to web.xml
?
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <filter> <filter-name>SetCharacterEncodingFilter</filter-name> <filter-class> servlet.CharacterFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> <init-param> <param-name>ignore</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>SetCharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>InvokeWS</servlet-name> <servlet-class>servlet.InvokeWS</servlet-class> </servlet> <servlet-mapping> <servlet-name>InvokeWS</servlet-name> <url-pattern>/invoke</url-pattern> </servlet-mapping> </web-app>?
7. web pages
?
index.htm <html> <head> <title>WebService weather</title> </head> <frameset rows="5%,*%" Borders="No" border="0"> <frame src="top.htm" noresize="false" name="top" frameborder="0"> <frame src="bottom.htm" noresize="true" name="bottom" frameborder="0"> </frameset> </html>?
top.htm <html> <head> <title>weather</title> <meta http-equiv="content-type" content="text/html; charset=gb2312"> </head> <body> <form name="form1" method="post" action="invoke" target="bottom"> <input type="text" name="city" id="city"> <input type="submit" name="sub" value="GO"> </form> </body> </html>?
bottom.htm <head> <title>weather</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"/> </head>?
8. deploy and run
?
at location: http://localhost:8080/axis/ ?and input any thing, you can get a result returned from servers.
?