Monday, November 15, 2010

troubleshooting procedure for Spring + Hessian

1) How to get HttpServletRequest object so as to call getRemoteAddr()


There is a request from client to restrict a limit of machines' IPs to access the web service developed by spring and hessian.
Definitely, There is no out-of-the-box function for Spring or Hessian to open HttpServletRequest to use.
Some smart guys have found some ways to resolve this problem.


Solution 1) modify the Hessian source code
refer to http://www.blogjava.net/Caixiaopig/archive/2007/08/03/134287.aspx


Solution 2) develop a customized HessianExporter
refer to http://wesee.javaeye.com/blog/663876


I prefer the second solution.


// HessianContext.java
package com.spring.hessian.test.exporter;

import javax.servlet.ServletRequest;

public class HessianContext {
    private ServletRequest _request;
    private static final ThreadLocal<HessianContext> _localContext = new ThreadLocal<HessianContext>() {

        public HessianContext initialValue() {
            return new HessianContext();
        }
    };

    private HessianContext() {
    }

    public static void setRequest(ServletRequest request) {
        _localContext.get()._request = request;
    }

    public static ServletRequest getRequest() {
        return _localContext.get()._request;
    }

    public static void clear() {
        _localContext.get()._request = null;
    }
}


// customized Hessian Exporter
package com.spring.hessian.test.exporter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.remoting.caucho.HessianExporter;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.util.NestedServletException;

public class MyExporter extends HessianExporter implements HttpRequestHandler {

    @Override
    public void handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        if (!"POST".equals(request.getMethod())) {
            throw new HttpRequestMethodNotSupportedException(request
                    .getMethod(), new String[] { "POST" },
                    "HessianServiceExporter only supports POST requests");
        }

        response.setContentType(CONTENT_TYPE_HESSIAN);
        try {
           
            String clientIp = request.getRemoteAddr();
            System.out.println("----------->>> "+clientIp);
           
            if (!clientIp.equalsIgnoreCase("10.12.103.118")){
                throw new Exception("Invalid IP-----------------------");
            }
           
            HessianContext.setRequest(request);
            invoke(request.getInputStream(), response.getOutputStream());
        } catch (Throwable ex) {
             throw e;
        } finally {
            HessianContext.clear();
        }

    }
}
// your <servlet-name>-servlet.xml
 take note the class name in red, should put your customized hessian exporter class,not standard one
<bean name="/onepassService"
        class="com.spring.hessian.test.exporter.MyExporter">
        <property name="service" ref="accountInfoImpl" />
        <property name="serviceInterface" value="com.spring.hessian.test.IAccountInfo" />
 </bean>


I wonder how this guy worked it out !  :-(


2) can not get Spring Bean if using auto classpath scan

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="order" value="1" />
    </bean>

    <bean
        class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
        <property name="defaultHandler" ref="httpRequestHandlerAdapter" />
        <property name="order" value="2" />
    </bean>

    <bean id="httpRequestHandlerAdapter"
        class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />

    <context:component-scan base-package="com.spring.hessian.test" />

</beans>

The three beans definition are required, otherwise, NullPointerException will occur due to system can not find the spring beans if adopting annotation to define spring bean.

3) setup SSL connection

3.1 generate keystore


keytool -genkeypair -keyalg RSA -keysize 2048 -sigalg SHA1withRSA -validity 36000 -storepass changeit -alias myalias -keystore my.keystore -dname "CN=localhost,OU=mycomp,O=mycomp,L=SG,ST=SG,C=SG"


TAKE NOTE: set the value of CN carefully. if set CN=myhost, the URL of hessian servlet would be
https://myhost:port/xxxxxxxx


3.2 configure SSL connection in tomcat


edit %tomcat%/conf/server.xml and add following configuration


<Connector port="8843" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="C:/tmp/my.keystore" keystorePass="changeit" />


3.3 export cert for client side


keytool -exportcert -alias myalias -keystore my.keystore -file my.pem -rfc -storepass changeit


3.4 import cert to client's trust store


keytool -import -trustcacerts  -alias mycert_tomcat -file c:\tmp\my.pem  -keystore  cacerts


3.5 client caller source code


package com.spring.hessian.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.caucho.hessian.client.HessianProxyFactory;

public class HessianTester {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void test() throws Exception {
        System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
        System.setProperty("javax.net.ssl.trustStore", "C:\\tmp\\cacerts");
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
     
         String url = "https://localhost:8843/springhessian/remote/myService";
        HessianProxyFactory factory = new HessianProxyFactory();
        IAccountInfo accountInfo = (IAccountInfo) factory.create(
                IAccountInfo.class, url);

        accountInfo.changeEmail(126, "def@email.com");
        accountInfo.deleteAccount(129);
    }
}


