声明:以下笔记内容都来自于小峰老师的视频课程,花了一天时间学习完,并做了笔记,供后续参考以及大家一起学习
分享小峰老师的一个很不错的开源博客系统
http://blog.java1234.com
项目中需要用到的依赖包都是通过maven来导入的,我的配置是这样的
//pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.java1234.webservice</groupId>
<artifactId>WS_Spring_CXF</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>WS_Spring_CXF</name>
<description />
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<version>3.0</version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-core -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
</dependencies>
</project>
如果CXF整合Spring的话,Maven又是构建的web工程,用的是tomcat容器的话,需要如下配置(如果构建的是Java工程,没有使用tomcat容器,则还需要引入jetty的依赖包)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>WS_Spring_CXF</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/webservice/*</url-pattern>
</servlet-mapping>
</web-app>
- 使用CXF开发WebService服务端接口
- 使用CXF开发WebService客户端
wsdl2java工具在CXF开发包里
开发下载地址
我的是jdk1.7的选择3.1.15版本的,最新版3.2.4需要1.8的jdk
下载二进制包解压到D盘
我们需要用到wsdl2java的命令,需要把bin目录配置到环境变量里面
新建一个客户端工程,找到需要生成java代码的目录,在DOS下进入当前目录,执行命令
D:\svnwork\WS_Client\src\main\java>wsdl2java http://192.168.1.104/helloWorld?wsdl
- CXF处理JavaBean以及复合类型
- CXF处理一些Map等复杂类型
- CXF添加拦截器
- CXF添加自定义拦截器
- Spring整合CXF发布WebService服务
- Spring整合CXF添加拦截器
//applicationContext.xml
<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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.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-servlet.xml" />
<context:component-scan base-package="com.java1234.webservice"></context:component-scan>
<!-- 定义服务提供者 -->
<!-- 这里implementor指定webservice接口实现类 address是具体的接口路径 -->
<jaxws:endpoint implementor="#helloWorld" address="/HelloWorld">
<!-- 添加in拦截器 -->
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
<bean class="com.java1234.interceptor.MyInterceptor" />
</jaxws:inInterceptors>
<!-- 添加out拦截器 -->
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</jaxws:outInterceptors>
</jaxws:endpoint>
</beans>
//User.java
package com.java1234.entity;
public class User {
private Integer id;// 编号
private String userName;// 用户名
private String password;// 密码
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//Role.java
package com.java1234.entity;
public class Role {
private Integer id;// 编号
private String roleName;// 角色名称
public Role() {
}
public Role(Integer id, String roleName) {
this.id = id;
this.roleName = roleName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
//MyRole.java
package com.java1234.entity;
import java.util.List;
/**
* 自定义实体cxf能接受
* @author pankai
*
*/
public class MyRole {
private String key;
private List<Role> value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<Role> getValue() {
return value;
}
public void setValue(List<Role> value) {
this.value = value;
}
}
//CXF解析不了Map类型,需要写一个适配器
//MyAdapter.java
package com.java1234.adapter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import com.java1234.entity.MyRole;
import com.java1234.entity.Role;
public class MapAdapter extends XmlAdapter<MyRole[], Map<String, List<Role>>>{
/**
* 适配转换MyRole[] -> Map<String, List<Role>>
*/
@Override
public Map<String, List<Role>> unmarshal(MyRole[] v) throws Exception {
Map<String, List<Role>> map = new HashMap<String, List<Role>>();
for (int i = 0; i < v.length; i++) {
MyRole role = v[i];
map.put(role.getKey(), role.getValue());
}
return map;
}
/**
* 适配转换Map<String, List<Role>> -> MyRole[]
*/
@Override
public MyRole[] marshal(Map<String, List<Role>> v) throws Exception {
MyRole[] roles = new MyRole[v.size()];
int i = 0;
for(String key : v.keySet()){
roles[i] = new MyRole();
roles[i].setKey(key);
roles[i].setValue(v.get(key));
i++;
}
return roles;
}
}
//自定义拦截器,模拟用户权限的,主要是服务端这边,进来的时候拦截
//MyInterceptor.java
package com.java1234.interceptor;
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 MyInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
public MyInterceptor() {
super(Phase.PRE_INVOKE);// 在调用方法之前调用拦截器
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
List<Header> headers = message.getHeaders();
if(headers==null || headers.size()==0){
throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截"));
}
Header firstHeader = headers.get(0);
Element element = (Element) firstHeader.getObject();
NodeList uList = element.getElementsByTagName("userName");
NodeList pList = element.getElementsByTagName("password");
if(uList.getLength()!=1){
throw new Fault(new IllegalArgumentException("用户名格式不对"));
}
if(pList.getLength()!=1){
throw new Fault(new IllegalArgumentException("密码格式不对"));
}
String userName = uList.item(0).getTextContent();
String password = pList.item(0).getTextContent();
if(!userName.equals("dravenxiaokai") || !password.equals("123456")){
throw new Fault(new IllegalArgumentException("用户名或者密码错误"));
}
}
}
//HelloWorldImpl.java
package com.java1234.webservice.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import org.springframework.stereotype.Component;
import com.java1234.entity.Role;
import com.java1234.entity.User;
import com.java1234.webservice.HelloWorld;
@Component("helloWorld")
@WebService
public class HelloWorldImpl implements HelloWorld {
@Override
public String say(String str) {
return "Hello:" + str;
}
@Override
public List<Role> getRoleByUser(User user) {
List<Role> roleList = new ArrayList<Role>();
// 模拟 直接写死
if (user != null) {
if (user.getUserName().equals("dravenxiaokai")
&& user.getPassword().equals("123456")) {
roleList.add(new Role(1, "技术总监"));
roleList.add(new Role(2, "架构师"));
} else if (user.getUserName().equals("jack")
&& user.getPassword().equals("123456")) {
roleList.add(new Role(3, "程序员"));
}
}
return roleList;
}
@Override
public Map<String, List<Role>> getRoles() {
Map<String, List<Role>> map = new HashMap<String, List<Role>>();
List<Role> roleList1 = new ArrayList<Role>();
roleList1.add(new Role(1, "技术总监"));
roleList1.add(new Role(2, "架构师"));
map.put("dravenxiaokai", roleList1);
List<Role> roleList2 = new ArrayList<Role>();
roleList2.add(new Role(3, "程序员"));
map.put("jack", roleList2);
return map;
}
}
//客户端在写之前,先在src/main/java的路径下执行wsdl2java命令,前面已经介绍了用法
//客户端自定义拦截器,消息头
//AddHeaderInterceptor.java
package com.java1234.interceptor;
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 AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
private String userName;
private String password;
public AddHeaderInterceptor() {
super(Phase.PREPARE_SEND);// 准备发送soap消息的时候调用拦截器
}
public AddHeaderInterceptor(String userName, String password) {
super(Phase.PREPARE_SEND);
this.userName = userName;
this.password = password;
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
List<Header> headerList = message.getHeaders();
Document document = DOMUtils.createDocument();
Element element = document.createElement("authHeader");
Element uElement = document.createElement("userName");
uElement.setTextContent(userName);
Element pElement = document.createElement("password");
pElement.setTextContent(password);
element.appendChild(uElement);
element.appendChild(pElement);
headerList.add(new Header(new QName("dravenxiaokai"),element));
}
}
//客户端测试程序
//Client.java
package com.java1234.webservice;
import java.util.List;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import com.java1234.interceptor.AddHeaderInterceptor;
import com.java1234.webservice.impl.HelloWorldImplService;
public class Client {
public static void main(String[] args) {
HelloWorldImplService service = new HelloWorldImplService();
HelloWorld helloWorld = service.getHelloWorldImplPort();
org.apache.cxf.endpoint.Client client = ClientProxy.getClient(helloWorld);
client.getOutInterceptors().add(new AddHeaderInterceptor("dravenxiaokai","123456"));//添加自定义拦截器
client.getInInterceptors().add(new LoggingInInterceptor());//添加In拦截器 日志拦截器
client.getOutInterceptors().add(new LoggingOutInterceptor());//添加out拦截器 日志拦截器
//System.out.println(helloWorld.say("draven_xiaokai"));
/*User user = new User();
user.setUserName("dravenxiaokai");
user.setPassword("123456");
List<Role> roleList = helloWorld.getRoleByUser(user);
for (Role role : roleList) {
System.out.println(role.getId()+","+role.getRoleName());
}*/
MyRoleArray array = helloWorld.getRoles();
List<MyRole> roleList = array.item;
for(int i=0;i<roleList.size();i++){
MyRole myRole = roleList.get(i);
System.out.print(myRole.key+":");
for(Role role : myRole.value){
System.out.println(role.getId()+","+role.getRoleName());
}
System.out.println("=============");
}
}
}
网友评论