springmvc分页实现,java如何调用webservice接口

作者: 新金沙平台  发布:2019-08-16

java如何调用webservice接口,java调用webservice

java调用WebService可以直接使用Apache提供的axis.jar自己编写代码,或者利用Eclipse自动生成WebService Client代码,利用其中的Proxy类进行调用。理论上是一样的,只不过用Eclipse自动生成代码省事些。
1、编写代码方式:
package com.yudun.test;
import java.rmi.RemoteException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.PrefixedQName;
import org.apache.axis.message.SOAPHeaderElement;
import com.cezanne.golden.user.Exception;
import com.cezanne.golden.user.UserManagerServiceProxy;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import javax.xml.rpc.ServiceException;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPException;

public class testWebService {
public static String getResult() throws ServiceException, MalformedURLException, RemoteException, SOAPException
  {
     //标识Web Service的具体路径
   String endpoint = "WebService服务地址";
     // 创建 Service实例
    Service service = new Service();   
     // 通过Service实例创建Call的实例
    Call call = (Call) service.createCall();
    //将Web Service的服务路径加入到call实例之中.
    call.setTargetEndpointAddress( new java.net.URL(endpoint) );//为Call设置服务的位置
   // 由于需要认证,故需要设置调用的SOAP头信息。   
    Name headerName = new PrefixedQName( new QName("发布的wsdl里的targetNamespace里的url", "string_itemName") ); 
          org.apache.axis.message.SOAPHeaderElement header = new SOAPHeaderElement(headerName); 
          header.addTextNode( "blablabla" ); 
          call.addHeader(header);

//    SOAPHeaderElement soapHeaderElement = new SOAPHeaderElement("发布的wsdl里的targetNamespace里的url", "SoapHeader");   
//    soapHeaderElement.setNamespaceURI("发布的wsdl里的targetNamespace里的url");   
//    try  
//    {   
//        soapHeaderElement.addChildElement("string_itemName").setValue("blablabla");   
//    }   
//    catch (SOAPException e)   
//    {   
//        e.printStackTrace();   
//    }   
//    call.addHeader(soapHeaderElement);  
    //调用Web Service的方法
          org.apache.axis.description.OperationDesc oper;
          org.apache.axis.description.ParameterDesc param;
          oper = new org.apache.axis.description.OperationDesc();
          oper.setName("opName");
          param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "arg0"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), java.lang.String.class, false, false);
          param.setOmittable(true);
          oper.addParameter(param);
          param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "arg1"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), java.lang.String.class, false, false);
          param.setOmittable(true);
          oper.addParameter(param);
          param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "arg2"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), java.lang.String.class, false, false);
          param.setOmittable(true);
          oper.addParameter(param);
          oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
          oper.setReturnClass(java.lang.String.class);
          oper.setReturnQName(new javax.xml.namespace.QName("", "return"));
          oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
          oper.setUse(org.apache.axis.constants.Use.LITERAL);
          oper.addFault(new org.apache.axis.description.FaultDesc(
                        new javax.xml.namespace.QName("发布的wsdl里的targetNamespace里的url", "Exception"),
                        "Exception",
                        new javax.xml.namespace.QName("发布的wsdl里的targetNamespace里的url", "Exception"), 
                        true
                       ));
   call.setOperation( oper );
   call.setOperationName(new javax.xml.namespace.QName("发布的wsdl里的targetNamespace里的url", "opName"));
    //调用Web Service,传入参数
   String res = ( String ) call.invoke( new Object[]("arg0","arg1"));
   System.out.println("===============");
   return res;
  }
/**
  * @param args
  */
 public static void main(String[] args) {
  try {
   System.out.println(getResult());
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (RemoteException e) {
   e.printStackTrace();
  } catch (ServiceException e) {
   e.printStackTrace();
  } catch (SOAPException e) {
   e.printStackTrace();
  }
    }
}