take note the property in red, previously, I set it as keyStore and always got the exception as follows.


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(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 38 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 44 more

Monday, November 8, 2010

Spring v3.0.2 Learning Note 16 (Cont.)- Resolve NullPointerException on weblogic v10.3

In this article http://wangxiangblog.blogspot.com/2010/10/spring-v302-learning-note-16-integrate.html, I mentioned that NullPointerException occured if deployed hessian project to weblogic v10.3

After seach oracle website, found the info as follows
---------------------------------------------------------------------------------------------------
After some research on the stack trace, I found the reason for this error is Hession Spring servlet closes the input stream explicitly. While when WLS' reclaiming the connection for reuse(keep-alive) purpose, it tries to read the input stream to clear unread chunks. NPE happens here as input stream has been closed.

There is an existing bug on this: Bug 8183755. Patches are available for bug  8183755:

------------------------------------------
    PATCH REPOSITORY INFORMATION
------------------------------------------
 WLS Version | Patch ID |  Passcode
--------------+----------+----------------
    9.2 GA   |   K75X   | K3EB5V7M
    9.2 MP1  |   H67L   | HZYJQECN
    9.2 MP2  |   T4HG   | MJ95CPML
    9.2 MP3  |   RZCZ   | M3IEQWIP
    10.0MP1  |   2JNU   | HX9YYCA7
    10.3 GA  |   2UZ1   | I74ATQ1X

Fixed in: 10.3.1

To apply one of these patches, download the patch using Smart Update and apply: see Note  885851.1 for step-by-step instructions. If your target system is offline, please refer to Note  876004.1 for additional assistance. All the details about SmartUpdate are available in the SmartUpdate  documentation.

Patches are specifically tied to a particular release and maintenance  pack of WebLogic Server (WLS). A patch for WLS 9.2.2, for example, very  likely would not work on WLS 9.2.3. In a few cases, patches are also specific to particular operating systems. If you think you are experiencing the problem outlined in this note, but your WLS version is not included in the list of patches provided here, please contact support and ask for a version of the patch appropriate for you. Please reference this note as well as this bug number to help speed our service  for you.
----------------------------------------------------------------------------------------------------

The following commands are used to apply the patch on weblogic v10.3.
Before running these commands, need to copy 2UZ1.jar and patch-catalog.xml to folder D:\bea\utils\bsu\cache_dir

//// view the patch info
D:\bea\utils\bsu>bsu -prod_dir=D:\bea\wlserver_10.3 -patch_download_dir=D:\bea\utils\bsu\cache_dir -status=downloaded -view -verbose
ProductName:       WebLogic Server
ProductVersion:    10.3
Components:        WebLogic Server/Core Application Server,WebLogic Server/Admi
                   nistration Console,WebLogic Server/Configuration Wizard and
                   Upgrade Framework,WebLogic Server/Web 2.0 HTTP Pub-Sub Serve
                   r,WebLogic Server/WebLogic JDBC Drivers,WebLogic Server/Thir
                   d Party JDBC Drivers,WebLogic Server/WebLogic Server Clients
                   ,WebLogic Server/WebLogic Web Server Plugins,WebLogic Server
                   /UDDI and Xquery Support,WebLogic Server/Server Examples,Web
                   Logic Server/Evaluation Database,WebLogic Server/Workshop Co
                   de Completion Support
BEAHome:           D:\bea
ProductHome:       D:\bea\wlserver_10.3
PatchSystemDir:    D:\bea\utils\bsu
PatchDir:          D:\bea\patch_wls1030
Profile:           Default
DownloadDir:       D:\bea\utils\bsu\cache_dir
JavaHome:          D:\bea\jdk160_05
JavaVersion:       1.6.0_05
JavaVendor:        Sun


Patch ID:          2UZ1
PatchContainer:    2UZ1.jar
Checksum:          -2128224792
Severity:          optional
Category:          Web App
CR:                CR371433,CR385319
Restart:           true
Description:       Fixed NPE when ServletInputStream is closed explicitly.

//// apply the patch
D:\bea\utils\bsu>bsu -prod_dir=D:\bea\wlserver_10.3 -patchlist=2UZ1 -verbose -install
Checking for conflicts..
No conflict(s) detected

Starting installation of Patch ID: 2UZ1
Installing D:\bea\utils\bsu\cache_dir\2UZ1.jar
Extracting D:\bea\patch_wls1030\patch_jars\CR371433_1030ga.jar
Updating D:\bea\patch_wls1030\profiles\default\sys_manifest_classpath\weblogic_patch.jar
Old manifest value: Class-Path=
New manifest value: Class-Path=../../../patch_jars/CR371433_1030ga.jar
Result: Success

///// verify the patch
D:\bea\utils\bsu>bsu -prod_dir=D:\bea\wlserver_10.3 -status=applied -view -verbose
ProductName:       WebLogic Server
ProductVersion:    10.3
Components:        WebLogic Server/Core Application Server,WebLogic Server/Admi
                   nistration Console,WebLogic Server/Configuration Wizard and
                   Upgrade Framework,WebLogic Server/Web 2.0 HTTP Pub-Sub Serve
                   r,WebLogic Server/WebLogic JDBC Drivers,WebLogic Server/Thir
                   d Party JDBC Drivers,WebLogic Server/WebLogic Server Clients
                   ,WebLogic Server/WebLogic Web Server Plugins,WebLogic Server
                   /UDDI and Xquery Support,WebLogic Server/Server Examples,Web
                   Logic Server/Evaluation Database,WebLogic Server/Workshop Co
                   de Completion Support
BEAHome:           D:\bea
ProductHome:       D:\bea\wlserver_10.3
PatchSystemDir:    D:\bea\utils\bsu
PatchDir:          D:\bea\patch_wls1030
Profile:           Default
DownloadDir:       D:\bea\utils\bsu\cache_dir
JavaHome:          D:\bea\jdk160_05
JavaVersion:       1.6.0_05
JavaVendor:        Sun


Patch ID:          2UZ1
PatchContainer:    2UZ1.jar
Checksum:          -2128224792
Severity:          optional
Category:          Web App
CR:                CR371433,CR385319
Restart:           true
Description:       Fixed NPE when ServletInputStream is closed explicitly.


Wednesday, October 27, 2010

Logging and Spring AOP

Problem

Normally, we log down the values of parameters of a method and the value of return of a method. For example,

public class MyClass {

      public YYY getSomething(int id, Object obj) {
             log.debug ("para[id]="+id+",para[obj]="+obj);
             // do something, then return object YYY
             log.debug("return value : "+YYY);
             return YYY;
     }

}

We can log down the relative information with spring AOP. It is not necessary to log down something in each methods.

Configuration

prepare the spring configuration as follows.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:component-scan base-package="com.spring.test" />

    <aop:aspectj-autoproxy />

    <bean id="personAopImpl" class="com.spring.test.aop.PersonAopImpl" />
    <bean id="personAopProxy" class="com.spring.test.aop.PersonAopProxy" />
  
</beans>

Reference Library

add the following reference library files to your project. you can get them from spring v3.0.2 dist package and its dependency package.

com.springsource.javax.annotation-1.0.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.aspectj.tools-1.6.6.RELEASE.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
org.springframework.aop-3.0.2.RELEASE.jar
org.springframework.asm-3.0.2.RELEASE.jar
org.springframework.beans-3.0.2.RELEASE.jar
org.springframework.context-3.0.2.RELEASE.jar

org.springframework.context.support-3.0.2.RELEASE.jar
org.springframework.core-3.0.2.RELEASE.jar
org.springframework.expression-3.0.2.RELEASE.jar

Source Code

// there are two POJO classes
package com.spring.test.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import java.util.Map;

public class Address {

    private static final long serialVersionUID = -872400794860227364L;
    private int floor;
    private String unit;

    public Address() {
        super();
    }

    public Address(int floor, String unit) {
        super();
        this.floor = floor;
        this.unit = unit;
    }

    public int getFloor() {
        return floor;
    }

    public void setFloor(int floor) {
        this.floor = floor;
    }

    public String getUnit() {
        return unit;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }

    public String toString() {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            if (fields != null) {
                for (Field f : fields) {
                    if (Modifier.isPrivate(f.getModifiers())
                            || Modifier.isProtected(f.getModifiers())) {
                        f.setAccessible(true);
                    } else {
                        continue;
                    }

                    map.put(f.getName(), f.get(this));
                }
            }
        } catch (Exception e) {
        }
        return map.toString();
    }
}
=====================================================
package com.spring.test.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class PersonInfo {

    private static final long serialVersionUID = 1552674486660927122L;
    private int id;
    private String name;
    private List<String> mobilePhone;
    private List<Address> addressList;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getMobilePhone() {
        return mobilePhone;
    }

    public void setMobilePhone(List<String> mobilePhone) {
        this.mobilePhone = mobilePhone;
    }

    public List<Address> getAddressList() {
        return addressList;
    }

    public void setAddressList(List<Address> addressList) {
        this.addressList = addressList;
    }

    public String toString() {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            if (fields != null) {
                for (Field f : fields) {
                    if (Modifier.isPrivate(f.getModifiers())
                            || Modifier.isProtected(f.getModifiers())) {
                        f.setAccessible(true);
                    } else {
                        continue;
                    }

                    map.put(f.getName(), f.get(this));
                }
            }
        } catch (Exception e) {
        }
        return map.toString();
    }
}
=======================================================
// interface class
package com.spring.test.aop;

public interface IPersonAop {
    public void sayHello() throws Throwable;
    public void sayHello2() throws Throwable;
    public boolean createPersonInfo(PersonInfo info, int id);
    public PersonInfo getPersonInfo(int id);
}
=======================================================
// implement class
package com.spring.test.aop;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class PersonAopImpl implements IPersonAop {

    @Override
    public void sayHello() throws Throwable {
        System.out.println("Hello !!");
        throw new Exception("throw out exception in sayHello().");
    }
   
    @Override
    public void sayHello2() throws Throwable {
        System.out.println("Hello2 !!");
    }

    @Override
    public boolean createPersonInfo(PersonInfo info, int id) {
        info.setId(id);
        System.out.println("creating person information " + info);
        return true;
    }

    @Override
    public PersonInfo getPersonInfo(int id) {
        Address addr1 = new Address(15, "-101");
        Address addr2 = new Address(19, "-204");
        List<Address> addr = new ArrayList<Address>();
        addr.add(addr1);
        addr.add(addr2);
        PersonInfo info = new PersonInfo();
        info.setAddressList(addr);
        info.setName("testname2");
        List<String> mobile = new ArrayList<String>();
        mobile.add("999999");
        mobile.add("888888");
        info.setMobilePhone(mobile);
        info.setId(id);
        return info;
    }
}
========================================================
// Junit class
package com.spring.test.junit;

import java.util.ArrayList;
import java.util.List;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.test.aop.Address;
import com.spring.test.aop.IPersonAop;
import com.spring.test.aop.PersonInfo;

public class AopTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "spring.xml");
        IPersonAop aop = (IPersonAop) ctx.getBean("personAopImpl");
        try {
            aop.sayHello2();
            aop.sayHello();
        } catch (Throwable e) {
        }

        Address addr1 = new Address(12, "-01");
        Address addr2 = new Address(13, "-04");
        List<Address> addr = new ArrayList<Address>();
        addr.add(addr1);
        addr.add(addr2);
        PersonInfo info = new PersonInfo();
        info.setAddressList(addr);
        info.setName("testname");
        List<String> mobile = new ArrayList<String>();
        mobile.add("222222");
        mobile.add("333333");
        info.setMobilePhone(mobile);
        aop.createPersonInfo(info, 40);

        aop.getPersonInfo(18);
    }
}
=================================================================
// this is proxy class, it is important
package com.spring.test.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class PersonAopProxy {

    @Before("execution (* com.spring.test.aop..*.*(..))")
    public void logBeforeMethodRunning(JoinPoint joinPoint) {
        StringBuilder sb = new StringBuilder();
        sb.append("--- Begin to call "
                + joinPoint.getTarget().getClass().getName() + "."
                + joinPoint.getSignature().getName() + "() ");

        Object[] objs = joinPoint.getArgs();
        if (objs == null || objs.length == 0)
            sb.append("Without Parameter");
        else {
            int i = 0;
            while (i < objs.length) {
                sb.append(" para" + (i + 1) + "["
                        + objs[i].getClass().getSimpleName() + "]=" + objs[i]);
                i++;
            }
        }

        System.out.println(sb.toString());
    }

    @AfterReturning(pointcut = "execution (* com.spring.test.aop..*.*(..))", returning = "result")
    public void logAfterMethodRunning(JoinPoint joinPoint, Object result)
            throws Throwable {

        StringBuilder sb = new StringBuilder();

        sb.append("--- End to call "
                + joinPoint.getTarget().getClass().getName() + "."
                + joinPoint.getSignature().getName() + "() ");

        Object[] objs = joinPoint.getArgs();
        if (objs == null || objs.length == 0)
            sb.append("Without Parameter");
        else {
            int i = 0;
            while (i < objs.length) {
                sb.append(" para" + (i + 1) + "["
                        + objs[i].getClass().getSimpleName() + "]=" + objs[i]);
                i++;
            }
        }
        sb.append(" <return> " + result);
        System.out.println(sb.toString());
    }

    @AfterThrowing(pointcut = "execution (* com.spring.test.aop..*.*(..))", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        StringBuilder sb = new StringBuilder();

        sb.append("--- End to call "
                + joinPoint.getTarget().getClass().getName() + "."
                + joinPoint.getSignature().getName() + "() ");

        Object[] objs = joinPoint.getArgs();
        if (objs == null || objs.length == 0)
            sb.append("Without Parameter");
        else {
            int i = 0;
            while (i < objs.length) {
                sb.append(" para" + (i + 1) + "["
                        + objs[i].getClass().getSimpleName() + "]=" + objs[i]);
                i++;
            }
        }
        sb.append(" <Exception> " + e);
        System.out.println(sb.toString());
    }
}


