zoukankan      html  css  js  c++  java
  • cxf

    一,cxf webService入门案例

    1,jar包

    注意版本 使用jdk6和apache-cxf-3.1.2,但cxf-3.1.2已经不支持jdk6,需要jdk7以上

    版本用错会报java.lang.UnsupportedClassVersionError: org/apache/cxf/transport/servlet/CXFServlet : Unsupported major.minor version 51.0 

    下载地址: 取lib下的jar

     http://www.apache.org/dyn/closer.lua/cxf/2.7.18/apache-cxf-2.7.18.zip

    2,新建web工程

    3,java代码

    1 package com.lxl.it.cxf.service;
    2 
    3 import javax.jws.WebService;
    4 
    5 @WebService
    6 public interface ITestCxfWs {
    7 String sayHi(String text);
    8 }
    ITestCxfWs接口
     1 package com.lxl.it.cxf.service.impl;
     2 
     3 import javax.jws.WebService;
     4 
     5 import com.lxl.it.cxf.service.ITestCxfWs;
     6 @WebService(endpointInterface="com.lxl.it.cxf.service.ITestCxfWs",serviceName="testCxfWs")
     7 public class TestCxfWs implements ITestCxfWs{
     8 
     9     @Override
    10     public String sayHi(String text) {
    11         return text;
    12     }
    13 
    14 }
    TestCxfWs实现类
     1 package com.lxl.it.cxf.service.test;
     2 
     3 import javax.xml.ws.Endpoint;
     4 
     5 import com.lxl.it.cxf.service.impl.TestCxfWs;
     6 
     7 public class WebServiceApp {
     8     public static void main(String[] args) {
     9         System.out.println("WebServiceApp satrt");
    10         TestCxfWs ws=new TestCxfWs();
    11         String address="http://localhost:8080/testCxfWs";
    12         Endpoint.publish(address, ws);
    13         System.out.println("WebServiceApp end");
    14     }
    15 }
    代码发webService

    4,xml配置 web.xml  spring配置

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xmlns="http://java.sun.com/xml/ns/javaee"
     4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     5     id="WebApp_ID" version="2.5">
     6     <display-name>TestWebService</display-name>
     7     <welcome-file-list>
     8         <welcome-file>index.html</welcome-file>
     9         <welcome-file>index.htm</welcome-file>
    10         <welcome-file>index.jsp</welcome-file>
    11         <welcome-file>default.html</welcome-file>
    12         <welcome-file>default.htm</welcome-file>
    13         <welcome-file>default.jsp</welcome-file>
    14     </welcome-file-list>
    15     <context-param>
    16         <param-name>contextConfigLocation</param-name>
    17         <param-value>/WEB-INF/applicationContext.xml</param-value>
    18     </context-param>
    19     <listener>
    20         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    21     </listener>
    22     <servlet>
    23         <servlet-name>CXFServlet</servlet-name>
    24         <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    25         <load-on-startup>1</load-on-startup>
    26     </servlet>
    27     <servlet-mapping>
    28         <servlet-name>CXFServlet</servlet-name>
    29         <url-pattern>/ws/*</url-pattern>
    30     </servlet-mapping>
    31 </web-app>
    web.xml
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
     4     xsi:schemaLocation="
     5                        http://www.springframework.org/schema/beans
     6 
     7                        http://www.springframework.org/schema/beans/spring-beans.xsd
     8                        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
     9 
    10     <import resource="classpath:META-INF/cxf/cxf.xml" />
    11     <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    12     <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
    13 
    14     <jaxws:endpoint id="testCxfWs" implementor="com.lxl.it.cxf.service.impl.TestCxfWs"
    15         address="/testCxfWs" />
    16 
    17     <bean id="client" class="com.lxl.it.cxf.service.ITestCxfWs" factory-bean="clientFactory"
    18         factory-method="create" />
    19 
    20     <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
    21         <property name="serviceClass" value="com.lxl.it.cxf.service.ITestCxfWs" />
    22         <property name="address"
    23 
    24             value="http://localhost:8080/TestWebService/webservice/testCxfWs" />
    25     </bean>
    26 </beans>
    spring

    二,cxf增加拦截器

    1,工程

    2,java代码

     1 package com.lxl.it.cxf.service.Interceptor;
     2 
     3 import java.lang.reflect.Method;
     4 import java.util.List;
     5 
     6 import javax.servlet.http.HttpServletRequest;
     7 
     8 import org.apache.cxf.frontend.MethodDispatcher;
     9 import org.apache.cxf.interceptor.Fault;
    10 import org.apache.cxf.message.Exchange;
    11 import org.apache.cxf.message.Message;
    12 import org.apache.cxf.phase.AbstractPhaseInterceptor;
    13 import org.apache.cxf.phase.Phase;
    14 import org.apache.cxf.service.Service;
    15 import org.apache.cxf.service.model.BindingOperationInfo;
    16 import org.apache.cxf.transport.http.AbstractHTTPDestination;
    17 
    18 import com.lxl.it.utils.IpUtil;
    19 import com.lxl.it.utils.StringUtils;
    20 import com.lxl.it.utils.Tuple2;
    21 /**
    22  * 对webservice的请求ip地址进行限制的拦截器
    23  * 
    24  */
    25 public class IpAddressInInterceptor extends AbstractPhaseInterceptor<Message>{
    26     
    27     public IpAddressInInterceptor() {
    28         super(Phase.USER_LOGICAL);
    29     }
    30     @Override
    31     public void handleMessage(Message msg) throws Fault {
    32 
    33         String ip = "0.0.0.0";
    34         HttpServletRequest httpRequest = (HttpServletRequest) msg
    35         .get(AbstractHTTPDestination.HTTP_REQUEST);
    36         
    37         if (null != httpRequest) {
    38             ip = StringUtils.getIpFromRequest(httpRequest);
    39         }else{
    40             return;
    41         }
    42         
    43 
    44         Exchange exchange = msg.getExchange();
    45         Method paramMethod = ((MethodDispatcher) exchange.get(Service.class)
    46                 .get(MethodDispatcher.class.getName())).getMethod(exchange
    47                 .get(BindingOperationInfo.class));
    48         String method = paramMethod.toString();
    49         List<Tuple2<Long, Long>> ips =null;//这里是获取系统配置的ip白名单
    50         //ips=InterfaceMethodCache
    51 //                .getAuthorizedIp(method);
    52 //        if (ips == null || ips.isEmpty()) {
    53 //            // 然后用类名称查找配置
    54 //            method = paramMethod.getDeclaringClass().getName();
    55 //            ips = InterfaceMethodCache.getAuthorizedIp(method);
    56 //        }
    57         if (ips == null || ips.isEmpty()) {
    58             return;
    59         }
    60 
    61         if (!IpUtil.ipCheck(ip, ips)) {
    62             throw new Fault(new IllegalAccessException("method id[" + method
    63                     + "] & ip address[" + ip + "] is denied!"));
    64         }
    65     
    66         
    67     }
    68 
    69 }
    IpAddressInInterceptor
     1 package com.lxl.it.utils;
     2 
     3 import java.util.List;
     4 
     5 import org.slf4j.Logger;
     6 import org.slf4j.LoggerFactory;
     7 
     8 public class IpUtil {
     9     
    10     private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
    11 
    12     /**
    13      * 将IP转成整数
    14      * 
    15      * @param ip
    16      * @return
    17      */
    18     public static long ipToLong(String ip) {
    19         long res = 0;
    20         String[] ss = ip.split("\.");
    21         res = ((Long.valueOf(ss[0]) * 256 + Long.valueOf(ss[1])) * 256 + Long
    22                 .valueOf(ss[2])) * 256 + Long.valueOf(ss[3]);
    23         return res;
    24     }
    25 
    26     /**
    27      * 校验IP是否合法
    28      * 
    29      * @param ip
    30      * @param ips
    31      * @return
    32      */
    33     public static boolean ipCheck(String ip, List<Tuple2<Long, Long>> ips) {
    34         return ipCheck(ipToLong(ip), ips);
    35     }
    36 
    37     public static boolean ipCheck(long ip, List<Tuple2<Long, Long>> ips) {
    38         for (Tuple2<Long, Long> tuple : ips) {
    39             if ((ip >= tuple._1 && ip <= tuple._2) || ip == 0L)
    40                 return true;
    41         }
    42         return false;
    43     }
    44 
    45     public static boolean ipCheck(String ip, Tuple2<Long, Long> tuple) {
    46         return ipCheck(ipToLong(ip), tuple);
    47     }
    48 
    49     public static boolean ipCheck(long ip, Tuple2<Long, Long> tuple) {
    50         return (ip >= tuple._1 && ip <= tuple._2);
    51     }
    52 
    53     private static String getCheckword(String xml) {
    54         String checkword = null;
    55         try {
    56             if (xml != null) {
    57                 int sIndex = xml.indexOf("<checkword>");
    58                 int eIndex = xml.indexOf("</checkword>");
    59 
    60                 if (sIndex != -1 && eIndex != -1) {
    61                     checkword = xml.substring(sIndex + "<checkword>".length(),
    62                             eIndex);
    63                 }
    64             }
    65         } catch (Exception e) {
    66             // e.printStackTrace();
    67             logger.error("", e);
    68         }
    69         return checkword;
    70     }
    71 
    72 
    73 
    74 
    75 
    76 
    77     public static void main(String[] args) {
    78         // System.out.println(ipToLong("0.0.0.0"));
    79         // System.out.println(ipToLong("255.255.255.255"));
    80     }
    81 }
    IpUtil
      1 package com.lxl.it.utils;
      2 
      3 /**
      4  * Copyright (c) 2013, S.F. Express Inc. All rights reserved.
      5  */
      6 
      7 import java.io.ByteArrayOutputStream;
      8 import java.io.PrintWriter;
      9 import java.io.UnsupportedEncodingException;
     10 import java.lang.reflect.Field;
     11 import java.nio.charset.Charset;
     12 import java.util.ArrayList;
     13 import java.util.List;
     14 
     15 import javax.servlet.http.HttpServletRequest;
     16 
     17 import org.slf4j.Logger;
     18 import org.slf4j.LoggerFactory;
     19 
     20 public class StringUtils {
     21 
     22     private static Logger logger = LoggerFactory.getLogger(StringUtils.class);
     23 
     24     /*
     25      * 16进制数字字符集
     26      */
     27     private static String hexString = "0123456789ABCDEF";
     28 
     29     public static boolean isNotEmpty(String str) {
     30         return !isEmpty(str);
     31     }
     32 
     33     public static boolean isEmpty(String str) {
     34         return str == null || str.trim().length() == 0;
     35     }
     36 
     37     public static String toString(Object o) {
     38         if (o == null)
     39             return null;
     40         return o.toString();
     41     }
     42 
     43     // private static final String BR = "<br>
    ";
     44 
     45     public static String throwableToString(Throwable e) {
     46         ByteArrayOutputStream buf = new ByteArrayOutputStream();
     47         e.printStackTrace(new PrintWriter(buf, true));
     48         return buf.toString();
     49         // StringBuilder sb = new StringBuilder();
     50         // try {
     51         // throwableToString(e, sb);
     52         // } catch (Exception e1) {
     53         // sb.append("parse and print exception error.");
     54         // }
     55         // return sb.toString();
     56     }
     57 
     58     // @SuppressWarnings("unchecked")
     59     // private static void throwableToString(Throwable e, StringBuilder sb) {
     60     // if (e == null)
     61     // sb.append("#Exception:NULL");
     62     // else {
     63     // sb.append(BR).append(e.getClass().getName()).append(":").append(e.getMessage()).append(BR)
     64     // .append("#StackTrace:");
     65     // boolean isIterable = false;
     66     // if (e instanceof Iterable) {
     67     // try {
     68     // StringBuilder sb2 = new StringBuilder();
     69     // for (Throwable t : (Iterable<Throwable>) e)
     70     // throwableToString(t, sb2);
     71     // sb.append(sb2);
     72     // isIterable = true;
     73     // } catch (Exception e1) {
     74     // isIterable = false;
     75     // }
     76     // }
     77     // if (!isIterable) {
     78     // for (StackTraceElement ele : e.getStackTrace())
     79     // sb.append(BR).append(ele.toString());
     80     // }
     81     // }
     82     // }
     83 
     84     /**
     85      * 从request中获取ip地址
     86      * 
     87      * @param request
     88      *            请求
     89      * @return
     90      */
     91     public static String getIpFromRequest(HttpServletRequest request) {
     92         String ip = request.getHeader("x-forwarded-for");
     93         if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
     94             ip = request.getHeader("Proxy-Client-IP");
     95         }
     96         if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
     97             ip = request.getHeader("WL-Proxy-Client-IP");
     98         }
     99         if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
    100             ip = request.getRemoteAddr();
    101         }
    102         if (ip != null) {
    103             int idx = ip.indexOf(',');
    104             if (idx > 0) {
    105                 ip = ip.substring(0, idx);
    106             }
    107         }
    108         return ip;
    109     }
    110 
    111     /**
    112      * null和空字符串认为空
    113      * 
    114      * @param target
    115      * @return
    116      */
    117     public static boolean isBlank(String target) {
    118         return isEmpty(target);
    119     }
    120 
    121     /**
    122      * 按字节数截取字符串
    123      * 
    124      * @param orignal
    125      *            字符串
    126      * @param count
    127      *            需要截取的字节数
    128      * @return
    129      * @throws UnsupportedEncodingException
    130      */
    131     public static String substring(String orignal, int count)
    132             throws UnsupportedEncodingException {
    133         // 原始字符不为null,也不是空字符串
    134         if (!isEmpty(orignal)) {
    135             // 将原始字符串转换为UTF-8编码格式
    136             orignal = new String(orignal.getBytes(), "UTF-8");
    137             // 要截取的字节数大于0,且小于原始字符串的字节数
    138             if (count > 0 && count < orignal.getBytes("UTF-8").length) {
    139                 StringBuffer buff = new StringBuffer();
    140                 boolean lastCharIsChineses = false;
    141 
    142                 char c;
    143                 for (int i = 0; i < count; i++) {
    144                     c = orignal.charAt(i);
    145                     buff.append(c);
    146                     if (isChineseChar(c)) {
    147                         lastCharIsChineses = true;
    148                         // 遇到中文汉字,截取字节总数减2
    149                         --count;
    150                         --count;
    151                     } else {
    152                         lastCharIsChineses = false;
    153                     }
    154                 }
    155 
    156                 if (lastCharIsChineses) {
    157                     buff.deleteCharAt(buff.length() - 1);
    158                 }
    159 
    160                 return buff.toString();
    161             }
    162         }
    163         return orignal;
    164     }
    165 
    166     public static boolean isChineseChar(char c) {
    167         Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
    168         if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
    169                 || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
    170                 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
    171                 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
    172                 || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
    173                 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
    174                 || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
    175             return true;
    176         }
    177         return false;
    178     }
    179 
    180     private static final int[] BYTES_COUNT = new int[] { 0x80, 0x40, 0x20,
    181             0x10, 8, 4 };
    182 
    183     private static final Charset utf8Charset = Charset.forName("utf-8");
    184 
    185     public static String oracleUtf8Sub(String str, int len)
    186             throws UnsupportedEncodingException {
    187         return oracleUtf8Sub(str, 0, len);
    188     }
    189 
    190     public static String oracleUtf8Sub(String str, int from, int len)
    191             throws UnsupportedEncodingException {
    192         if (str == null || len < 0 || from < 0 || from >= str.length())
    193             throw new IllegalArgumentException();
    194 
    195         if (from != 0)
    196             str = str.substring(from);
    197 
    198         byte[] bs = str.getBytes(utf8Charset);
    199 
    200         if (len >= bs.length)
    201             return str;
    202 
    203         int to = 0;
    204         int to_ = 0;
    205 
    206         while (to <= len) {
    207             to_ = to;
    208             byte b = bs[to];
    209             if (0 <= b && b < 128) {
    210                 to += 1;
    211             } else {
    212                 for (int i = 1; i <= 5; ++i) {
    213                     if ((b & BYTES_COUNT[i]) > 0)
    214                         continue;
    215                     if (i == 1)
    216                         throw new RuntimeException("Error utf8 decode for:"
    217                                 + str);
    218                     to += i;
    219                     break;
    220                 }
    221             }
    222         }
    223 
    224         return new String(bs, 0, to_, utf8Charset);
    225     }
    226 
    227     /**
    228      * 从含路由的文件名中提取单纯的文件名称
    229      * 
    230      * @param pathFileName
    231      *            含路径的文件名称
    232      * @return String
    233      */
    234     public static String getFileNameFromPath(String pathFileName) {
    235         String fileNameTemp = null;
    236         int lastSplitPos = 0;
    237 
    238         if (pathFileName.indexOf("/") > -1) {
    239             lastSplitPos = pathFileName.lastIndexOf("/");
    240             fileNameTemp = pathFileName.substring(lastSplitPos + 1,
    241                     pathFileName.length());
    242         } else if (pathFileName.indexOf("\") > -1) {
    243             lastSplitPos = pathFileName.lastIndexOf("\");
    244             fileNameTemp = pathFileName.substring(lastSplitPos + 1,
    245                     pathFileName.length());
    246         } else if (pathFileName.indexOf(":") > -1) {
    247             lastSplitPos = pathFileName.lastIndexOf(":");
    248             fileNameTemp = pathFileName.substring(lastSplitPos + 1,
    249                     pathFileName.length());
    250         } else {
    251             fileNameTemp = pathFileName;
    252         }
    253 
    254         return fileNameTemp;
    255     }
    256 
    257     public static String getFirstNodeTxt(String xmlStr, String nodeName) {
    258         String resultStr = null;
    259 
    260         if (StringUtils.isNotEmpty(xmlStr) && StringUtils.isNotEmpty(nodeName)) {
    261             int startIndex = xmlStr.indexOf("<" + nodeName + ">");
    262             int endIndex = xmlStr.indexOf("</" + nodeName + ">");
    263 
    264             if (startIndex != -1 && endIndex != -1) {
    265                 resultStr = xmlStr.substring(
    266                         startIndex + nodeName.length() + 2, endIndex);
    267             }
    268 
    269         }
    270 
    271         return resultStr;
    272     }
    273 
    274     public static String getHexTOString(String bytes) {
    275         ByteArrayOutputStream baos = new ByteArrayOutputStream(
    276                 bytes.length() / 2);
    277         // 将每2位16进制整数组装成一个字节
    278         for (int i = 0; i < bytes.length(); i += 2)
    279             baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
    280                     .indexOf(bytes.charAt(i + 1))));
    281         return new String(baos.toByteArray());
    282     }
    283 
    284     public static String toString(StackTraceElement[] stesElements) {
    285         if (stesElements != null) {
    286             try {
    287                 StringBuilder sBuilder = new StringBuilder();
    288                 for (StackTraceElement ste : stesElements) {
    289                     sBuilder.append(' ').append(ste.toString()).append('
    ');
    290                 }
    291                 return sBuilder.toString();
    292             } catch (Exception e) {
    293                 logger.error("", e);
    294             }
    295         }
    296         return null;
    297     }
    298 
    299     /**
    300      * HTML转义
    301      * 
    302      * @param content
    303      * @return
    304      */
    305     public static String htmlEncode(String content) {
    306         if (content == null)
    307             return "";
    308 
    309         String html = content;
    310 
    311         html = html.replaceAll("&", "&amp;");
    312         html = html.replace("'", "&apos;");
    313         html = html.replace(""", "&quot;"); // "
    314         html = html.replace("	", "&nbsp;&nbsp;");// 替换跳格
    315         html = html.replace(" ", "&nbsp;");// 替换空格
    316         html = html.replace("<", "&lt;");
    317         html = html.replaceAll(">", "&gt;");
    318 
    319         return html;
    320     }
    321 
    322     /**
    323      * 输出某个对象的全部属性值
    324      * 
    325      * @param obj
    326      *            对象
    327      * @param fieldShow属性名称与属性值之间的分隔符
    328      * @param fieldEndChr属性结束符
    329      *            :各个属性之间的分隔符
    330      * @return
    331      */
    332     public static String outAllFields4Object(Object obj, String fieldShow,
    333             String fieldEndChr) {
    334         if (null == obj) {
    335             return null;
    336         } else {
    337             StringBuilder sbuilder = new StringBuilder();
    338 
    339             if (isEmpty(fieldShow)) {
    340                 fieldShow = "->";
    341             }
    342 
    343             if (isEmpty(fieldEndChr)) {
    344                 fieldEndChr = ";";
    345             }
    346 
    347             try {
    348                 Class<?> c = obj.getClass();
    349                 Field[] fields = c.getDeclaredFields();
    350 
    351                 sbuilder.append(obj.getClass()).append(":");
    352 
    353                 for (Field f : fields) {
    354                     f.setAccessible(true);
    355                     String field = f.toString().substring(
    356                             f.toString().lastIndexOf(".") + 1); // 取出属性名称
    357                     sbuilder.append(field).append(fieldShow)
    358                             .append(f.get(obj) == null ? "" : f.get(obj))
    359                             .append(fieldEndChr);
    360                 }
    361             } catch (IllegalArgumentException e) {
    362                 // TODO Auto-generated catch block
    363                 e.printStackTrace();
    364             } catch (IllegalAccessException e) {
    365                 // TODO Auto-generated catch block
    366                 e.printStackTrace();
    367             }
    368 
    369             return sbuilder.toString();
    370         }
    371 
    372     }
    373     /**
    374      * 输出某个对象的全部属性值
    375      * 
    376      * @param obj
    377      *            对象
    378      * @param fieldShow属性名称与属性值之间的分隔符
    379      * @param fieldEndChr属性结束符
    380      *            :各个属性之间的分隔符
    381      * @return
    382      */
    383     public static String outAllFields4ObjectAndSuper(Object obj, String fieldShow,
    384             String fieldEndChr) {
    385         if (null == obj) {
    386             return null;
    387         } else {
    388             StringBuilder sbuilder = new StringBuilder();
    389 
    390             if (isEmpty(fieldShow)) {
    391                 fieldShow = "->";
    392             }
    393 
    394             if (isEmpty(fieldEndChr)) {
    395                 fieldEndChr = ";";
    396             }
    397 
    398             try {
    399                 Class<?> c = obj.getClass();
    400                 List<Field> fields=new ArrayList<Field>();
    401                 fields=getClassField(c,fields);
    402 
    403                 sbuilder.append(obj.getClass()).append(":");
    404 
    405                 for (Field f : fields) {
    406                     f.setAccessible(true);
    407                     String field = f.toString().substring(
    408                             f.toString().lastIndexOf(".") + 1); // 取出属性名称
    409                     sbuilder.append(field).append(fieldShow)
    410                             .append(f.get(obj) == null ? "" : f.get(obj))
    411                             .append(fieldEndChr);
    412                 }
    413             } catch (IllegalArgumentException e) {
    414                 // TODO Auto-generated catch block
    415                 e.printStackTrace();
    416             } catch (IllegalAccessException e) {
    417                 // TODO Auto-generated catch block
    418                 e.printStackTrace();
    419             }
    420 
    421             return sbuilder.toString();
    422         }
    423 
    424     }
    425 
    426     /**
    427      * 获取类的所有属性,包括父类的
    428      * 
    429      * @param aClazz
    430      * @param fieldList
    431      * @return
    432      */
    433     private static List<Field> getClassField(Class aClazz, List<Field> fieldList) {
    434         Field[] declaredFields = aClazz.getDeclaredFields();
    435         for (Field field : declaredFields) {
    436             fieldList.add(field);
    437         }
    438 
    439         Class superclass = aClazz.getSuperclass();
    440         if (superclass != null) {// 简单的递归一下
    441             return getClassField(superclass, fieldList);
    442         }
    443         return fieldList;
    444     }
    445 
    446     /**
    447      * 将非打印字符替换为空格
    448      * 
    449      * @param str
    450      *            需处理的字符串
    451      * @param charset
    452      *            :字符串编码格式:UTF-8,GBK
    453      * @return
    454      * @throws UnsupportedEncodingException
    455      */
    456     public static String emptyNotPrintChar(String str, String charset)
    457             throws UnsupportedEncodingException {
    458 
    459         if (StringUtils.isEmpty(str)) {
    460             return "";
    461         }
    462 
    463         return new String(emptyNotPrintChar(str.getBytes(charset)), charset);
    464     }
    465 
    466     /**
    467      * 将非打印字符替换为空格
    468      * 
    469      * @param str
    470      *            需处理的字符串
    471      * @return
    472      * @throws UnsupportedEncodingException
    473      */
    474     public static String emptyNotPrintChar(String str) {
    475 
    476         if (StringUtils.isEmpty(str)) {
    477             return "";
    478         }
    479 
    480         return new String(emptyNotPrintChar(str.getBytes()));
    481     }
    482 
    483     /**
    484      * 将非打印字符替换为空格
    485      * 
    486      * @param bts
    487      *            需处理的字节数组
    488      * @return
    489      */
    490     private static byte[] emptyNotPrintChar(byte[] bts) {
    491         int btsLength = bts.length;
    492         byte[] newBytes = new byte[btsLength];
    493         for (int i = 0; i < btsLength; i++) {
    494 
    495             byte b = bts[i];
    496             if ((b >= 0 && b <= 31) || b == 127) {
    497                 b = 32;
    498             }
    499 
    500             newBytes[i] = b;
    501         }
    502 
    503         return newBytes;
    504     }
    505 
    506 //    public static void main(String[] args) throws UnsupportedEncodingException {
    507 //        String str = "qwertyuiop中华人民共和国123456789";
    508 //        String destStr = "";
    509 //
    510 //        destStr = StringUtils.emptyNotPrintChar(str, "UTF-8");
    511 //        System.out.println(destStr);
    512 //
    513 //        str = "上海杨浦区昆明路739号文通大厦15层 中青旅联科";
    514 //        destStr = "";
    515 //
    516 //        destStr = StringUtils.emptyNotPrintChar(str, "GBK");
    517 //        System.out.println(destStr);
    518 //    }
    519 }
    StringUtils
     1 package com.lxl.it.utils;
     2 
     3 import java.io.Serializable;
     4 
     5 public class Tuple2<T1, T2> implements Serializable {
     6 
     7     private static final long serialVersionUID = -39962326066034337L;
     8 
     9     public T1 _1;
    10     public T2 _2;
    11 
    12     public Tuple2() {
    13     }
    14 
    15     public Tuple2(T1 _1, T2 _2) {
    16         super();
    17         this._1 = _1;
    18         this._2 = _2;
    19     }
    20 
    21     /**
    22      * 根据提供的参数,构造Tuple对象
    23      * 
    24      * @param _1
    25      * @param _2
    26      * @return
    27      */
    28     public static <E1, E2> Tuple2<E1, E2> apply(E1 _1, E2 _2) {
    29         Tuple2<E1, E2> res = new Tuple2<E1, E2>();
    30         res._1 = _1;
    31         res._2 = _2;
    32         return res;
    33     }
    34 
    35     @Override
    36     public String toString() {
    37         return "[" + _1 + ", " + _2 + "]";
    38     }
    39 
    40     @Override
    41     public int hashCode() {
    42         final int prime = 31;
    43         int result = 1;
    44         result = prime * result + ((_1 == null) ? 0 : _1.hashCode());
    45         result = prime * result + ((_2 == null) ? 0 : _2.hashCode());
    46         return result;
    47     }
    48 
    49     @Override
    50     public boolean equals(Object obj) {
    51         if (this == obj)
    52             return true;
    53         if (obj == null)
    54             return false;
    55         if (getClass() != obj.getClass())
    56             return false;
    57         Tuple2<?, ?> other = (Tuple2<?, ?>) obj;
    58         if (_1 == null) {
    59             if (other._1 != null)
    60                 return false;
    61         } else if (!_1.equals(other._1))
    62             return false;
    63         if (_2 == null) {
    64             if (other._2 != null)
    65                 return false;
    66         } else if (!_2.equals(other._2))
    67             return false;
    68         return true;
    69     }
    70 
    71 }
    Tuple2

    3,配置spring文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     4     xmlns:jaxws="http://cxf.apache.org/jaxws"
     5     xmlns:cxf="http://cxf.apache.org/core"
     6     xsi:schemaLocation="
     7                        http://www.springframework.org/schema/beans
     8                        http://www.springframework.org/schema/beans/spring-beans.xsd
     9                        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
    10                        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
    11                        
    12                        
    13 
    14     <import resource="classpath:META-INF/cxf/cxf.xml" />
    15     <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    16     <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
    17     <bean id="ipAddressInInterceptor"
    18         class="com.lxl.it.cxf.service.Interceptor.IpAddressInInterceptor" />
    19     <!-- 监听 -->
    20     <cxf:bus>
    21         <cxf:inInterceptors>
    22             <ref bean="ipAddressInInterceptor" />
    23         </cxf:inInterceptors>
    24     </cxf:bus>
    25     <jaxws:endpoint id="testCxfWs"
    26         implementor="com.lxl.it.cxf.service.impl.TestCxfWs" address="/testCxfWs" />
    27 
    28     <bean id="client" class="com.lxl.it.cxf.service.ITestCxfWs"
    29         factory-bean="clientFactory" factory-method="create" />
    30 
    31     <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
    32         <property name="serviceClass" value="com.lxl.it.cxf.service.ITestCxfWs" />
    33         <property name="address"
    34 
    35             value="http://localhost:8080/TestWebService/webservice/testCxfWs" />
    36     </bean>
    37 
    38 
    39 </beans>
    spring

    注意:
       <!-- 监听 -->
     <cxf:bus>
      <cxf:inInterceptors>
       <ref bean="ipAddressInInterceptor" />
      </cxf:inInterceptors>
     </cxf:bus>

    上述监听配置用的cxf标签,需要再spring配置文件头部加上声明

    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:jaxws="http://cxf.apache.org/jaxws"
     xmlns:cxf="http://cxf.apache.org/core"
     xsi:schemaLocation="
                           http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
                           http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
                          

  • 相关阅读:
    BZOJ 2212/BZOJ 3702
    BZOJ 4761 Cow Navigation
    BZOJ 3209 花神的数论题
    BZOJ 4760 Hoof, Paper, Scissors
    BZOJ 3620 似乎在梦中见过的样子
    BZOJ 3940 Censoring
    BZOJ 3942 Censoring
    BZOJ 3571 画框
    BZOJ 1937 最小生成树
    BZOJ 1058 报表统计
  • 原文地址:https://www.cnblogs.com/jiaozi-li/p/5695591.html
Copyright © 2011-2022 走看看