2、利用Eclipse自动生成WebService client代码就容易多了:(由于还不会发图片,就用语言描述了,大家酬和看吧。。。)
首先,new project,选择other,在输入框中输入Web Service Client,选中搜索后的结果,点击Next,在Service definition中输入 WebService的发布地址,点击Finish
这样,WebService Client代码已经生成好了。
接下来写一个Test类,在main函数中输入如下代码:

String endpoint = "服务器的WebService的地址";
 YourWebServiceNameProxy umsp = new YourWebServiceNameProxy (endpoint);
 try {
 String resultStr = umsp.opMethod("arg0","arg1");
 System.out.println(resultStr);
 } catch (Exception e) {
 System.out.println("异常");
 e.printStackTrace();
} catch (RemoteException e) {
 System.out.println("RemoteException异常");
 e.printStackTrace();
}

java调用WebService可以直接使用Apache提供的axis.jar自己编写代码,或者利用Eclipse自动生成WebService...

解决PKIX(PKIX path building failed) 问题 unable to find valid certification path to requested target,certification

最近在写java的一个服务,需要给远程服务器发送post请求,认证方式为Basic Authentication,在请求过程中出现了 

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target的错误,于是开始搜索并得到解决,

下面总结一下解决过程:

我们要做的就是将所要访问的URL的安全认证证书导入到客户端中,以下就是获取安全证书的一种方法:

1.首先新建一个java类,命名为 InstallCert.java,将下面内容保存到文件中

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
 String host;
 int port;
 char[] passphrase;
 if ((args.length == 1) || (args.length == 2)) {
     String[] c = args[0].split(":");
     host = c[0];
     port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
     String p = (args.length == 1) ? "changeit" : args[1];
     passphrase = p.toCharArray();
 } else {
     System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
     return;
 }

 File file = new File("jssecacerts");
 if (file.isFile() == false) {
     char SEP = File.separatorChar;
     File dir = new File(System.getProperty("java.home")   SEP
        "lib"   SEP   "security");
     file = new File(dir, "jssecacerts");
     if (file.isFile() == false) {
  file = new File(dir, "cacerts");
     }
 }
 System.out.println("Loading KeyStore "   file   "...");
 InputStream in = new FileInputStream(file);
 KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
 ks.load(in, passphrase);
 in.close();

 SSLContext context = SSLContext.getInstance("TLS");
 TrustManagerFactory tmf =
     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
 tmf.init(ks);
 X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
 SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
 context.init(null, new TrustManager[] {tm}, null);
 SSLSocketFactory factory = context.getSocketFactory();

 System.out.println("Opening connection to "   host   ":"   port   "...");
 SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
 socket.setSoTimeout(10000);
 try {
     System.out.println("Starting SSL handshake...");
     socket.startHandshake();
     socket.close();
     System.out.println();
     System.out.println("No errors, certificate is already trusted");
 } catch (SSLException e) {
     System.out.println();
     e.printStackTrace(System.out);
 }

 X509Certificate[] chain = tm.chain;
 if (chain == null) {
     System.out.println("Could not obtain server certificate chain");
     return;
 }

 BufferedReader reader =
  new BufferedReader(new InputStreamReader(System.in));

 System.out.println();
 System.out.println("Server sent "   chain.length   " certificate(s):");
 System.out.println();
 MessageDigest sha1 = MessageDigest.getInstance("SHA1");
 MessageDigest md5 = MessageDigest.getInstance("MD5");
 for (int i = 0; i < chain.length; i  ) {
     X509Certificate cert = chain[i];
     System.out.println
      (" "   (i   1)   " Subject "   cert.getSubjectDN());
     System.out.println("   Issuer  "   cert.getIssuerDN());
     sha1.update(cert.getEncoded());
     System.out.println("   sha1    "   toHexString(sha1.digest()));
     md5.update(cert.getEncoded());
     System.out.println("   md5     "   toHexString(md5.digest()));
     System.out.println();
 }

 System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
 String line = reader.readLine().trim();
 int k;
 try {
     k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
 } catch (NumberFormatException e) {
     System.out.println("KeyStore not changed");
     return;
 }

 X509Certificate cert = chain[k];
 String alias = host   "-"   (k   1);
 ks.setCertificateEntry(alias, cert);

 OutputStream out = new FileOutputStream("jssecacerts");
 ks.store(out, passphrase);
 out.close();

 System.out.println();
 System.out.println(cert);
 System.out.println();
 System.out.println
  ("Added certificate to keystore 'jssecacerts' using alias '"
    alias   "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
 StringBuilder sb = new StringBuilder(bytes.length * 3);
 for (int b : bytes) {
     b &= 0xff;
     sb.append(HEXDIGITS[b >> 4]);
     sb.append(HEXDIGITS[b & 15]);
     sb.append(' ');
 }
 return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

 private final X509TrustManager tm;
 private X509Certificate[] chain;

 SavingTrustManager(X509TrustManager tm) {
     this.tm = tm;
 }

 public X509Certificate[] getAcceptedIssuers() {
     throw new UnsupportedOperationException();
 }

 public void checkClientTrusted(X509Certificate[] chain, String authType)
  throws CertificateException {
     throw new UnsupportedOperationException();
 }

 public void checkServerTrusted(X509Certificate[] chain, String authType)
  throws CertificateException {
     this.chain = chain;
     tm.checkServerTrusted(chain, authType);
 }
    }

}

