使用JDK发布WebService服务 JAX-WS:是指Java Api for XML – WebService。与Web服务相关的类,都位于javax.xml.ws.*包中。在JDK1.6以后的JDK中JAX-WS规范定义了如何发布一个webService服务。 @WebService - 就是一个WebService就是一个注解,用在类上指定将此类发布成一个webservice服务. Endpoint – 此类为端点服务类,它的方法publish用于将一个已经添加了@WebService注解对象绑定到一个地址的端口上。Endpoint是jdk提供的一个专门用于发布服务的类,它的publish方法接收两个参数,一个是本地的服务地址,二是提供服务的类。它位于javax.xml.ws.*包中。 static Endpoint.publish(String address, Object implementor) 在给定地址处针对指定的实现者对象创建并发布端点。stop方法用于停止服务。 1)给类添加上@WebService注解后,类中所有的非静态和非final方法都将会对外公布。 2)如果希望某个方法(非static,非final)不对外公开,可以在方法上添加@WebMethod(exclude=true),阻止其对外公开。 3)如果一个类上,被添加了@WebService注解,则必须此类至少有一个可以公开的方法,否则将会启动失败。如果添加@WebService的类里面没有一个方法,启动时也会报错。 使用AJAX方式调用WebService服务
var xhr; function invoke(){ if(window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }else{ xhr = new XMLHttpRequest(); } var inputValue= document.getElementById("inputValue").value; //指定请求地址 var url = "http://127.0.0.1:8888/demo?wsdl"; //定义请求类型和地址和异步 xhr.open("POST", url, true); //设置请求头 xhr.setRequestHeader("Content-Type", "text/xml;charset=UTF-8"); //指定回调函数 xhr.onreadystatechange = callBack; //拼接请求数据 var data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://demo.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +'<soapenv:Body>' +'<q0:demoMethod>' +'<arg0>'+inputValue+'</arg0>' +'</q0:demoMethod>' +'</soapenv:Body>' +'</soapenv:Envelope>'; xhr.send(data); } function callBack(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var node= xhr.responseXML; var tag = node.getElementsByTagName("return")[0]; } } }使用URLConnection方式调用WebService服务
//创建请求的url URL url = new URL("http://127.0.0.1:8888/demo"); URLConnection conn = url.openConnection(); //强制转换成HttpURL HttpURLConnection httpConn = (HttpURLConnection) conn; //打开输入输出的开关 httpConn.setDoInput(true); httpConn.setDoOutput(true); //设置请求方式 httpConn.setRequestMethod("POST"); //设置请求的头部信息 httpConn.setRequestProperty("Content-type", "text/xml;charset=UTF-8"); //拼接请求体 String data = "<soapenv:Envelope xmlns:soapenv=" + "\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:q0=\"http://demo.com/\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +"<soapenv:Body>" +"<q0:demoMethod>" +"<arg0>renliang</arg0> " +"</q0:demoMethod>" +"</soapenv:Body>" +"</soapenv:Envelope>"; //获得输出流 OutputStream out = httpConn.getOutputStream(); //发送数据 out.write(data.getBytes()); //判断请求成功 if(httpConn.getResponseCode() == 200){ //获得输入流 InputStream in = httpConn.getInputStream(); //使用输入流的缓冲区 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuffer sb = new StringBuffer(); String line = null; //读取输入流 while((line = reader.readLine()) != null){ sb.append(line); } //创建sax的读取器 SAXReader saxReader = new SAXReader(); //创建文档对象 Document doc = saxReader.read(new StringReader(sb.toString())); //获得请求响应return元素 List<Element> eles = doc.selectNodes("//return");