• WebService之CXF入门开发


    1. Server端项目结构
      f870ff0e5a4348aaa9f88df1c91c2fb5.png
    2. Server端pom.xml
      1. <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">
      2. <modelVersion>4.0.0</modelVersion>
      3. <groupId>com.java1234.webservice</groupId>
      4. <artifactId>WS_Server</artifactId>
      5. <version>0.0.1-SNAPSHOT</version>
      6. <dependencies>
      7. <dependency>
      8. <groupId>org.apache.cxf</groupId>
      9. <artifactId>cxf-core</artifactId>
      10. <version>3.1.5</version>
      11. </dependency>
      12. <dependency>
      13. <groupId>org.apache.cxf</groupId>
      14. <artifactId>cxf-rt-frontend-jaxws</artifactId>
      15. <version>3.1.5</version>
      16. </dependency>
      17. <dependency>
      18. <groupId>org.apache.cxf</groupId>
      19. <artifactId>cxf-rt-transports-http-jetty</artifactId>
      20. <version>3.1.5</version>
      21. </dependency>
      22. <!--JDK11需要添加此依赖-->
      23. <dependency>
      24. <groupId>com.sun.xml.ws</groupId>
      25. <artifactId>jaxws-ri</artifactId>
      26. <version>2.3.1</version>
      27. </dependency>
      28. </dependencies>
      29. </project>
    3. Server端实体类
      1. package com.cxf.entity;
      2. public class User {
      3. private Integer id; // 编号
      4. private String userName; // 用户名
      5. private String password; // 密码
      6. public Integer getId() {
      7. return id;
      8. }
      9. public void setId(Integer id) {
      10. this.id = id;
      11. }
      12. public String getUserName() {
      13. return userName;
      14. }
      15. public void setUserName(String userName) {
      16. this.userName = userName;
      17. }
      18. public String getPassword() {
      19. return password;
      20. }
      21. public void setPassword(String password) {
      22. this.password = password;
      23. }
      24. }
      1. package com.cxf.entity;
      2. public class Role {
      3. private Integer id; // 编号
      4. private String roleName; // 角色名称
      5. public Role() {
      6. super();
      7. // TODO Auto-generated constructor stub
      8. }
      9. public Role(Integer id, String roleName) {
      10. super();
      11. this.id = id;
      12. this.roleName = roleName;
      13. }
      14. public Integer getId() {
      15. return id;
      16. }
      17. public void setId(Integer id) {
      18. this.id = id;
      19. }
      20. public String getRoleName() {
      21. return roleName;
      22. }
      23. public void setRoleName(String roleName) {
      24. this.roleName = roleName;
      25. }
      26. }
      1. package com.cxf.entity;
      2. import java.util.List;
      3. /**
      4. * 接口的返回值类型为Map时需要该中间实体来互转
      5. * @author Administrator
      6. *
      7. */
      8. public class MyRole {
      9. private String key;
      10. private List<Role> value;
      11. public String getKey() {
      12. return key;
      13. }
      14. public void setKey(String key) {
      15. this.key = key;
      16. }
      17. public List<Role> getValue() {
      18. return value;
      19. }
      20. public void setValue(List value) {
      21. this.value = value;
      22. }
      23. }
    4.  Server端接口
      1. package com.cxf.webservice;
      2. import java.util.List;
      3. import java.util.Map;
      4. import javax.jws.WebService;
      5. import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
      6. import com.cxf.adapter.MapAdapter;
      7. import com.cxf.entity.Role;
      8. import com.cxf.entity.User;
      9. @WebService
      10. public interface HelloWorld {
      11. // 返回值为String
      12. public String say(String str);
      13. // 返回值为List
      14. public List getRoleByUser(User user);
      15. // 返回值为Map-->需要自定义适配器:MapAdapter-->@XmlJavaTypeAdapter(MapAdapter.class)
      16. @XmlJavaTypeAdapter(MapAdapter.class)
      17. public Map> getRoles();
      18. }
    5. Server端接口实现
      1. package com.cxf.webservice.impl;
      2. import java.util.ArrayList;
      3. import java.util.HashMap;
      4. import java.util.List;
      5. import java.util.Map;
      6. import javax.jws.WebService;
      7. import com.cxf.entity.Role;
      8. import com.cxf.entity.User;
      9. import com.cxf.webservice.HelloWorld;
      10. @WebService
      11. public class HelloWorldImpl implements HelloWorld{
      12. public String say(String str) {
      13. return "Hello:"+str;
      14. }
      15. public List<Role> getRoleByUser(User user) {
      16. List<Role> roleList=new ArrayList<Role>();
      17. roleList.add(new Role(1,"AAAA"));
      18. roleList.add(new Role(2,"BBBB"));
      19. return roleList;
      20. }
      21. public Map<String, List<Role>> getRoles() {
      22. Map<String,List<Role>> map=new HashMap>();
      23. List<Role> roleList1=new ArrayList<Role>();
      24. roleList1.add(new Role(1,"CCCC"));
      25. map.put("cccc", roleList1);
      26. List<Role> roleList2=new ArrayList<Role>();
      27. roleList2.add(new Role(2,"DDDD"));
      28. map.put("dddd", roleList2);
      29. return map;
      30. }
      31. }
    6.  Map类型返回值适配器
      1. package com.cxf.adapter;
      2. import java.util.HashMap;
      3. import java.util.List;
      4. import java.util.Map;
      5. import java.util.Set;
      6. import javax.xml.bind.annotation.adapters.XmlAdapter;
      7. import com.cxf.entity.MyRole;
      8. import com.cxf.entity.Role;
      9. public class MapAdapter extends XmlAdapter<MyRole[], Map<String,List<Role>>>{
      10. /**
      11. * 适配转换 MyRole[] -> Map<String, List<Role>>
      12. */
      13. @Override
      14. public Map<String, List<Role>> unmarshal(MyRole[] myRoles) throws Exception {
      15. Map<String, List<Role>> map=new HashMap>();
      16. for(int i=0;i<myRoles.length;i++){
      17. MyRole myRole=myRoles[i];
      18. map.put(myRole.getKey(), myRole.getValue());
      19. }
      20. return map;
      21. }
      22. /**
      23. * 适配转换 Map<String, List<Role>> -> MyRole[]
      24. */
      25. @Override
      26. public MyRole[] marshal(Map<String, List<Role>> map) throws Exception {
      27. MyRole[] roles=new MyRole[map.size()];
      28. Set<Map.Entry<String, List<Role>>> entries = map.entrySet();
      29. Integer index = 0;
      30. for (Map.Entry<String, List<Role>> entry : entries) {
      31. roles[index]=new MyRole();
      32. roles[index].setKey(entry.getKey());
      33. roles[index].setValue(entry.getValue());
      34. index++;
      35. }
      36. return roles;
      37. }
      38. }
    7.  Server端自定义拦截器(调用接口方法前执行)
      1. package com.cxf.interceptor;
      2. import java.util.List;
      3. import org.apache.cxf.binding.soap.SoapMessage;
      4. import org.apache.cxf.headers.Header;
      5. import org.apache.cxf.interceptor.Fault;
      6. import org.apache.cxf.phase.AbstractPhaseInterceptor;
      7. import org.apache.cxf.phase.Phase;
      8. import org.w3c.dom.Element;
      9. import org.w3c.dom.NodeList;
      10. public class MyInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
      11. public MyInterceptor() {
      12. super(Phase.PRE_INVOKE); // 调用接口方法前执行自定拦截器
      13. }
      14. @SuppressWarnings("null")
      15. public void handleMessage(SoapMessage message) throws Fault {
      16. List<Header> headers=message.getHeaders();
      17. if(headers==null && headers.size()==0){
      18. throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截"));
      19. }
      20. Header firstHeader=headers.get(0);
      21. Element ele=(Element) firstHeader.getObject();
      22. NodeList uList=ele.getElementsByTagName("userName");
      23. NodeList pList=ele.getElementsByTagName("password");
      24. if(uList.getLength()!=1){
      25. throw new Fault(new IllegalArgumentException("用户名格式不对"));
      26. }
      27. if(pList.getLength()!=1){
      28. throw new Fault(new IllegalArgumentException("密码格式不对"));
      29. }
      30. String userName=uList.item(0).getTextContent();
      31. String password=pList.item(0).getTextContent();
      32. if(!userName.equals("cxf")||!password.equals("123456")){
      33. throw new Fault(new IllegalArgumentException("用户名或者密码错误!"));
      34. }
      35. }
      36. }
    8.  Server端启动类
      1. package com.cxf.webservice.impl;
      2. import org.apache.cxf.interceptor.LoggingInInterceptor;
      3. import org.apache.cxf.interceptor.LoggingOutInterceptor;
      4. import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
      5. import com.cxf.interceptor.MyInterceptor;
      6. import com.cxf.webservice.HelloWorld;
      7. public class Server {
      8. public static void main(String[] args) {
      9. System.out.println("web service start");
      10. HelloWorld implementor=new HelloWorldImpl();
      11. String address="http://localhost:8888/helloWorld";
      12. // Endpoint.publish(address, implementor); // jdk实现 暴露webservice接口
      13. JaxWsServerFactoryBean factoryBean=new JaxWsServerFactoryBean();
      14. factoryBean.setAddress(address); // 设置暴露地址
      15. factoryBean.setServiceClass(HelloWorld.class); // 接口类
      16. factoryBean.setServiceBean(implementor); // 设置实现类
      17. factoryBean.getInInterceptors().add(new LoggingInInterceptor()); // 添加in拦截器 日志拦截器
      18. factoryBean.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加out拦截器 日志拦截器
      19. factoryBean.getInInterceptors().add(new MyInterceptor());
      20. factoryBean.create(); // 创建webservice接口
      21. System.out.println("web service started");
      22. }
      23. }
    9.  启动Server端
      2120ac8e43104c918d69ab5f686aab35.png
    10.  Client端自动生成
      https://pan.baidu.com/s/1wTK2ly-SJgZM99TyAdmPiw?pwd=hbn1
      1. 1.apache-cxf-3.1.5.zip解压后在环境变量添加bin路径
      2. 2.执行命令:wsdl2java -encoding utf-8 -d C:\Users\Administrator\Desktop\wsdl http://localhost:8888/helloWorld?wsdl
      3. 3.将C:\Users\Administrator\Desktop\wsdl路径下自动生成的java文件复制到Client端

      11cc871c30ae4196b9f20a752f444b65.png
      17c8239685f1411e8a0f82acea16ce53.png

    11.  Client端pom.xml
      1. <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">
      2. <modelVersion>4.0.0</modelVersion>
      3. <groupId>com.java1234.webservice</groupId>
      4. <artifactId>WS_Client</artifactId>
      5. <version>0.0.1-SNAPSHOT</version>
      6. <dependencies>
      7. <dependency>
      8. <groupId>org.apache.cxf</groupId>
      9. <artifactId>cxf-core</artifactId>
      10. <version>3.1.5</version>
      11. </dependency>
      12. <dependency>
      13. <groupId>org.apache.cxf</groupId>
      14. <artifactId>cxf-rt-frontend-jaxws</artifactId>
      15. <version>3.1.5</version>
      16. </dependency>
      17. <dependency>
      18. <groupId>org.apache.cxf</groupId>
      19. <artifactId>cxf-rt-transports-http-jetty</artifactId>
      20. <version>3.1.5</version>
      21. </dependency>
      22. <!--JDK11需要添加此依赖-->
      23. <dependency>
      24. <groupId>com.sun.xml.ws</groupId>
      25. <artifactId>jaxws-ri</artifactId>
      26. <version>2.3.1</version>
      27. </dependency>
      28. </dependencies>
      29. </project>
    12.  Client端自定义拦截器(发送SOAP消息时调用)
      1. package com.cxf.interceptor;
      2. import java.util.List;
      3. import javax.xml.namespace.QName;
      4. import org.apache.cxf.binding.soap.SoapMessage;
      5. import org.apache.cxf.headers.Header;
      6. import org.apache.cxf.helpers.DOMUtils;
      7. import org.apache.cxf.interceptor.Fault;
      8. import org.apache.cxf.phase.AbstractPhaseInterceptor;
      9. import org.apache.cxf.phase.Phase;
      10. import org.w3c.dom.Document;
      11. import org.w3c.dom.Element;
      12. public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
      13. private String userName;
      14. private String password;
      15. public AddHeaderInterceptor(String userName,String password) {
      16. super(Phase.PREPARE_SEND); // 准备发送SOAP消息的时候调用拦截器
      17. this.userName=userName;
      18. this.password=password;
      19. }
      20. /**
      21. * 客户端拦截器和服务端拦截器对应,客户端拦截器向SoapMessage添加的参数可以在服务端拦截器获取到并进行校验
      22. * 校验失败通过:throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截"))抛出的异常在客户端控制台可见
      23. * @param message
      24. * @throws Fault
      25. */
      26. public void handleMessage(SoapMessage message) throws Fault {
      27. List<Header> headerList=message.getHeaders();
      28. Document doc=DOMUtils.createDocument();
      29. Element ele=doc.createElement("authHeader");
      30. Element uElement=doc.createElement("userName");
      31. uElement.setTextContent(userName);
      32. Element pElement=doc.createElement("password");
      33. pElement.setTextContent(password);
      34. ele.appendChild(uElement);
      35. ele.appendChild(pElement);
      36. headerList.add(new Header(new QName("cxf"),ele));
      37. }
      38. }
    13.   Client端测试类
      1. package com.cxf.webservice;
      2. import java.util.List;
      3. import org.apache.cxf.frontend.ClientProxy;
      4. import org.apache.cxf.interceptor.LoggingInInterceptor;
      5. import org.apache.cxf.interceptor.LoggingOutInterceptor;
      6. import com.cxf.interceptor.AddHeaderInterceptor;
      7. public class Client {
      8. public static void main(String[] args) {
      9. HelloWorldService service=new HelloWorldService();
      10. HelloWorld helloWorld=service.getHelloWorldPort();
      11. org.apache.cxf.endpoint.Client client=ClientProxy.getClient(helloWorld);
      12. client.getOutInterceptors().add(new AddHeaderInterceptor("cxf","123456")); // 添加自定义拦截器
      13. client.getInInterceptors().add(new LoggingInInterceptor()); // 添加In拦截器 日志拦截器
      14. client.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加Out拦截器 日志拦截器
      15. System.out.println(helloWorld.say("cxf"));
      16. List roles1=helloWorld.getRoleByUser(new User());
      17. for(Role role:roles1){
      18. System.out.println(role.getId()+","+role.getRoleName());
      19. }
      20. // 返回值为Map,服务端需要适配转换 @XmlJavaTypeAdapter(MapAdapter.class)-->Map> -> MyRole[]
      21. List roles2 = helloWorld.getRoles().item;
      22. for (MyRole myRole : roles2) {
      23. String key = myRole.getKey();
      24. List roles = myRole.getValue();
      25. System.out.println(key+":"+roles.toString());
      26. }
      27. }
      28. }
      f31163d5a90d4d47b3a9dc3c5f5a3a65.png
      b17cee2ba230492fa82121cca81b92fb.png
      32293391822b468db888abfd5ec7c3b5.png
      ab0b8197bbb04304bbdd50b8861e6a97.png

    https://blog.csdn.net/caoli201314?type=blog

     

     

  • 相关阅读:
    问题总结:一个 list 使用 for 遍历,边循环边删除的问题
    爬虫基本原理介绍、实现以及问题解决
    【算法|贪心算法系列No.3】leetcode334. 递增的三元子序列
    力扣面试150 文本左右对齐 贪心 字符串 满注释版
    RDB 做快照的时候数据能修改吗?
    SUB-1G 无线收发芯片CC1101国产替代方案
    双十一买什么比较划算?四款实用性超强不吃灰的数码好物推荐
    C#调用Python脚本
    【前端笔试】关于一些输入输出
    培训机构不会告诉的真相:为什么不招聘培训出来的前端
  • 原文地址:https://blog.csdn.net/tongxin_tongmeng/article/details/126482362