2.我是将文件放到D盘根目录,打开cmd命令开始编译此java文件

   首先在cmd中进入到java的安装目录,然后用 javac 来编译文件

图片 1

文件编译完成后会在 同一个目录下成两个类(InstallCert.class,InstallCert$SavingTrustManager.class)

  1. 用命令执行 InstallCert.class ,命令方式为:java InstallCert hostname  (hostname为请求服务器的地址)  比如:java InstallCert www.cebbank.com

接下来会看到如下的打印信息

java InstallCert www.cebbank.com
Loading KeyStore /usr/java/jdk1.6.0_31/jre/lib/security/cacerts...
Opening connection to www.cebbank.com:443...
Starting SSL handshake...

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
  at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1731)
  at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
  at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
  at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
  at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
  at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
  at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
  at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:925)
  at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)
  at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)
  at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)
  at InstallCert.main(InstallCert.java:102)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: 
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
  at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
  at sun.security.validator.Validator.validate(Validator.java:218)
  at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
  at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
  at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:198)
  at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1198)
  ... 8 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
  at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
  ... 14 more

Server sent 1 certificate(s):

 1 Subject CN=www.cebbank.com, OU=Terms of use at www.verisign.com/rpa (c)05, OU=CEB, O="China Everbright Bank Co., Ltd", L=Beijing
   Issuer  CN=VeriSign Class 3 Extended Validation SSL CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network
   sha1    5b d2 85 6e b3 a4 2b 07 a2 13 47 b3 be 3e 1f c9 d3 ce 46 57 
   md5     05 d8 ae ee f1 d9 51 63 6d 2f 11 e0 ac d0 e7 d7 

Enter certificate to add to trusted keystore or 'q' to quit: [1]

  然后输入 1 并回车,会看到类似下面的打印信息

