CXF

package com.redbaby.myWeb;

public class Cat {
	private String color;
	private String name;

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String getName() {
		return name;
	}

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

	public Cat(String color, String name) {
		super();
		this.color = color;
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((color == null) ? 0 : color.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Cat other = (Cat) obj;
		if (color == null) {
			if (other.color != null)
				return false;
		} else if (!color.equals(other.color))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public Cat() {
		super();
		// TODO Auto-generated constructor stub
	}
	

}
package com.redbaby.myWeb;

import java.util.List;
import java.util.Map;

public interface HelloService {
	public List<Cat> getCat(User user);
	public Map<String, Cat> getAllCat();
}

package com.redbaby.myWeb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HelloServiceImpl implements HelloService {
	static Map<User, List<Cat>> map = new HashMap();
	static {
		List list = new ArrayList();
		list.add(new Cat("red", "miaomiao"));
		list.add(new Cat("blue", "mimi"));
		map.put(new User("qq", 18), list);
		List list2 = new ArrayList();
		list2.add(new Cat("green", "dog"));
		list2.add(new Cat("yellow", "hug"));
		map.put(new User("qq", 30), list2);
	}

	@Override
	public List<Cat> getCat(User user) {

		return map.get(user);
	}

	@Override
	public Map<String, Cat> getAllCat() {
		Map<String, Cat> re = new HashMap();
		int i=0;
		for (List<Cat> list : map.values()) {
			for (Cat cat : list) {
				re.put("qq"+i, cat);
			}
		}

		return re;
	}

}

package com.redbaby.myWeb;

import java.util.List;
import java.util.Map;

import javax.jws.WebService;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@WebService
public interface HelloWorld {
	public String sayHello(String name);
	public List<Cat> getCat(User user);
	public @XmlJavaTypeAdapter(MyXmlAdapter.class) Map<String,Cat> getAllCat();
}

package com.redbaby.myWeb;

import java.util.List;
import java.util.Map;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;;
@SOAPBinding(style = Style.RPC)
@WebService(endpointInterface="com.redbaby.myWeb.HelloWorld",serviceName="helloworldws")
public class HelloWorldimpl implements HelloWorld {

	@Override
	public String sayHello(String name) {
		// TODO Auto-generated method stub
		return "helloWorld"+name;
	}
	@Override
	public List<Cat> getCat(User user){
		HelloService hs=new HelloServiceImpl();
		return hs.getCat(user);
	}
	@Override
	public Map<String, Cat> getAllCat() {
		HelloService hs=new HelloServiceImpl();
		return hs.getAllCat();
	}

}
package com.redbaby.myWeb;

import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class MyInInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

public MyInInterceptor() {
super(Phase.PRE_INVOKE);// 拦截器在服务端被调用之前触发,检查SOAP消息
}

@Override
public void handleMessage(SoapMessage msg) throws Fault {
System.out.println("-----拦截------!!!!!!!!!!!!!!!!!");

// 得到soap消息的所有Header
List<Header> headers = msg.getHeaders();
if (headers == null || headers.size()<1) {
throw new Fault(new IllegalArgumentException("没有head信息,禁止调用!"));
}

// 假如要求第一个header携带用户名和密吗
Header header = headers.get(0);
Element e = (Element) header.getObject();
NodeList usernames = e.getElementsByTagName("username");
NodeList userpasses = e.getElementsByTagName("userpass");
if (usernames.getLength() != 1 || userpasses.getLength() != 1) {
throw new Fault(new IllegalArgumentException("head信息里的 用户名或密码 格式不对,禁止调用!"));
}

// 取出用户名的密码
String name = usernames.item(0).getTextContent();
String pass = userpasses.item(0).getTextContent();

// 查询数据库,检验用户名的密码
if (!name.equals("admin") || !pass.equals("root")) {
throw new Fault(new IllegalArgumentException("用户名或密码错误,拒绝调用!!"));
}
System.out.println("检查完毕");
}

}

package com.redbaby.myWeb;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import com.redbaby.myWeb.StringCat.MyEntry;

public class MyXmlAdapter extends XmlAdapter<StringCat, Map<String, Cat>> {

	@Override
	public Map<String, Cat> unmarshal(StringCat v) throws Exception {
		Map<String, Cat> map=new HashMap<String, Cat>();
		for(MyEntry mt:v.getEntries()){
			
			map.put(mt.getKey() , mt.getValue());
		}
		return map;
	}

	@Override
	public StringCat marshal(Map<String, Cat> v) throws Exception {
		StringCat sc=new StringCat();
		for(String key:v.keySet()){
			sc.getEntries().add(new MyEntry(key,v.get(key)));
			
		}
		return sc;
	}

}

package com.redbaby.myWeb;

import java.util.ArrayList;
import java.util.List;

public class StringCat {
	public static class MyEntry {
		private String key;
		private Cat value;

		public MyEntry() {
			// TODO Auto-generated constructor stub
		}

		public MyEntry(String key, Cat cat) {
			this.key = key;
			this.value = cat;
		}