Before Advices
To create a before advice to handle crosscutting concerns before particular program execution points,you use the @Before annotation and include the pointcut expression as the annotation value.
@Before("execution(* *.*(..))")
 
This pointcut expression (* com.spring.test.aop..*.*(..) matches the any method execution under package com.spring.test.aop and its sub-package.The preceding wildcard in this expression matches any modifier (public, protected, and private) and any return type. The two dots in the argument list match any number of arguments.

To register this aspect, you just declare a bean instance of it in the IoC container. The aspect bean may even be anonymous if there’s no reference from other beans.
<bean id="personAopProxy" class="com.spring.test.aop.PersonAopProxy" />

After Advices
An after advice is executed after a join point finishes, whenever it returns a result or throws an exception
abnormally.
@After("execution(* *.*(..))")


After Returning Advices
An after advice is executed regardless of whether a join point returns normally. If you want to perform logging only when a join point returns, you should replace the after advice with an after returning advice.
@AfterReturning("execution(* *.*(..))")
or
@AfterReturning(pointcut = "execution(* *.*(..))", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result)

After Throwing Advices
An after throwing advice is executed only when an exception is thrown by a join point.
@AfterThrowing("execution(* *.*(..))")
or
@AfterThrowing(pointcut = "execution(* *.*(..))", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e)

Around Advices
It is the most powerful of all the advice types. It gains full control of a join point, so you can combine all the actions of the preceding advices into one single advice. You can even control when, and whether, to proceed with the original join point execution.
The following around advice is the combination of the before, after returning, and after throwing advices you created before. Note that for an around advice, the argument type of the join point must be ProceedingJoinPoint. It’s a subinterface of JoinPoint that allows you to control when to proceed with the original join point.

@Around("execution(* *.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
       log.info("The method " + joinPoint.getSignature().getName()
                   + "() begins with " + Arrays.toString(joinPoint.getArgs()));
       try {
                Object result = joinPoint.proceed();
                log.info("The method " + joinPoint.getSignature().getName()+ "() ends with " + result);
                return result;
        } catch (IllegalArgumentException e) {
                log.error("Illegal argument " + Arrays.toString(joinPoint.getArgs())
                              + " in "+joinPoint.getSignature().getName() + "()");
            throw e;
        }
}


Reference Book
Apress.Spring.Enterprise.Recipes.A.Problem.Solution.Approach, written by Gary Mak and Josh Long

Monday, October 25, 2010

Spring工具类-特殊字符转义和方法入参检测工具类

转载自http://www.ibm.com/developerworks/cn/java/j-lo-spring-utils2/


简介:
Spring 不但提供了一个功能全面的应用开发框架,本身还拥有众多可以在程序编写时直接使用的工具类,您不但可以在 Spring 应用中使用这些工具类,也可以在其它的应用中使用,这些工具类中的大部分是可以在脱离 Spring 框架时使用的。了解 Spring 中有哪些好用的工具类并在程序编写时适当使用,将有助于提高开发效率、增强代码质量。


特殊字符转义
由于 Web 应用程序需要联合使用到多种语言,每种语言都包含一些特殊的字符,对于动态语言或标签式的语言而言,如果需要动态构造语言的内容时,一个我们经常会碰到的问题就是特殊字符转义的问题。下面是 Web 开发者最常面对需要转义的特殊字符类型:
  • HTML 特殊字符;
  • JavaScript 特殊字符;
  • SQL 特殊字符;
如果不对这些特殊字符进行转义处理,则不但可能破坏文档结构,还可以引发潜在的安全问题。Spring 为 HTML 和 JavaScript 特殊字符提供了转义操作工具类,它们分别是 HtmlUtils 和 JavaScriptUtils。
HTML 特殊字符转义
HTML 中 <,>,& 等字符有特殊含义,它们是 HTML 语言的保留字,因此不能直接使用。使用这些个字符时,应使用它们的转义序列:
  • &:&amp;
  • " :&quot;
  • < :&lt;
  • > :&gt;
由 于 HTML 网页本身就是一个文本型结构化文档,如果直接将这些包含了 HTML 特殊字符的内容输出到网页中,极有可能破坏整个 HTML 文档的结构。所以,一般情况下需要对动态数据进行转义处理,使用转义序列表示 HTML 特殊字符。下面的 JSP 网页将一些变量动态输出到 HTML 网页中:

清单 1. 未进行 HTML 特殊字符转义处理网页
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%!
   String userName = "</td><tr></table>";
   String address = " \" type=\"button";
 %>
<table border="1">
   <tr>
     <td>姓名:</td><td><%=userName%></td> ①
   </tr>
   <tr>
     <td>年龄:</td><td>28</td>
   </tr>
</table>
 <input value="<%=address%>"  type="text" /> ②

在 ① 和 ② 处,我们未经任何转义处理就直接将变量输出到 HTML 网页中,由于这些变量可能包含一些特殊的 HTML 的字符,它们将可能破坏整个 HTML 文档的结构。我们可以从以上 JSP 页面的一个具体输出中了解这一问题:
<table border="1">
   <tr>
     <td>姓名:</td><td></td><tr></table></td> 
     ① 破坏了 <table> 的结构
   </tr>
   <tr>
     <td>年龄:</td><td>28</td>
   </tr>
</table>
 <input value=" " type="button"  type="text" /> 
 ② 将本来是输入框组件偷梁换柱为按钮组件

融合动态数据后的 HTML 网页已经面目全非,首先 ① 处的 <table> 结构被包含 HTML 特殊字符的 userName 变量截断了,造成其后的 <table> 代码变成无效的内容;其次,② 处 <input> 被动态数据改换为按钮类型的组件(type="button")。为了避免这一问题,我们需要事先对可能破坏 HTML 文档结构的动态数据进行转义处理。Spring 为我们提供了一个简单适用的 HTML 特殊字符转义工具类,它就是 HtmlUtils。下面,我们通过一个简单的例子了解 HtmlUtils 的具体用法:

清单 2. HtmpEscapeExample
package com.baobaotao.escape;
import org.springframework.web.util.HtmlUtils;
public class HtmpEscapeExample {
    public static void main(String[] args) {
        String specialStr = "<div id=\"testDiv\">test1;test2</div>";
        String str1 = HtmlUtils.htmlEscape(specialStr); ①转换为HTML转义字符表示
        System.out.println(str1);
       
        String str2 = HtmlUtils.htmlEscapeDecimal(specialStr); ②转换为数据转义表示
        System.out.println(str2);
       
        String str3 = HtmlUtils.htmlEscapeHex(specialStr); ③转换为十六进制数据转义表示
        System.out.println(str3);
       
        ④下面对转义后字符串进行反向操作
        System.out.println(HtmlUtils.htmlUnescape(str1));
        System.out.println(HtmlUtils.htmlUnescape(str2));
        System.out.println(HtmlUtils.htmlUnescape(str3));
    }
}

HTML 不但可以使用通用的转义序列表示 HTML 特殊字符,还可以使用以 # 为前缀的数字序列表示 HTML 特殊字符,它们在最终的显示效果上是一样的。HtmlUtils 提供了三个转义方法:
方法说明
static String htmlEscape(String input)将 HTML 特殊字符转义为 HTML 通用转义序列;
static String htmlEscapeDecimal(String input)将 HTML 特殊字符转义为带 # 的十进制数据转义序列;
static String htmlEscapeHex(String input)将 HTML 特殊字符转义为带 # 的十六进制数据转义序列;
此外,HtmlUtils 还提供了一个能够将经过转义内容还原的方法:htmlUnescape(String input),它可以还原以上三种转义序列的内容。运行以上代码,您将可以看到以下的输出:
str1:&lt;div id=&quot;testDiv&quot;&gt;test1;test2&lt;/div&gt;
str2:&#60;div id=&#34;testDiv&#34;&#62;test1;test2&#60;/div&#62;
str3:&#x3c;div id=&#x22;testDiv&#x22;&#x3e;test1;test2&#x3c;/div&#x3e;
<div id="testDiv">test1;test2</div>
<div id="testDiv">test1;test2</div>
<div id="testDiv">test1;test2</div>

您只要使用 HtmlUtils 对代码清单1 的 userName 和 address 进行转义处理,最终输出的 HTML 页面就不会遭受破坏了。
JavaScript 特殊字符转义
JavaScript 中也有一些需要特殊处理的字符,如果直接将它们嵌入 JavaScript 代码中,JavaScript 程序结构将会遭受破坏,甚至被嵌入一些恶意的程序。下面列出了需要转义的特殊 JavaScript 字符:
  • ' :\'
  • " :\"
  • \ :\\
  • 走纸换页: \f
  • 换行:\n
  • 换栏符:\t
  • 回车:\r
  • 回退符:\b

我们通过一个具体例子演示动态变量是如何对 JavaScript 程序进行破坏的。假设我们有一个 JavaScript 数组变量,其元素值通过一个 Java List 对象提供,下面是完成这一操作的 JSP 代码片断:

清单 3. jsTest.jsp:未对 JavaScript 特殊字符进行处理
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<jsp:directive.page import="java.util.*"/>
<%
  List textList = new ArrayList();
  textList.add("\";alert();j=\"");
%>
<script>
  var txtList = new Array();
   <% for ( int i = 0 ; i < textList.size() ; i++) { %>
     txtList[<%=i%>] = "<%=textList.get(i)%>"; 
  ① 未对可能包含特殊 JavaScript 字符的变量进行处理
   <% } %>
</script>

当客户端调用这个 JSP 页面后,将得到以下的 HTML 输出页面:
<script>
  var txtList = new Array();
   txtList[0] = "";alert();j=""; ① 本来是希望接受一个字符串,结果被植入了一段JavaScript代码
</script>

由于包含 JavaScript 特殊字符的 Java 变量直接合并到 JavaScript 代码中,我们本来期望 ① 处所示部分是一个普通的字符串,但结果变成了一段 JavaScript 代码,网页将弹出一个 alert 窗口。想像一下如果粗体部分的字符串是“";while(true)alert();j="”时会产生什么后果呢?
因 此,如果网页中的 JavaScript 代码需要通过拼接 Java 变量动态产生时,一般需要对变量的内容进行转义处理,可以通过 Spring 的 JavaScriptUtils 完成这件工作。下面,我们使用 JavaScriptUtils 对以上代码进行改造:
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<jsp:directive.page import="java.util.*"/>
<jsp:directive.page import="org.springframework.web.util.JavaScriptUtils"/>
<%
  List textList = new ArrayList();
  textList.add("\";alert();j=\"");
%>
<script>
   var txtList = new Array();
   <% for ( int i = 0 ; i < textList.size() ; i++) { %>
   ① 在输出动态内容前事先进行转义处理
   txtList[<%=i%>] = "<%=JavaScriptUtils.javaScriptEscape(""+textList.get(i))%>";
   <% } %>
</script>

通过转义处理后,这个 JSP 页面输出的结果网页的 JavaScript 代码就不会产生问题了:
<script>
   var txtList = new Array();
   txtList[0] = "\";alert();j=\"";
   ① 粗体部分仅是一个普通的字符串,而非一段 JavaScript 的语句了
</script>

SQL特殊字符转义
应 该说,您即使没有处理 HTML 或 JavaScript 的特殊字符,也不会带来灾难性的后果,但是如果不在动态构造 SQL 语句时对变量中特殊字符进行处理,将可能导致程序漏洞、数据盗取、数据破坏等严重的安全问题。网络中有大量讲解 SQL 注入的文章,感兴趣的读者可以搜索相关的资料深入研究。
虽然 SQL 注入的后果很严重,但是只要对动态构造的 SQL 语句的变量进行特殊字符转义处理,就可以避免这一问题的发生了。来看一个存在安全漏洞的经典例子:
SELECT COUNT(userId) 
FROM t_user 
WHERE userName='"+userName+"' AND password ='"+password+"';

以上 SQL 语句根据返回的结果数判断用户提供的登录信息是否正确,如果 userName 变量不经过特殊字符转义处理就直接合并到 SQL 语句中,黑客就可以通过将 userName 设置为 “1' or '1'='1”绕过用户名/密码的检查直接进入系统了。
所 以除非必要,一般建议通过 PreparedStatement 参数绑定的方式构造动态 SQL 语句,因为这种方式可以避免 SQL 注入的潜在安全问题。但是往往很难在应用中完全避免通过拼接字符串构造动态 SQL 语句的方式。为了防止他人使用特殊 SQL 字符破坏 SQL 的语句结构或植入恶意操作,必须在变量拼接到 SQL 语句之前对其中的特殊字符进行转义处理。Spring 并没有提供相应的工具类,您可以通过 jakarta commons lang 通用类包中(spring/lib/jakarta-commons/commons-lang.jar)的 StringEscapeUtils 完成这一工作:

清单 4. SqlEscapeExample
package com.baobaotao.escape;
import org.apache.commons.lang.StringEscapeUtils;
public class SqlEscapeExample {
    public static void main(String[] args) {
        String userName = "1' or '1'='1";
        String password = "123456";
        userName = StringEscapeUtils.escapeSql(userName);
        password = StringEscapeUtils.escapeSql(password);
        String sql = "SELECT COUNT(userId) FROM t_user WHERE userName='"
            + userName + "' AND password ='" + password + "'";
        System.out.println(sql);
    }
}

事实上,StringEscapeUtils 不但提供了 SQL 特殊字符转义处理的功能,还提供了 HTML、XML、JavaScript、Java 特殊字符的转义和还原的方法。如果您不介意引入 jakarta commons lang 类包,我们更推荐您使用 StringEscapeUtils 工具类完成特殊字符转义处理的工作。

方法入参检测工具类
Web 应用在接受表单提交的数据后都需要对其进行合法性检查,如果表单数据不合法,请求将被驳回。类似的,当我们在编写类的方法时,也常常需要对方法入参进行合 法性检查,如果入参不符合要求,方法将通过抛出异常的方式拒绝后续处理。举一个例子:有一个根据文件名获取输入流的方法:InputStream getData(String file),为了使方法能够成功执行,必须保证 file 入参不能为 null 或空白字符,否则根本无须进行后继的处理。这时方法的编写者通常会在方法体的最前面编写一段对入参进行检测的代码,如下所示:
public InputStream getData(String file) {
    if (file == null || file.length() == 0|| file.replaceAll("\\s", "").length() == 0) {
        throw new IllegalArgumentException("file入参不是有效的文件地址");
    }
…
}

类似以上检测方法入参的代码是非常常见,但是在每个方法中都使用手工编写检测逻辑的方式并不是一个好主意。阅读 Spring 源码,您会发现 Spring 采用一个 org.springframework.util.Assert 通用类完成这一任务。
Assert 翻译为中文为“断言”,使用过 JUnit 的读者都熟知这个概念,它断定某一个实际的运行值和预期想一样,否则就抛出异常。Spring 对方法入参的检测借用了这个概念,其提供的 Assert 类拥有众多按规则对方法入参进行断言的方法,可以满足大部分方法入参检测的要求。这些断言方法在入参不满足要求时就会抛出 IllegalArgumentException。下面,我们来认识一下 Assert 类中的常用断言方法:
断言方法说明
notNull(Object object)当 object 不为 null 时抛出异常,notNull(Object object, String message) 方法允许您通过 message 定制异常信息。和 notNull() 方法断言规则相反的方法是 isNull(Object object)/isNull(Object object, String message),它要求入参一定是 null;
isTrue(boolean expression) / isTrue(boolean expression, String message)当 expression 不为 true 抛出异常;
notEmpty(Collection collection) / notEmpty(Collection collection, String message)当 集合未包含元素时抛出异常。notEmpty(Map map) / notEmpty(Map map, String message) 和 notEmpty(Object[] array, String message) / notEmpty(Object[] array, String message) 分别对 Map 和 Object[] 类型的入参进行判断;
hasLength(String text) / hasLength(String text, String message)当 text 为 null 或长度为 0 时抛出异常;
hasText(String text) / hasText(String text, String message)text 不能为 null 且必须至少包含一个非空格的字符,否则抛出异常;
isInstanceOf(Class clazz, Object obj) / isInstanceOf(Class type, Object obj, String message)如果 obj 不能被正确造型为 clazz 指定的类将抛出异常;
isAssignable(Class superType, Class subType) / isAssignable(Class superType, Class subType, String message)subType 必须可以按类型匹配于 superType,否则将抛出异常;
使用 Assert 断言类可以简化方法入参检测的代码,如 InputStream getData(String file) 在应用 Assert 断言类后,其代码可以简化为以下的形式:
public InputStream getData(String file){
    Assert.hasText(file,"file入参不是有效的文件地址"); 
    ① 使用 Spring 断言类进行方法入参检测
…
}

可见使用 Spring 的 Assert 替代自编码实现的入参检测逻辑后,方法的简洁性得到了不少的提高。Assert 不依赖于 Spring 容器,您可以大胆地在自己的应用中使用这个工具类。

小结
本文介绍了一些常用的 Spring 工具类,其中大部分 Spring 工具类不但可以在基于 Spring 的应用中使用,还可以在其它的应用中使用。
对 于 Web 应用来说,由于有很多关联的脚本代码,如果这些代码通过拼接字符串的方式动态产生,就需要对动态内容中特殊的字符进行转义处理,否则就有可能产生意想不到 的后果。Spring 为此提供了 HtmlUtils 和 JavaScriptUtils 工具类,只要将动态内容在拼接之前使用工具类进行转义处理,就可以避免类似问题的发生了。如果您不介意引入一个第三方类包,那么 jakarta commons lang 通用类包中的 StringEscapeUtils 工具类可能更加适合,因为它提供了更加全面的转义功能。
最后我们还介绍了 Spring 的 Assert 工具类,Assert 工具类是通用性很强的工具类,它使用面向对象的方式解决方法入参检测的问题,您可以在自己的应用中使用 Assert 对方法入参进行检查。

Spring工具类-文件资源操作和 Web 相关工具类

转载自http://www.ibm.com/developerworks/cn/java/j-lo-spring-utils1/


简介:
Spring 不但提供了一个功能全面的应用开发框架,本身还拥有众多可以在程序编写时直接使用的工具类,您不但可以在 Spring 应用中使用这些工具类,也可以在其它的应用中使用,这些工具类中的大部分是可以在脱离 Spring 框架时使用的。了解 Spring 中有哪些好用的工具类并在程序编写时适当使用,将有助于提高开发效率、增强代码质量。


文件资源操作
文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等。我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来说,JDK 的这些操作类所提供的方法过于底层,直接使用它们进行文件操作不但程序编写复杂而且容易产生错误。相比于 JDK 的 File,Spring 的 Resource 接口(资源概念的描述接口)抽象层面更高且涵盖面更广,Spring 提供了许多方便易用的资源操作工具类,它们大大降低资源操作的复杂度,同时具有更强的普适性。这些工具类不依赖于 Spring 容器,这意味着您可以在程序中象一般普通类一样使用它们。
加载文件资源
Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名、URL 地址以及资源内容的操作方法。
访问文件资源
假设有一个文件地位于 Web 应用的类路径下,您可以通过以下方式对这个文件资源进行访问:
  • 通过 FileSystemResource 以文件系统绝对路径的方式进行访问;
  • 通过 ClassPathResource 以类路径的方式进行访问;
  • 通过 ServletContextResource 以相对于 Web 应用根目录的方式进行访问。
相比于通过 JDK 的 File 类访问文件资源的方式,Spring 的 Resource 实现类无疑提供了更加灵活的操作方式,您可以根据情况选择适合的 Resource 实现类访问资源。下面,我们分别通过 FileSystemResource 和 ClassPathResource 访问同一个文件资源:

清单 1. FileSourceExample
package com.baobaotao.io; 
 import java.io.IOException; 
 import java.io.InputStream; 
 import org.springframework.core.io.ClassPathResource; 
 import org.springframework.core.io.FileSystemResource; 
 import org.springframework.core.io.Resource; 
 public class FileSourceExample { 
    public static void main(String[] args) { 
        try { 
            String filePath = 
            "D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt"; 
            // ① 使用系统文件路径方式加载文件
            Resource res1 = new FileSystemResource(filePath); 
            // ② 使用类路径方式加载文件
            Resource res2 = new ClassPathResource("conf/file1.txt"); 
            InputStream ins1 = res1.getInputStream(); 
            InputStream ins2 = res2.getInputStream(); 
            System.out.println("res1:"+res1.getFilename()); 
            System.out.println("res2:"+res2.getFilename()); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
 } 

在获取资源后,您就可以通过 Resource 接口定义的多个方法访问文件的数据和其它的信息:如您可以通过 getFileName() 获取文件名,通过 getFile() 获取资源对应的 File 对象,通过 getInputStream() 直接获取文件的输入流。此外,您还可以通过 createRelative(String relativePath) 在资源相对地址上创建新的资源。
在 Web 应用中,您还可以通过 ServletContextResource 以相对于 Web 应用根目录的方式访问文件资源,如下所示:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> 
 <jsp:directive.page import="
    org.springframework.web.context.support.ServletContextResource"/> 
 <jsp:directive.page import="org.springframework.core.io.Resource"/> 
 <% 
    // ① 注意文件资源地址以相对于 Web 应用根路径的方式表示
    Resource res3 = new ServletContextResource(application, 
        "/WEB-INF/classes/conf/file1.txt"); 
    out.print(res3.getFilename()); 
 %> 

对于位于远程服务器(Web 服务器或 FTP 服务器)的文件资源,您则可以方便地通过 UrlResource 进行访问。
为了方便访问不同类型的资源,您必须使用相应的 Resource 实现类,是否可以在不显式使用 Resource 实现类的情况下,仅根据带特殊前缀的资源地址直接加载文件资源呢? Spring 提供了一个 ResourceUtils 工具类,它支持“classpath:”和“file:”的地址前缀,它能够从指定的地址加载文件资源,请看下面的例子:

清单 2. ResourceUtilsExample
package com.baobaotao.io; 
 import java.io.File; 
 import org.springframework.util.ResourceUtils; 
 public class ResourceUtilsExample { 
    public static void main(String[] args) throws Throwable{ 
        File clsFile = ResourceUtils.getFile("classpath:conf/file1.txt"); 
        System.out.println(clsFile.isFile()); 

        String httpFilePath = "file:D:/masterSpring/chapter23/src/conf/file1.txt"; 
        File httpFile = ResourceUtils.getFile(httpFilePath); 
        System.out.println(httpFile.isFile());        
    } 
 } 

ResourceUtils 的 getFile(String resourceLocation) 方法支持带特殊前缀的资源地址,这样,我们就可以在不和 Resource 实现类打交道的情况下使用 Spring 文件资源加载的功能了。
本地化文件资源
本地化文件资源是一组通过本地化标识名进行特殊命名的文件,Spring 提供的 LocalizedResourceHelper 允许通过文件资源基名和本地化实体获取匹配的本地化文件资源并以 Resource 对象返回。假设在类路径的 i18n 目录下,拥有一组基名为 message 的本地化文件资源,我们通过以下实例演示获取对应中国大陆和美国的本地化文件资源:

清单 3. LocaleResourceTest
package com.baobaotao.io; 
 import java.util.Locale; 
 import org.springframework.core.io.Resource; 
 import org.springframework.core.io.support.LocalizedResourceHelper; 
 public class LocaleResourceTest { 
    public static void main(String[] args) { 
        LocalizedResourceHelper lrHalper = new LocalizedResourceHelper(); 
        // ① 获取对应美国的本地化文件资源
        Resource msg_us = lrHalper.findLocalizedResource("i18n/message", ".properties", 
        Locale.US); 
        // ② 获取对应中国大陆的本地化文件资源
        Resource msg_cn = lrHalper.findLocalizedResource("i18n/message", ".properties", 
        Locale.CHINA); 
        System.out.println("fileName(us):"+msg_us.getFilename()); 
        System.out.println("fileName(cn):"+msg_cn.getFilename()); 
    } 
 } 

虽然 JDK 的 java.util.ResourceBundle 类也可以通过相似的方式获取本地化文件资源,但是其返回的是 ResourceBundle 类型的对象。如果您决定统一使用 Spring 的 Resource 接表征文件资源,那么 LocalizedResourceHelper 就是获取文件资源的非常适合的帮助类了。
文件操作
在使用各种 Resource 接口的实现类加载文件资源后,经常需要对文件资源进行读取、拷贝、转存等不同类型的操作。您可以通过 Resource 接口所提供了方法完成这些功能,不过在大多数情况下,通过 Spring 为 Resource 所配备的工具类完成文件资源的操作将更加方便。
文件内容拷贝
第一个我们要认识的是 FileCopyUtils,它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。下面的实例展示了 FileCopyUtils 具体使用方法:

清单 4. FileCopyUtilsExample
package com.baobaotao.io; 
 import java.io.ByteArrayOutputStream; 
 import java.io.File; 
 import java.io.FileReader; 
 import java.io.OutputStream; 
 import org.springframework.core.io.ClassPathResource; 
 import org.springframework.core.io.Resource; 
 import org.springframework.util.FileCopyUtils; 
 public class FileCopyUtilsExample { 
    public static void main(String[] args) throws Throwable { 
        Resource res = new ClassPathResource("conf/file1.txt"); 
        // ① 将文件内容拷贝到一个 byte[] 中
        byte[] fileData = FileCopyUtils.copyToByteArray(res.getFile()); 
        // ② 将文件内容拷贝到一个 String 中
        String fileStr = FileCopyUtils.copyToString(new FileReader(res.getFile())); 
        // ③ 将文件内容拷贝到另一个目标文件
        FileCopyUtils.copy(res.getFile(), 
        new File(res.getFile().getParent()+ "/file2.txt")); 

        // ④ 将文件内容拷贝到一个输出流中
        OutputStream os = new ByteArrayOutputStream(); 
        FileCopyUtils.copy(res.getInputStream(), os); 
    } 
 } 

往往我们都通过直接操作 InputStream 读取文件的内容,但是流操作的代码是比较底层的,代码的面向对象性并不强。通过 FileCopyUtils 读取和拷贝文件内容易于操作且相当直观。如在 ① 处,我们通过 FileCopyUtils 的 copyToByteArray(File in) 方法就可以直接将文件内容读到一个 byte[] 中;另一个可用的方法是 copyToByteArray(InputStream in),它将输入流读取到一个 byte[] 中。
如果是文本文件,您可能希望将文件内容读取到 String 中,此时您可以使用 copyToString(Reader in) 方法,如 ② 所示。使用 FileReader 对 File 进行封装,或使用 InputStreamReader 对 InputStream 进行封装就可以了。
FileCopyUtils 还提供了多个将文件内容拷贝到各种目标对象中的方法,这些方法包括:
方法说明
static void copy(byte[] in, File out) 将 byte[] 拷贝到一个文件中
static void copy(byte[] in, OutputStream out) 将 byte[] 拷贝到一个输出流中
static int copy(File in, File out) 将文件拷贝到另一个文件中
static int copy(InputStream in, OutputStream out) 将输入流拷贝到输出流中
static int copy(Reader in, Writer out) 将 Reader 读取的内容拷贝到 Writer 指向目标输出中
static void copy(String in, Writer out) 将字符串拷贝到一个 Writer 指向的目标中
在实例中,我们虽然使用 Resource 加载文件资源,但 FileCopyUtils 本身和 Resource 没有任何关系,您完全可以在基于 JDK I/O API 的程序中使用这个工具类。
属性文件操作
我们知道可以通过 java.util.Properties 的 load(InputStream inStream) 方法从一个输入流中加载属性资源。Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源,请看下面的例子:
package com.baobaotao.io; 
 import java.util.Properties; 
 import org.springframework.core.io.support.PropertiesLoaderUtils; 
 public class PropertiesLoaderUtilsExample { 
    public static void main(String[] args) throws Throwable {    
        // ① jdbc.properties 是位于类路径下的文件
        Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties"); 
        System.out.println(props.getProperty("jdbc.driverClassName")); 
    } 
 } 

一般情况下,应用程序的属性文件都放置在类路径下,所以 PropertiesLoaderUtils 比之于 Properties#load(InputStream inStream) 方法显然具有更强的实用性。此外,PropertiesLoaderUtils 还可以直接从 Resource 对象中加载属性资源:
方法说明
static Properties loadProperties(Resource resource) 从 Resource 中加载属性
static void fillProperties(Properties props, Resource resource) 将 Resource 中的属性数据添加到一个已经存在的 Properties 对象中
特殊编码的资源
当您使用 Resource 实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如 UTF-8),则在读取资源内容时必须事先通过 EncodedResource 指定编码格式,否则将会产生中文乱码的问题。

清单 5. EncodedResourceExample
package com.baobaotao.io; 
 import org.springframework.core.io.ClassPathResource; 
 import org.springframework.core.io.Resource; 
 import org.springframework.core.io.support.EncodedResource; 
 import org.springframework.util.FileCopyUtils; 
 public class EncodedResourceExample { 
        public static void main(String[] args) throws Throwable  { 
            Resource res = new ClassPathResource("conf/file1.txt"); 
            // ① 指定文件资源对应的编码格式(UTF-8)
            EncodedResource encRes = new EncodedResource(res,"UTF-8"); 
            // ② 这样才能正确读取文件的内容,而不会出现乱码
            String content  = FileCopyUtils.copyToString(encRes.getReader()); 
            System.out.println(content);  
    } 
 } 

EncodedResource 拥有一个 getResource() 方法获取 Resource,但该方法返回的是通过构造函数传入的原 Resource 对象,所以必须通过 EncodedResource#getReader() 获取应用编码后的 Reader 对象,然后再通过该 Reader 读取文件的内容。

Web 相关工具类
您几乎总是使用 Spring 框架开发 Web 的应用,Spring 为 Web 应用提供了很多有用的工具类,这些工具类可以给您的程序开发带来很多便利。在这节里,我们将逐一介绍这些工具类的使用方法。
操作 Servlet API 的工具类
当您在控制器、JSP 页面中想直接访问 Spring 容器时,您必须事先获取 WebApplicationContext 对象。Spring 容器在启动时将 WebApplicationContext 保存在 ServletContext 的属性列表中,通过 WebApplicationContextUtils 工具类可以方便地获取 WebApplicationContext 对象。
WebApplicationContextUtils
当 Web 应用集成 Spring 容器后,代表 Spring 容器的 WebApplicationContext 对象将以 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在 ServletContext 属性列表中。您当然可以直接通过以下语句获取 WebApplicationContext:
WebApplicationContext wac = (WebApplicationContext)servletContext. 
 getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 

但通过位于 org.springframework.web.context.support 包中的 WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:
WebApplicationContext wac =WebApplicationContextUtils. 
 getWebApplicationContext(servletContext); 

当 ServletContext 属性列表中不存在 WebApplicationContext 时,getWebApplicationContext() 方法不会抛出异常,它简单地返回 null。如果后续代码直接访问返回的结果将引发一个 NullPointerException 异常,而 WebApplicationContextUtils 另一个 getRequiredWebApplicationContext(ServletContext sc) 方法要求 ServletContext 属性列表中一定要包含一个有效的 WebApplicationContext 对象,否则马上抛出一个 IllegalStateException 异常。我们推荐使用后者,因为它能提前发现错误的时间,强制开发者搭建好必备的基础设施。
WebUtils
位于 org.springframework.web.util 包中的 WebUtils 是一个非常好用的工具类,它对很多 Servlet API 提供了易用的代理方法,降低了访问 Servlet API 的复杂度,可以将其看成是常用 Servlet API 方法的门面类。
下面这些方法为访问 HttpServletRequest 和 HttpSession 中的对象和属性带来了方便:
方法说明
Cookie getCookie(HttpServletRequest request, String name) 获取 HttpServletRequest 中特定名字的 Cookie 对象。如果您需要创建 Cookie, Spring 也提供了一个方便的 CookieGenerator 工具类;
Object getSessionAttribute(HttpServletRequest request, String name) 获取 HttpSession 特定属性名的对象,否则您必须通过 request.getHttpSession.getAttribute(name) 完成相同的操作;
Object getRequiredSessionAttribute(HttpServletRequest request, String name) 和上一个方法类似,只不过强制要求 HttpSession 中拥有指定的属性,否则抛出异常;
String getSessionId(HttpServletRequest request) 获取 Session ID 的值;
void exposeRequestAttributes(ServletRequest request, Map attributes) 将 Map 元素添加到 ServletRequest 的属性列表中,当请求被导向(forward)到下一个处理程序时,这些请求属性就可以被访问到了;
此外,WebUtils 还提供了一些和 ServletContext 相关的方便方法:
方法说明
String getRealPath(ServletContext servletContext, String path) 获取相对路径对应文件系统的真实文件路径;
File getTempDir(ServletContext servletContext) 获取 ServletContex 对应的临时文件地址,它以 File 对象的形式返回。
下面的片断演示了使用 WebUtils 从 HttpSession 中获取属性对象的操作:
protected Object formBackingObject(HttpServletRequest request) throws Exception { 
    UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, 
        "userSession"); 
    if (userSession != null) { 
        return new AccountForm(this.petStore.getAccount( 
        userSession.getAccount().getUsername())); 
    } else { 
        return new AccountForm(); 
    } 
 } 

Spring 所提供的过滤器和监听器
Spring 为 Web 应用提供了几个过滤器和监听器,在适合的时间使用它们,可以解决一些常见的 Web 应用问题。
延迟加载过滤器
Hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session 范围之内进行。如果 Service 层返回一个启用了延迟加载功能的领域对象给 Web 层,当 Web 层访问到那些需要延迟加载的数据时,由于加载领域对象的 Hibernate Session 已经关闭,这些导致延迟加载数据的访问异常。
Spring 为此专门提供了一个 OpenSessionInViewFilter 过滤器,它的主要功能是使每个请求过程绑定一个 Hibernate Session,即使最初的事务已经完成了,也可以在 Web 层进行延迟加载的操作。
OpenSessionInViewFilter 过滤器将 Hibernate Session 绑定到请求线程中,它将自动被 Spring 的事务管理器探测到。所以 OpenSessionInViewFilter 适用于 Service 层使用 HibernateTransactionManager 或 JtaTransactionManager 进行事务管理的环境,也可以用于非事务只读的数据操作中。
要启用这个过滤器,必须在 web.xml 中对此进行配置:
…
 <filter> 
    <filter-name>hibernateFilter</filter-name> 
    <filter-class> 
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter 
    </filter-class> 
 </filter> 
 <filter-mapping> 
    <filter-name>hibernateFilter</filter-name> 
    <url-pattern>*.html</url-pattern> 
 </filter-mapping> 
…

上面的配置,我们假设使用 .html 的后缀作为 Web 框架的 URL 匹配模式,如果您使用 Struts 等 Web 框架,可以将其改为对应的“*.do”模型。
中文乱码过滤器
在您通过表单向服务器提交数据时,一个经典的问题就是中文乱码问题。虽然我们所有的 JSP 文件和页面编码格式都采用 UTF-8,但这个问题还是会出现。解决的办法很简单,我们只需要在 web.xml 中配置一个 Spring 的编码转换过滤器就可以了:
<web-app> 
 <!---listener 的配置 --> 
 <filter> 
    <filter-name>encodingFilter</filter-name> 
    <filter-class> 
        org.springframework.web.filter.CharacterEncodingFilter ① Spring 编辑过滤器
    </filter-class> 
    <init-param> ② 编码方式
        <param-name>encoding</param-name> 
        <param-value>UTF-8</param-value> 
    </init-param> 
    <init-param> ③ 强制进行编码转换
        <param-name>forceEncoding</param-name> 
        <param-value>true</param-value> 
    </init-param> 
    </filter> 
    <filter-mapping> ② 过滤器的匹配 URL 
        <filter-name>encodingFilter</filter-name> 
        <url-pattern>*.html</url-pattern> 
    </filter-mapping> 

 <!---servlet 的配置 --> 
 </web-app> 

这样所有以 .html 为后缀的 URL 请求的数据都会被转码为 UTF-8 编码格式,表单中文乱码的问题就可以解决了。
请求跟踪日志过滤器
除了以上两个常用的过滤器外,还有两个在程序调试时可能会用到的请求日志跟踪过滤器,它们会将请求的一些重要信息记录到日志中,方便程序的调试。这两个日志过滤器只有在日志级别为 DEBUG 时才会起作用:
方法说明
org.springframework.web.filter.ServletContextRequestLoggingFilter 该过滤器将请求的 URI 记录到 Common 日志中(如通过 Log4J 指定的日志文件);
org.springframework.web.filter.ServletContextRequestLoggingFilter 该过滤器将请求的 URI 记录到 ServletContext 日志中。
以下是日志过滤器记录的请求跟踪日志的片断:
(JspServlet.java:224) - JspEngine --> /htmlTest.jsp 
(JspServlet.java:225) - ServletPath: /htmlTest.jsp 
(JspServlet.java:226) - PathInfo: null 
(JspServlet.java:227) - RealPath: D:\masterSpring\chapter23\webapp\htmlTest.jsp 
(JspServlet.java:228) - RequestURI: /baobaotao/htmlTest.jsp 
…

通过这个请求跟踪日志,程度调试者可以详细地查看到有哪些请求被调用,请求的参数是什么,请求是否正确返回等信息。虽然这两个请求跟踪日志过 滤器一般在程序调试时使用,但是即使程序部署不将其从 web.xml 中移除也不会有大碍,因为只要将日志级别设置为 DEBUG 以上级别,它们就不会输出请求跟踪日志信息了。
转存 Web 应用根目录监听器和 Log4J 监听器
Spring 在 org.springframework.web.util 包中提供了几个特殊用途的 Servlet 监听器,正确地使用它们可以完成一些特定需求的功能。比如某些第三方工具支持通过 ${key} 的方式引用系统参数(即可以通过 System.getProperty() 获取的属性),WebAppRootListener 可以将 Web 应用根目录添加到系统参数中,对应的属性名可以通过名为“webAppRootKey”的 Servlet 上下文参数指定,默认为“webapp.root”。下面是该监听器的具体的配置:

清单 6. WebAppRootListener 监听器配置
…
 <context-param> 
    <param-name>webAppRootKey</param-name> 
    <param-value>baobaotao.root</param-value> ① Web 应用根目录以该属性名添加到系统参数中
 </context-param> 
…
② 负责将 Web 应用根目录以 webAppRootKey 上下文参数指定的属性名添加到系统参数中
 <listener> 
    <listener-class> 
    org.springframework.web.util.WebAppRootListener 
    </listener-class> 
 </listener> 
…

这样,您就可以在程序中通过 System.getProperty("baobaotao.root") 获取 Web 应用的根目录了。不过更常见的使用场景是在第三方工具的配置文件中通过 ${baobaotao.root} 引用 Web 应用的根目录。比如以下的 log4j.properties 配置文件就通过 ${baobaotao.root} 设置了日志文件的地址:
log4j.rootLogger=INFO,R 
 log4j.appender.R=org.apache.log4j.RollingFileAppender 
 log4j.appender.R.File=${baobaotao.root}/WEB-INF/logs/log4j.log ① 指定日志文件的地址
 log4j.appender.R.MaxFileSize=100KB 
 log4j.appender.R.MaxBackupIndex=1 
 log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n 

另一个专门用于 Log4J 的监听器是 Log4jConfigListener。一般情况下,您必须将 Log4J 日志配置文件以 log4j.properties 为文件名并保存在类路径下。Log4jConfigListener 允许您通过 log4jConfigLocation Servlet 上下文参数显式指定 Log4J 配置文件的地址,如下所示:
① 指定 Log4J 配置文件的地址
 <context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>/WEB-INF/log4j.properties</param-value> 
 </context-param> 
…
② 使用该监听器初始化 Log4J 日志引擎
 <listener> 
    <listener-class> 
    org.springframework.web.util.Log4jConfigListener 
    </listener-class> 
 </listener> 
…

提示

一些 Web 应用服务器(如 Tomcat)不会为不同的 Web 应用使用独立的系统参数,也就是说,应用服务器上所有的 Web 应用都共享同一个系统参数对象。这时,您必须通过 webAppRootKey 上下文参数为不同 Web 应用指定不同的属性名:如第一个 Web 应用使用 webapp1.root 而第二个 Web 应用使用 webapp2.root 等,这样才不会发生后者覆盖前者的问题。此外,WebAppRootListener 和 Log4jConfigListener 都只能应用在 Web 应用部署后 WAR 文件会解包的 Web 应用服务器上。一些 Web 应用服务器不会将 Web 应用的 WAR 文件解包,整个 Web 应用以一个 WAR 包的方式存在(如 Weblogic),此时因为无法指定对应文件系统的 Web 应用根目录,使用这两个监听器将会发生问题。
Log4jConfigListener 监听器包括了 WebAppRootListener 的功能,也就是说,Log4jConfigListener 会自动完成将 Web 应用根目录以 webAppRootKey 上下文参数指定的属性名添加到系统参数中,所以当您使用 Log4jConfigListener 后,就没有必须再使用 WebAppRootListener 了。
Introspector 缓存清除监听器
Spring 还提供了一个名为 org.springframework.web.util.IntrospectorCleanupListener 的监听器。它主要负责处理由 JavaBean Introspector 功能而引起的缓存泄露。IntrospectorCleanupListener 监听器在 Web 应用关闭的时会负责清除 JavaBean Introspector 的缓存,在 web.xml 中注册这个监听器可以保证在 Web 应用关闭的时候释放与其相关的 ClassLoader 的缓存和类引用。如果您使用了 JavaBean Introspector 分析应用中的类,Introspector 缓存会保留这些类的引用,结果在应用关闭的时候,这些类以及 Web 应用相关的 ClassLoader 不能被垃圾回收。不幸的是,清除 Introspector 的唯一方式是刷新整个缓存,这是因为没法准确判断哪些是属于本 Web 应用的引用对象,哪些是属于其它 Web 应用的引用对象。所以删除被缓存的 Introspection 会导致将整个 JVM 所有应用的 Introspection 都删掉。需要注意的是,Spring 托管的 Bean 不需要使用这个监听器,因为 Spring 的 Introspection 所使用的缓存在分析完一个类之后会马上从 javaBean Introspector 缓存中清除掉,并将缓存保存在应用程序特定的 ClassLoader 中,所以它们一般不会导致内存资源泄露。但是一些类库和框架往往会产生这个问题。例如 Struts 和 Quartz 的 Introspector 的内存泄漏会导致整个的 Web 应用的 ClassLoader 不能进行垃圾回收。在 Web 应用关闭之后,您还会看到此应用的所有静态类引用,这个错误当然不是由这个类自身引起的。解决这个问题的方法很简单,您仅需在 web.xml 中配置 IntrospectorCleanupListener 监听器就可以了:
<listener> 
    <listener-class> 
    org.springframework.web.util.IntrospectorCleanupListener 
    </listener-class> 
 </listener> 


小结
本文介绍了一些常用的 Spring 工具类,其中大部分 Spring 工具类不但可以在基于 Spring 的应用中使用,还可以在其它的应用中使用。使用 JDK 的文件操作类在访问类路径相关、Web 上下文相关的文件资源时,往往显得拖泥带水、拐弯抹角,Spring 的 Resource 实现类使这些工作变得轻松了许多。
在 Web 应用中,有时你希望直接访问 Spring 容器,获取容器中的 Bean,这时使用 WebApplicationContextUtils 工具类从 ServletContext 中获取 WebApplicationContext 是非常方便的。WebUtils 为访问 Servlet API 提供了一套便捷的代理方法,您可以通过 WebUtils 更好的访问 HttpSession 或 ServletContext 的信息。
Spring 提供了几个 Servlet 过滤器和监听器,其中 ServletContextRequestLoggingFilter 和 ServletContextRequestLoggingFilter 可以记录请求访问的跟踪日志,你可以在程序调试时使用它们获取请求调用的详细信息。WebAppRootListener 可以将 Web 应用的根目录以特定属性名添加到系统参数中,以便第三方工具类通过 ${key} 的方式进行访问。Log4jConfigListener 允许你指定 Log4J 日志配置文件的地址,且可以在配置文件中通过 ${key} 的方式引用 Web 应用根目录,如果你需要在 Web 应用相关的目录创建日志文件,使用 Log4jConfigListener 可以很容易地达到这一目标。
Web 应用的内存泄漏是最让开发者头疼的问题,虽然不正确的程序编写可能是这一问题的根源,也有可能是一些第三方框架的 JavaBean Introspector 缓存得不到清除而导致的,Spring 专门为解决这一问题配备了 IntrospectorCleanupListener 监听器,它只要简单在 web.xml 中声明该监听器就可以了。

Spring v3.0.2 Learning Note 16 - Integrate With Hessian

Reference Library

%SPRING%\dist\com.springsource.org.aopalliance-1.0.0.jar
%SPRING%\dist\org.springframework.aop-3.0.2.RELEASE.jar
%SPRING%\dist\org.springframework.asm-3.0.4.RELEASE.jar
%SPRING%\dist\org.springframework.beans-3.0.2.RELEASE.jar
%SPRING%\dist\org.springframework.context-3.0.4.RELEASE.jar
%SPRING%\dist\org.springframework.core-3.0.2.RELEASE.jar
%SPRING%\dist\org.springframework.expression-3.0.4.RELEASE.jar
%SPRING%\dist\org.springframework.transaction-3.0.2.RELEASE.jar
%SPRING%\dist\org.springframework.web.servlet-3.0.2.RELEASE
%SPRING%\dist\org.springframework.web-3.0.4.RELEASE.jar
%SPRING_DEP%\org.apache.commons\com.springsource.org.apache.commons.logging\1.1.1\com.springsource.org.apache.commons.logging-1.1.1.jar
%SPRING_DEP%\com.caucho\com.springsource.com.caucho\3.2.1\com.springsource.com.caucho-3.2.1.jar
%SPRING_DEP%\javax.servlet\com.springsource.javax.servlet\2.5.0\com.springsource.javax.servlet-2.5.0.jar

Wiring up the DispatcherServlet for Hessian

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springhessian</display-name>

    <servlet>
        <servlet-name>hessianServices</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>hessianServices</servlet-name>
        <url-pattern>/remote/*</url-pattern>
    </servlet-mapping>

</web-app>

Using Spring's DispatcherServlet principles, as known from Spring Web MVC usage, you can easily wire up such a servlet exposing your services.

Exposing your beans by using the HessianServiceExporter

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="com.spring.hessian.test" />
    <bean id="acctService" class="com.spring.hessian.test.impl.AccountInfoImpl" />
    <bean name="/acctService"
        class="org.springframework.remoting.caucho.HessianServiceExporter">
        <property name="service" ref="acctService" />
        <property name="serviceInterface" value="com.spring.hessian.test.IAccountInfo" />
    </bean>
</beans>

Above configuration should be stored in WEB-INF\hessianServices-servlet.xml
Take note the configuration file name must be hessianServices-servlet.xml. 
According to spring manual, the file name is remoting-servlet.xml, I tried it but it could not work.


>>> After several try, found the naming rule is <servlet name defined in web.xml>-servlet.xml.
For example, I defined a servlet named hessianServices, so the configure file will be hessianServices-servlet.xml



Source Code

// interface
package com.spring.hessian.test;

import com.spring.hessian.test.bean.AccountInfo;

public interface IAccountInfo {

    public void createAccount(AccountInfo accountInfo);

    public boolean changeEmail(int accountId, String newEmail);

    public void deleteAccount(int accountId);
}


// implement class
package com.spring.hessian.test.impl;

import org.springframework.stereotype.Service;

import com.spring.hessian.test.IAccountInfo;
import com.spring.hessian.test.bean.AccountInfo;

@Service
public class AccountInfoImpl implements IAccountInfo {

    @Override
    public boolean changeEmail(int accountId, String newEmail) {
        System.out.println("Here is the logic to change email.");
        return false;
    }

    @Override
    public void createAccount(AccountInfo accountInfo) {
        System.out
                .println("Here is the logic to create account with account info = "
                        + accountInfo.toString());
    }

    @Override
    public void deleteAccount(int accountId) {
        System.out.println("Here is the logic to delete account with ID = "
                + accountId);
    }

}
 

// domain class
package com.spring.hessian.test.bean;

import java.io.Serializable;

public class AccountInfo implements Serializable {

    private static final long serialVersionUID = 5308953586718817188L;
    private int accountId;
    private String userName;
    private String password;
    private String email;

    public AccountInfo() {
        super();
    }

    public AccountInfo(int accountId, String userName, String password,
            String email) {
        super();
        this.accountId = accountId;
        this.userName = userName;
        this.password = password;
        this.email = email;
    }

    public int getAccountId() {
        return accountId;
    }

    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }

    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;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String toString() {
        return "AccountInfo:[id]=" + this.accountId + ",[userName]="
                + this.userName + ",[pwd]=" + this.password + ",[email]="
                + this.email;
    }

}
 

// Junit test
package com.spring.hessian.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.caucho.hessian.client.HessianProxyFactory;
import com.spring.hessian.test.bean.AccountInfo;

public class HessianTester {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void test() throws Exception {
        String url = "http://localhost:8080/springhessian/remote/acctService";
        HessianProxyFactory factory = new HessianProxyFactory();
        IAccountInfo accountInfo = (IAccountInfo) factory.create(
                IAccountInfo.class, url);
        AccountInfo account = new AccountInfo(125, "myName", "myPwd",
                "abc@email.com");
        accountInfo.createAccount(account);
        accountInfo.changeEmail(126, "def@email.com");
        accountInfo.deleteAccount(129);
    }
}


From tomcat console ,we can see the output if running above junit test case.
Here is the logic to create account with account info = AccountInfo:[id]=125,[userName]=myName,[pwd]=myPwd,[email]=abc@email.com
Here is the logic to change email.
Here is the logic to delete account with ID = 129


未解决的问题

以上代码和配置在tomcat中一切正常,但是移到weblogic v10.3下,当调用第一个远程方法后总会碰到空指针异常
<Oct 29, 2010 1:42:20 PM SGT> <Error> <Kernel> <BEA-000802> <ExecuteRequest failed
 java.lang.NullPointerException.
java.lang.NullPointerException
        at weblogic.utils.http.HttpChunkInputStream.initChunk(HttpChunkInputStream.java:66)
        at weblogic.utils.http.HttpChunkInputStream.skip(HttpChunkInputStream.java:197)
        at weblogic.utils.http.HttpChunkInputStream.skipAllChunk(HttpChunkInputStream.java:371)
        at weblogic.servlet.internal.ServletInputStreamImpl.ensureChunkedConsumed(ServletInputStreamImpl.java:30)
        at weblogic.servlet.internal.ServletRequestImpl.skipUnreadBody(ServletRequestImpl.java:192)
        Truncated. see log file for complete stacktrace
>



到现在仍没找到原因,不得已还是采用hessian的配置方式
<servlet>
  <servlet-name>HessianServlet</servlet-name>
  <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
  <init-param>
   <param-name>home-class</param-name>
   <param-value>com.spring.hessian.test.impl.AccountInfoImpl</param-value>
  </init-param>
  <init-param>
   <param-name>home-api</param-name>
   <param-value>com.spring.hessian.test.IAccountInfo</param-value>
  </init-param>
 </servlet>

 <servlet-mapping>
  <servlet-name>HessianServlet</servlet-name>
  <url-pattern>/remote2</url-pattern>
 </servlet-mapping>



客户端改用这个URL "http://<host>:<port>/hessian/remote2" 在weblogic下可得正确结果。


如果采用hessian的配置方式,以下依赖包就不再需要了
%SPRING%\dist\org.springframework.web.servlet-3.0.2.RELEASE
%SPRING%\dist\org.springframework.web-3.0.4.RELEASE.jar

以下配置文件不再需要
WEB-INF\hessianServices-servlet.xml 

web.xml内容改为:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springhessian</display-name>

    <servlet>
        <servlet-name>HessianServlet</servlet-name>
        <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
        <init-param>
            <param-name>home-class</param-name>
            <param-value>com.spring.hessian.test.impl.AccountInfoImpl</param-value>
        </init-param>
        <init-param>
            <param-name>home-api</param-name>
            <param-value>com.spring.hessian.test.IAccountInfo</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>HessianServlet</servlet-name>
        <url-pattern>/remote2</url-pattern>
    </servlet-mapping>
</web-app>

WEB-INF\classes 需要spring的配置文件,内容为:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="com.spring.hessian.test" />
</beans>

为了部属到weblogic,还需要配置文件WEB-INF\weblogic.xml, 其内容为:
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd">
    <!-- share session in clustering env.  -->
    <session-descriptor>
        <persistent-store-type>replicated_if_clustered</persistent-store-type>
        <sharing-enabled>true</sharing-enabled> 
    </session-descriptor>
     <!-- load customized library files first  -->
    <container-descriptor>
        <prefer-web-inf-classes>true</prefer-web-inf-classes>
    </container-descriptor>
        <!-- set root context  -->
    <context-root>/hessian</context-root>

</weblogic-web-app>