[
[
  Version: V3
  Subject: CN=service.uvpan.com
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

  Key:  Sun RSA public key, 2048 bits
  modulus: 231788198608876119472114482789500949944227474346827557770462853229741747853549763950620726235232342519069911673680471226497
634308961543332172169137368578604955021528942246111911815409088185549136660837904968530263770617490825071029281708805581287573146382156
988547125413531430759608525852511318423406844445234168173367907113071152809771040697029566469752955209390398103399068938288619962718137
3674868501753185286836657606758066747142393165835640040523017880256030555956691753813436498142943955042622976588004799964700139167420116
5072543279163545224784152093458502039083825500983120089499582892294317486244911305201899
  public exponent: 65537
  Validity: [From: Wed Jun 22 15:36:32 CST 2016,
               To: Fri Jun 22 15:36:32 CST 2018]
  Issuer: CN=WoSign CA Free SSL Certificate G2, O=WoSign CA Limited, C=CN
  SerialNumber: [    4c4a82ba 115c1eed fd6861f6 e8e6c15d]

Certificate Extensions: 9
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
  [
   accessMethod: ocsp
   accessLocation: URIName: http://ocsp1.wosign.com/ca6/server1/free
,
   accessMethod: caIssuers
   accessLocation: URIName: http://aia1.wosign.com/ca6.server1.free.cer
]
]

[2]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: D2 A7 16 20 7C AF D9 95   9E EB 43 0A 19 F2 E0 B9  ... ......C.....
0010: 74 0E A8 C7                                        t...
]
]

[3]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
  CA:false
  PathLen: undefined
]

[4]: ObjectId: 2.5.29.31 Criticality=false
CRLDistributionPoints [
  [DistributionPoint:
     [URIName: http://crls1.wosign.com/ca6-server1-free.crl]
]]

[5]: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
  [CertificatePolicyId: [2.23.140.1.2.1]
[]  ]
  [CertificatePolicyId: [1.3.6.1.4.1.36305.1.1.2]
[PolicyQualifierInfo: [
  qualifierID: 1.3.6.1.5.5.7.2.1
  qualifier: 0000: 16 1D 68 74 74 70 3A 2F   2F 77 77 77 2E 77 6F 73  ..http://www.wos
0010: 69 67 6E 2E 63 6F 6D 2F   70 6F 6C 69 63 79 2F     ign.com/policy/

]]  ]
]

[6]: ObjectId: 2.5.29.37 Criticality=false
ExtendedKeyUsages [
  clientAuth
  serverAuth
]

[7]: ObjectId: 2.5.29.15 Criticality=true
KeyUsage [
  DigitalSignature
  Key_Encipherment
]

[8]: ObjectId: 2.5.29.17 Criticality=false
SubjectAlternativeName [
  DNSName: service.uvpan.com
]

[9]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 41 1E C2 CA C5 C6 DE 3A   19 02 3B 0B EE 3B 22 09  A......:..;..;".
0010: 76 43 C3 56                                        vC.V
]
]

]
  Algorithm: [SHA256withRSA]
  Signature:
0000: 2C AC BE 2D 4A 38 2F 1F   AE 80 38 F3 64 7B 58 BF  ,..-J8/...8.d.X.
0010: B9 91 8C B6 59 09 42 95   9A BE 50 FD 22 A9 13 DA  ....Y.B...P."...
0020: C2 ED 6B 32 88 DB E2 A6   A1 1C 96 A0 02 B7 1D 2E  ..k2............
0030: 93 9C B7 6C BB F3 FB 92   AF F6 3E 71 5A 0B A5 89  ...l......>qZ...
0040: 46 1F 4F 5F 06 6B 0B FF   77 B2 B2 E2 31 CA 09 86  F.O_.k..w...1...
0050: 78 64 A6 2B DA A1 8D EA   93 DF E8 BB CF F3 55 F9  xd. ..........U.
0060: 10 B0 BA 8D D2 04 7A EB   D4 66 12 D6 03 86 65 D8  ......z..f....e.
0070: 2A 55 EB 6A 92 28 98 52   B8 BC A0 8A 66 EF FE E5  *U.j.(.R....f...
0080: 48 1A 01 9B 14 CB D9 66   62 1C 22 D5 5A C1 00 05  H......fb.".Z...
0090: 00 8C 48 63 F2 E8 42 A8   3D 66 38 FC F0 5A B3 36  ..Hc..B.=f8..Z.6
00A0: C9 47 C1 13 2A CC 06 71   AB 28 28 04 66 80 11 FE  .G..*..q.((.f...
00B0: F6 C0 97 45 85 6B B9 EC   6A 7C E8 EF AD 95 F4 EC  ...E.k..j.......
00C0: BF FF 95 39 D0 45 EB CD   29 E0 84 45 7A 29 F0 B0  ...9.E..)..Ez)..
00D0: 9C F8 E2 72 F7 50 8C AF   FE 9D F5 1E 78 A9 06 A9  ...r.P......x...
00E0: F5 7E 6D B7 AF B2 72 D7   C9 5C FD FC 41 95 FA 1D  ..m...r....A...
00F0: E8 AC D5 1C 52 86 67 3D   56 56 A5 B9 87 38 86 20  ....R.g=VV...8.

]