		public String getKey() {
			return key;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public Cat getValue() {
			return value;
		}

		public void setValue(Cat value) {
			this.value = value;
		}

	}

	private List<MyEntry> entries=new ArrayList<StringCat.MyEntry>();

	public List<MyEntry> getEntries() {
		return entries;
	}

	public void setEntries(List<MyEntry> entries) {
		this.entries = entries;
	}

}

package com.redbaby.myWeb;

public class User {
	private String name;
	private Integer age;

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public User(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + "]";
	}

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	

}

package com.redbaby.myWeb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;

import javax.xml.ws.Endpoint;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;



public class Main {

	/**
	 * @param args	服务器发布
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException {
		HelloWorld helloWorldinstance=new HelloWorldimpl();
		EndpointImpl ep = (EndpointImpl) Endpoint.publish("http://192.168.1.109:8080/helloworldService", helloWorldinstance);
		
		//添加in拦截器,可以检查用户名及密码
		// ep.getInInterceptors().add(new MyInInterceptor(new PrintWriter(new File("in.txt"))));,输出到文件
		ep.getInInterceptors().add(new MyInInterceptor());//输出在控制台
		
		//添加out拦截器
		//ep.getOutInterceptors().add(new LoggingOutInterceptor());
		System.out.println("ok");
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p" 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-2.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" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<bean id="helloservice" class="com.redbaby.myWeb.HelloServiceImpl"></bean>
	<bean id="outLoggingInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
	<bean id="inMessageInterceptor" class="com.redbaby.myWeb.MyInInterceptor">
	</bean>

	<jaxws:server id="helloworld" serviceClass="com.redbaby.myWeb.HelloWorldimpl"
		address="/hello">
		<jaxws:serviceBean>
			<!-- 要暴露的 bean 的引用 -->
			<ref bean="helloservice" />
		</jaxws:serviceBean>
		<jaxws:inInterceptors>
			<ref bean="inMessageInterceptor" />
		</jaxws:inInterceptors>
		<jaxws:outInterceptors>
			<ref bean="outLoggingInterceptor" />
		</jaxws:outInterceptors>
	</jaxws:server>

</beans>



<!-- xmlns:p="http://www.springframework.org/schema/p" -->
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
	<display-name></display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/wsContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>cxf</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	<servlet-name>cxf</servlet-name>
	<url-pattern>/*</url-pattern>
	</servlet-mapping>





</web-app>



package com.redbaby.test;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class MyClientInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

	private String username;
	private String userpass;

	public MyClientInterceptor(String username, String userpass) {
		super(Phase.PREPARE_SEND);//准备发送SOAP消息时调用,插入头信息
		this.username = username;
		this.userpass = userpass;

	}

	@Override
	public void handleMessage(SoapMessage msg) throws Fault {

		List<Header> headers=msg.getHeaders();
		
		Document doc=DOMUtils.createDocument();
		
		Element h=doc.createElement("userHeader");//这个元素可以随便
		
		Element name=doc.createElement("username");//这个元素必须与服务器端一致
		name.setTextContent(username);
		Element pass=doc.createElement("userpass");
		pass.setTextContent(userpass);
		h.appendChild(name);
		h.appendChild(pass);
		
		headers.add(new Header(new QName("qqqqq"), h));//Qname可以随便取值
		
	}

}
package com.redbaby.test;

import java.util.List;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.jboss.weld.bean.proxy.ClientProxyMethodHandler;

import com.redbaby.myweb.Cat;
import com.redbaby.myweb.HelloWorld;
import com.redbaby.myweb.Helloworldws;
import com.redbaby.myweb.MyEntry;
import com.redbaby.myweb.StringCat;
import com.redbaby.myweb.User;

public class TestMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Helloworldws ws = new Helloworldws();

		// 得到代理
		HelloWorld hw = ws.getHelloWorldimplPort();
		Client client = ClientProxy.getClient(hw);
		
		//添加拦截器。向Header头信息注入用户名和密码
		client.getOutInterceptors().add(new MyClientInterceptor("admin","root"));
		
		
		
		//client.getInInterceptors().add();
		User user = new User();
		user.setAge(18);
		user.setName("张三");
		List<Cat> list = hw.getCat(user);
		for (Cat cat : list) {

			System.out.println(cat.getColor() + "  " + cat.getName());
		}
		System.out.println("");
		StringCat a = hw.getAllCat();
		for (MyEntry me : a.getEntries()) {

			System.out.println(me.getKey() + " " + me.getValue().getName());
		}
		System.out.println("end");
	}

}

若客户端与spring整合,则客户端的application.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"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
    
    <jaxws:client id="userWsClient" serviceClass="com.redbaby.myWeb.HelloWorldimpl" 
        address="http://{服务段地址}:8080/服务名/hello">
        <jaxws:outInterceptors>
             <bean class="com.redbaby.test.MyClientInterceptor">
              <constuctor-arg value="admin"/>   就是用户名
 		<constuctor-arg value="root"/>  就是密码
	</bean>
	</jaxws:outInterceptors>
</jaws:client>
</beans>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值