Java WebService

原生实现

编写web服务类
package jws.server;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService(name="Example", targetNamespace="http://www.zzy.com/wstest", serviceName="Example")
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class Example {

	@WebMethod(operationName="toSayHello",
			action="sayHello",
			exclude=false)
	@WebResult(name="returnWord")
	public String sayHello(@WebParam(name="userName")String userName){
		return "Hello : " + userName;
	}
}

编写服务器端
package jws.server;

import javax.xml.ws.Endpoint;

public class StartWebServiceServer {
	
	public static void main(String[] args){
		Example serverBean = new Example();
		Endpoint.publish("http://localhost:8080/hello", serverBean);
		System.out.println("服务已启动, URL: http://localhost:8080/hello");
	}
}


使用wsimport自动生成Example接口和Example_Service类
package jws.client;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Action;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebService(name = "Example", targetNamespace = "http://www.zzy.com/wstest")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface Example {


    /**
     * 
     * @param userName
     * @return
     *     returns java.lang.String
     */
    @WebMethod(action = "sayHello")
    @WebResult(name = "returnWord", partName = "returnWord")
    @Action(input = "sayHello", output = "http://www.zzy.com/wstest/Example/toSayHelloResponse")
    public String toSayHello(
        @WebParam(name = "userName", partName = "userName")
        String userName);

}


package jws.client;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebServiceClient(name = "Example", targetNamespace = "http://www.zzy.com/wstest", wsdlLocation = "http://localhost:8080/hello?wsdl")
public class Example_Service
    extends Service
{

    private final static URL EXAMPLE_WSDL_LOCATION;
    private final static WebServiceException EXAMPLE_EXCEPTION;
    private final static QName EXAMPLE_QNAME = new QName("http://www.zzy.com/wstest", "Example");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("http://localhost:8080/hello?wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        EXAMPLE_WSDL_LOCATION = url;
        EXAMPLE_EXCEPTION = e;
    }

    public Example_Service() {
        super(__getWsdlLocation(), EXAMPLE_QNAME);
    }

    public Example_Service(WebServiceFeature... features) {
        super(__getWsdlLocation(), EXAMPLE_QNAME, features);
    }

    public Example_Service(URL wsdlLocation) {
        super(wsdlLocation, EXAMPLE_QNAME);
    }

    public Example_Service(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, EXAMPLE_QNAME, features);
    }

    public Example_Service(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public Example_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     * 
     * @return
     *     returns Example
     */
    @WebEndpoint(name = "ExamplePort")
    public Example getExamplePort() {
        return super.getPort(new QName("http://www.zzy.com/wstest", "ExamplePort"), Example.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns Example
     */
    @WebEndpoint(name = "ExamplePort")
    public Example getExamplePort(WebServiceFeature... features) {
        return super.getPort(new QName("http://www.zzy.com/wstest", "ExamplePort"), Example.class, features);
    }

    private static URL __getWsdlLocation() {
        if (EXAMPLE_EXCEPTION!= null) {
            throw EXAMPLE_EXCEPTION;
        }
        return EXAMPLE_WSDL_LOCATION;
    }

}

编写客户端类
package jws.client;

public class RunClient {

	public static void main(String[] args) {
		Example_Service service = new Example_Service();
		Example server = (Example) service.getExamplePort();
		try{
			System.out.println("toSayHello:" + server.toSayHello("zzy"));
		}catch( Exception e){
			e.printStackTrace();
		}
	}

}

-----------------------------------------------------------------------------------------------------------------------------------------

使用Eclipse生成Web Service


新建一个普通的java项目
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class Hello {
	@WebMethod
	public String hello(String name){
		return name + ", Hello!";
	}
	
	public static void main(String[] args) {   
	   // create and publish an endpoint
	   Hello hello = new Hello();   
	   Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", hello);    
	} 
}

在该项目上右击新建一个Web Service项目,再右击新建一个Web Service Client项目

OK!

---------------------------------------------------------------------------------------------------------------------------------------------------


Spring +CXF实现Web Service


This Demo is copied from http://blog.csdn.net/cq1982/article/details/44761699

User实体类
package com.java.entity;

public class User {
	private long id;
	private String name;
	private String address;
	private String email;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}


WebService接口
package com.java.service;

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import com.java.entity.User;

/**
 * <b>function:</b>定制客户端请求WebService所需要的接口
 */
@WebService
@SOAPBinding(style = Style.RPC)
public interface IUserService {
	public User getUserByName(@WebParam(name = "name") String name);

	public void setUser(User user);
}

WebService实现类
package com.java.service.impl;

import java.util.Date;

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import com.java.entity.User;
import com.java.service.IUserService;

/**
 * <b>function:</b> WebService传递复杂对象,如JavaBean、Array、List、Map等
 */
@WebService
@SOAPBinding(style = Style.RPC)
public class UserServiceImpl implements IUserService {
	public User getUserByName(@WebParam(name = "name") String name) {
		User user = new User();
		user.setId(new Date().getTime());
		user.setName(name);
		user.setAddress("china");
		user.setEmail(name + "@test.com");
		return user;
	}

	public void setUser(User user) {
		System.out.println("############Server setUser###########");
		System.out.println("setUser:" + user);
	}
}

Web Service客户端
package com.java.client;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.java.entity.User;
import com.java.service.IUserService;

public class SpringUsersWsClient {

	public static void main(String[] args) {
		// 调用WebService
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(IUserService.class);
		factory.setAddress("http://localhost:8080/CXFWebService/Users");

		IUserService service = (IUserService) factory.create();

		System.out.println("#############Client getUserByName##############");
		User user = service.getUserByName("hoojo");
		System.out.println(user.getName());

		user.setAddress("China-Guangzhou");
		service.setUser(user);
	}
}

applicationContext-server.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://cxf.apache.org/jaxws
    http://cxf.apache.org/schemas/jaxws.xsd">
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	 

	<bean id="inMessageInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
	<bean id="outLoggingInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

	<bean id="userServiceBean" class="com.java.service.impl.UserServiceImpl" />
	<jaxws:server id="userService" serviceClass="com.java.service.IUserService" address="/WebService/Users">
		<jaxws:serviceBean>
			<ref bean="userServiceBean" />
		</jaxws:serviceBean>
		<jaxws:inInterceptors>
			<ref bean="inMessageInterceptor" />
		</jaxws:inInterceptors>
		<jaxws:outInterceptors>
			<ref bean="outLoggingInterceptor" />
		</jaxws:outInterceptors>
	</jaxws:server>
</beans>  

log4j.properties
 ### set log levels ###
log4j.rootLogger = debug,D

### \u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.D = org.apache.log4j.ConsoleAppender
log4j.appender.D.Target = System.out
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c:%L - %m%n

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext-server.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>CXFService</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CXFService</servlet-name>
    <url-pattern>/WebService/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值