Added certificate to keystore 'jssecacerts' using alias 'service.uvpan.com-1'

  

同时我们会在当前目录下发现已经生成了一个名为jssecacerts的证书

再将名为jssecacerts的证书拷贝\%JAVA_HONME%\jre\lib\security\目录中

最后重启下应用的服务,证书就会生效了,就可以正常发送请求了(重启tomcat就可以了)。。 

 

 

path building failed) 问题 unable to find valid certification path to requested target,certification 最近在写java的一个服务,需要给远程服务器发...

springMVC分页,interceptor实现,springmvc分页实现

PageInterceptor.java

@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PageInterceptor implements Interceptor {
    private static final Logger logger = Logger
            .getLogger(PageInterceptor.class);
    private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    private static String defaultPageSqlId = ".*Page$"; // 需要拦截的ID(正则匹配)
    private static String pageSqlId = ""; // 需要拦截的ID(正则匹配)

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation
                .getTarget();
        MetaObject metaStatementHandler = MetaObject.forObject(
                statementHandler, DEFAULT_OBJECT_FACTORY,
                DEFAULT_OBJECT_WRAPPER_FACTORY);
        // 分离代理对象链(由于目标类可能被多个拦截器拦截,从而形成多次代理,通过下面的两次循环可以分离出最原始的的目标类)
        while (metaStatementHandler.hasGetter("h")) {
            Object object = metaStatementHandler.getValue("h");
            metaStatementHandler = MetaObject.forObject(object,
                    DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
        }
        // 分离最后一个代理对象的目标类
        while (metaStatementHandler.hasGetter("target")) {
            Object object = metaStatementHandler.getValue("target");
            metaStatementHandler = MetaObject.forObject(object,
                    DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
        }
        Configuration configuration = (Configuration) metaStatementHandler
                .getValue("delegate.configuration");
        Properties properties = configuration.getVariables();
        if (null != properties
                && StringUtils.isNotBlank(properties.getProperty("pageSqlId"))) {
            pageSqlId = properties.getProperty("pageSqlId");
        } else {
            pageSqlId = defaultPageSqlId;
        }

        MappedStatement mappedStatement = (MappedStatement) metaStatementHandler
                .getValue("delegate.mappedStatement");
        // 只重写需要分页的sql语句。通过MappedStatement的ID匹配,默认重写以Page结尾的MappedStatement的sql
        if (mappedStatement.getId().matches(pageSqlId)) {
            BoundSql boundSql = (BoundSql) metaStatementHandler
                    .getValue("delegate.boundSql");
            Object parameterObject = boundSql.getParameterObject();

            if (parameterObject == null) {
                throw new NullPointerException("parameterObject is null!");
            }
            Map<String, Object> paramMap = (Map) parameterObject;

            PageParameter page = (PageParameter) paramMap.get("0");
            String sql = boundSql.getSql();
            // 重写sql
            String pageSql = buildPageSqlForMysql(sql, page);
            metaStatementHandler.setValue("delegate.boundSql.sql", pageSql);
            // 采用物理分页后,就不需要mybatis的内存分页了,所以重置下面的两个参数
            metaStatementHandler.setValue("delegate.rowBounds.offset",
                    RowBounds.NO_ROW_OFFSET);
            metaStatementHandler.setValue("delegate.rowBounds.limit",
                    RowBounds.NO_ROW_LIMIT);
            Connection connection = (Connection) invocation.getArgs()[0];
            // 重设分页参数里的总页数等
            setPageParameter(sql, connection, mappedStatement, boundSql, page);
        }
        // 将执行权交给下一个拦截器
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // 当目标类是StatementHandler类型时,才包装目标类,否者直接返回目标本身,减少目标被代理的次数
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub

    }

    /**
     * mysql的分页语句
     * 
     * @param sql
     * @param page
     * @return String
     */
    public String buildPageSqlForMysql(String sql, PageParameter page) {
        StringBuilder pageSql = new StringBuilder(100);
        String beginrow = String.valueOf((page.getCurrentPage() - 1)
                * page.getPageSize());
        pageSql.append(sql);
        pageSql.append(" limit "   beginrow   ","   page.getPageSize());
        return pageSql.toString();
    }

    private void setPageParameter(String sql, Connection connection,
            MappedStatement mappedStatement, BoundSql boundSql,
            PageParameter page) {
        // 记录总记录数
        String countSql = "select count(0) from ("   sql   ") as total";
        PreparedStatement countStmt = null;
        ResultSet rs = null;
        try {
            countStmt = connection.prepareStatement(countSql);
            BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),
                    countSql, boundSql.getParameterMappings(),
                    boundSql.getParameterObject());
            setParameters(countStmt, mappedStatement, countBS,
                    boundSql.getParameterObject());
            rs = countStmt.executeQuery();
            int totalCount = 0;
            if (rs.next()) {
                totalCount = rs.getInt(1);
            }
            page.setTotalCount(totalCount);
            int totalPage = totalCount / page.getPageSize()
                      ((totalCount % page.getPageSize() == 0) ? 0 : 1);
            page.setTotalPage(totalPage);

        } catch (SQLException e) {
            logger.error("Ignore this exception", e);
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error("Ignore this exception", e);
            }
            try {
                countStmt.close();
            } catch (SQLException e) {
                logger.error("Ignore this exception", e);
            }
        }

    }

    private void setParameters(PreparedStatement ps,
            MappedStatement mappedStatement, BoundSql boundSql,
            Object parameterObject) throws SQLException {
        ParameterHandler parameterHandler = new DefaultParameterHandler(
                mappedStatement, parameterObject, boundSql);
        parameterHandler.setParameters(ps);
    }
}

