Cxf - Spring整合Cxf暴露WebServices

襲冷發表於2014-04-19

一、新建Web工程

    匯入Spring Core、Spring Web和Cxf的jar包;建立WS元件和業務邏輯Bean。結構如下:

        

二、配置web.xml

<?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">

	<!-- Spring配置檔案路徑  -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- Web啟動時載入Spring容器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 將Cxf的請求交給CXFServlet處理(所有webapp/cxf/* )  -->
	<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>/cxf/*</url-pattern>
	</servlet-mapping>
	
</web-app>
三、配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--  匯入Cxf的Schema(xmlns:jaxws) -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
		 http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

	<!-- 匯入Cxf的xml -->
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />

	<!-- 配置業務邏輯處理的Bean -->
	<bean id="userService" class="com.xilen.cxf.service.impl.UserServiceImpl"></bean>

	<!--  配置Web Services實現的Bean -->
	<bean id="userInfoWsImpl" class="com.xilen.cxf.ws.impl.UserInfoWsImpl">
		<property name="us" ref="userService" />
	</bean>

	<!-- 配置EndPoint,暴露Web Services
		 address:IP、Port、AppName、NameSpace(web.xml中CXFServlet配置)都是確定的,所以只需要配置其後面的部分即可
		 implementor:Web Services的實現 在Bean的Id前面加#符號   -->
	<jaxws:endpoint address="/userinfo" implementor="#userInfoWsImpl">
	
		<!-- 攔截器的配置  -->
		<jaxws:inInterceptors>
			<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
			<bean class="com.xilen.cxf.ws.inter.ServerAuthInInterceptor"></bean>
		</jaxws:inInterceptors>
	</jaxws:endpoint>

</beans>    

四、載入到Tomcat並啟動

       

    暴露成功!


五、相關程式碼

public class Book {
	private Integer id;
	private String name;
	private Date date;

	/*getter and setter*/

}
public class User {
	private Integer id;
	private String name;
	private String email;

	/*getter and setter */

}
public interface UserService {

	public List<Book> getBookByUser(User user);

	public Map<String, Book> getUserRecommBook();

	public Map<User, List<Book>> getBookGroupByUser();

}
public class UserServiceImpl implements UserService {

	static Map<User, List<Book>> MEMORYDB = new HashMap<User, List<Book>>();

	static {
		List<Book> books1 = new ArrayList<Book>();
		books1.add(new Book(1, "Java", new Date()));
		books1.add(new Book(2, "PHP", new Date()));
		books1.add(new Book(3, "C++", new Date()));
		MEMORYDB.put(new User(1, "Admin", "admin@admin.com"), books1);

		List<Book> books2 = new ArrayList<Book>();
		books2.add(new Book(11, "Windows", new Date()));
		books2.add(new Book(12, "Linux", new Date()));
		books2.add(new Book(13, "Mac", new Date()));
		MEMORYDB.put(new User(2, "Super", "super@super.com"), books2);

	}

	@Override
	public List<Book> getBookByUser(User user) {

		return MEMORYDB.get(user);
	}

	@Override
	public Map<String, Book> getUserRecommBook() {
		Map<String, Book> maps = new HashMap<String, Book>();

		for (User user : MEMORYDB.keySet()) {
			maps.put(user.getName(), MEMORYDB.get(user).get(0));
		}

		return maps;
	}

	@Override
	public Map<User, List<Book>> getBookGroupByUser() {
		return MEMORYDB;
	}

}
@WebService
public interface UserInfoWs {

	public String sayHello(String name);

	public List<Book> getBookByUser(User u);

	public Map<String, Book> getUserRecommBook();

	public @XmlJavaTypeAdapter(MyXmlAdapter.class) Map<User, List<Book>> getBookGroupByUser();

}
@WebService(serviceName = "UserInfoWsImpl", endpointInterface = "com.xilen.cxf.ws.UserInfoWs")
public class UserInfoWsImpl implements UserInfoWs {

	private UserService us;

	@Override
	public String sayHello(String name) {
		return name + ", Hello!";
	}

	@Override
	public List<Book> getBookByUser(User u) {
		return us.getBookByUser(new User("Admin"));
	}

	@Override
	public Map<String, Book> getUserRecommBook() {
		return us.getUserRecommBook();
	}

	@Override
	public Map<User, List<Book>> getBookGroupByUser() {
		return us.getBookGroupByUser();
	}

	public UserService getUs() {
		return us;
	}

	public void setUs(UserService us) {
		this.us = us;
	}

}
public class ServerAuthInInterceptor extends AbstractPhaseInterceptor<SoapMessage>{
	
	public ServerAuthInInterceptor(){
		super(Phase.PRE_INVOKE);
	}
	
	public void handleMessage(SoapMessage message) throws Fault {
		List<Header> headers = message.getHeaders();
		
		if (headers.isEmpty()) {
			throw new Fault(new IllegalArgumentException("沒有攜帶額外的資訊!"));
		}
		
		Header header = headers.get(0);
		Element element = (Element) header.getObject();
		
		NodeList nodeUserName = element.getElementsByTagName("userName");
		NodeList nodeUserPass = element.getElementsByTagName("userPass");
		if(nodeUserName.getLength() != 1 || nodeUserPass.getLength() != 1){
			throw new Fault(new IllegalArgumentException("沒有攜帶使用者資訊或者不符合要求!"));
		}
		
		String userName = nodeUserName.item(0).getTextContent();
		String userPass = nodeUserPass.item(0).getTextContent();
		if(!userName.equals("CxfName") || !userPass.equals("CxfPass")){
			throw new Fault(new IllegalArgumentException("使用者名稱或者密碼不正確!"));
		}
		
		// 如果驗證一路通過,則請求自動繼續往下
	}
}
public class MyXmlAdapter extends XmlAdapter<DataSet, Map<User, List<Book>>> {

	@Override
	public Map<User, List<Book>> unmarshal(DataSet v) throws Exception {

		Map<User, List<Book>> maps = new HashMap<User, List<Book>>();
		for (Item item : v.getItem()) {
			maps.put(item.getKey(), item.getValue());
		}
		return maps;
	}

	@Override
	public DataSet marshal(Map<User, List<Book>> v) throws Exception {
		
		DataSet ds = new DataSet();
		for (User user : v.keySet()) {
			Item item = new Item(user, v.get(user));
			ds.getItem().add(item);
		}
		return ds;
	}
	
}
public class Item {
	private User key;
	private List<Book> value;

	/*getter and setter*/

}
public class DataSet {

	private List<Item> item = new ArrayList<Item>();

}
六、資源下載

    http://download.csdn.net/detail/u013379717/7219307

 

 

相關文章