PageParameter.java

public class PageParameter {
    public static final int DEFAULT_PAGE_SIZE = 10;

    private int pageSize;
    private int currentPage;
    private int prePage;
    private int nextPage;
    private int totalPage;
    private int totalCount;

    public PageParameter() {
        this.currentPage = 1;
        this.pageSize = DEFAULT_PAGE_SIZE;
    }

    /**
     * 
     * @param currentPage
     * @param pageSize
     */
    public PageParameter(int currentPage, int pageSize) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPrePage() {
        return prePage;
    }

    public void setPrePage(int prePage) {
        this.prePage = prePage;
    }

    public int getNextPage() {
        return nextPage;
    }

    public void setNextPage(int nextPage) {
        this.nextPage = nextPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

mybatis-config.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <plugin interceptor="*.*.PageInterceptor"></plugin>
    </plugins>
</configuration>

使用:

Map<String, Object> paramMap = new HashMap<String, Object>();
        PageParameter pageParameter = new PageParameter();
        pageParameter.setCurrentPage(10000);
        userService.findUserPage(pageParameter, null);

 

PageInterceptor.java @Intercepts({ @Signature(type = StatementHandler. class , method = "prepare", args = { Connection....

本文由新金沙平台发布于新金沙平台,转载请注明出处:springmvc分页实现,java如何调用webservice接口

关键词: 新金沙平台 金沙js333娱乐场