axis1.4开发webservice

 

axis1.4整合spring2.5开发webservice

 

jar包

axis1.4jar包有:

    axis-ant.jar

    axis.jar

    commons-discovery-0.4.jar

    commons-httpclient-3.1.jar

    jaxrpc.jar

    saaj.jar

    wsdl4j.jar

 

<!-- axis -->
<!--webService-->
  <display-name>Apache-Axis</display-name>
  <servlet>
    <servlet-name>AxisServlet</servlet-name>
    <servlet-class>
        org.apache.axis.transport.http.AxisServlet
    </servlet-class>
  </servlet>
  <servlet>
    <servlet-name>AdminServlet</servlet-name>
    <servlet-class>
        org.apache.axis.transport.http.AdminServlet
    </servlet-class>
    <load-on-startup>100</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>SOAPMonitorService</servlet-name>
    <servlet-class>
        org.apache.axis.monitor.SOAPMonitorService
    </servlet-class>
    <init-param>
      <param-name>SOAPMonitorPort</param-name>
      <param-value>5001</param-value>
    </init-param>
    <load-on-startup>100</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/servlet/AxisServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>*.jws</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>SOAPMonitorService</servlet-name>
    <url-pattern>/SOAPMonitor</url-pattern>
  </servlet-mapping>
  <mime-mapping>
    <extension>wsdl</extension>
     <mime-type>text/xml</mime-type>
  </mime-mapping>
  <mime-mapping>
    <extension>xsd</extension>
    <mime-type>text/xml</mime-type>
  </mime-mapping>

 在WEB-INF下增加 server-config.wsdd文件,可以直接复制下面进行修改

    

<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="http://xml.apache.org/axis/wsdd/"
	xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
	<globalConfiguration>
		<parameter name="sendMultiRefs" value="true" />
		<parameter name="disablePrettyXML" value="true" />
		<parameter name="adminPassword" value="admin" />
		<parameter name="attachments.Directory" value="D:\JavaSoft\apache-tomcat-7.0.20\apache-tomcat-7.0.20\webapps\ljtoa\WEB-INF\attachments" />
		<parameter name="dotNetSoapEncFix" value="true" />
		<parameter name="enableNamespacePrefixOptimization" value="false" />
		<parameter name="sendXMLDeclaration" value="true" />
		<parameter name="sendXsiTypes" value="true" />
		<parameter name="attachments.implementation" value="org.apache.axis.attachments.AttachmentsImpl" />
		<requestFlow>
			<handler type="java:org.apache.axis.handlers.JWSHandler">
				<parameter name="scope" value="session" />
			</handler>
			<handler type="java:org.apache.axis.handlers.JWSHandler">
				<parameter name="scope" value="request" />
				<parameter name="extension" value=".jwr" />
			</handler>
		</requestFlow>
	</globalConfiguration>
	<handler name="LocalResponder" type="java:org.apache.axis.transport.local.LocalResponder" />
	<handler name="URLMapper" type="java:org.apache.axis.handlers.http.URLMapper" />
	<handler name="Authenticate" type="java:org.apache.axis.handlers.SimpleAuthenticationHandler" />
	<service name="SyncUserInfoService" provider="java:RPC">
	   <parameter name="className" value="com.lsq.webservice.service.inner.impl.SyncUserInfoServiceImpl" />
	   <parameter name="allowedMethods" value="*" />
	</service>
	
	<service name="AdminService" provider="java:MSG">
		<parameter name="allowedMethods" value="AdminService" />
		<parameter name="enableRemoteAdmin" value="false" />
		<parameter name="className" value="org.apache.axis.utils.Admin" />
		<namespace>http://xml.apache.org/axis/wsdd/</namespace>
	</service>
	<service name="Version" provider="java:RPC">
		<parameter name="allowedMethods" value="getVersion" />
		<parameter name="className" value="org.apache.axis.Version" />
	</service>
	<transport name="http">
		<requestFlow>
			<handler type="URLMapper" />
			<handler type="java:org.apache.axis.handlers.http.HTTPAuthHandler" />
		</requestFlow>
		<parameter name="qs:list" value="org.apache.axis.transport.http.QSListHandler" />
		<parameter name="qs:wsdl" value="org.apache.axis.transport.http.QSWSDLHandler" />
		<parameter name="qs.list" value="org.apache.axis.transport.http.QSListHandler" />
		<parameter name="qs.method" value="org.apache.axis.transport.http.QSMethodHandler" />
		<parameter name="qs:method" value="org.apache.axis.transport.http.QSMethodHandler" />
		<parameter name="qs.wsdl" value="org.apache.axis.transport.http.QSWSDLHandler" />
	</transport>
	<transport name="local">
		<responseFlow>
			<handler type="LocalResponder" />
		</responseFlow>
	</transport>
</deployment>

   修改上面的SyncUserInfoService为自已的service就行了

 

  

package com.lsq.webservice.service.inner;


public interface SyncUserInfoService {
	
	/**
	 * 
	 * @param updateDate 格式: 2013-05-05
	 * @return
	 */
	public String getUser(String updateDate);
}

 

public class SyncUserInfoServiceImpl implements SyncUserInfoService {
	private final Log logger = LogFactory.getLog(SyncUserInfoServiceImpl.class);
	@Override
	public String getUser(String updateDate) {
		AppUserService appUserService = (AppUserService)AppUtil.getBean("appUserService");
		List list = appUserService.findByUpdateTime(updateDate);
		List<SyncUserInfo> userList = this.assembleData(list);
		XStream xstream = new XStream();
		xstream.setMode(XStream.NO_REFERENCES);
		NullConverter nullConverter = new NullConverter();
		xstream.registerConverter(nullConverter);
		xstream.alias("syncUserInfo", SyncUserInfo.class);

		String str = xstream.toXML(userList);
		return XmlUtil.reponseXml(str);
	}

 测试类:

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class TestClient3 {
	public static void main(String[] args) {
		 testSync();
	}
	
	public static void testSync(){
		try {
			String wsdlUrl = "http://localhost:8080/lsq/services/SyncUserInfoService?wsdl";
			Service service = new Service();
			Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(wsdlUrl);
            call.setOperationName("getUser");//WSDL里面描述的接口名称
            call.addParameter("updateDate", org.apache.axis.encoding.XMLType.XSD_STRING,
                          javax.xml.rpc.ParameterMode.IN);//接口的参数
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型  
            String result = (String)call.invoke(new Object[]{"2013-05-05"});
            //给方法传递参数,并且调用方法
            System.out.println(result);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

 

为webservice增加简单访问权限控制

增加handler

package com.lsq.webservice.handler;
import java.util.Date;

import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LogHandler extends BasicHandler {
	private final Log logger = LogFactory.getLog(LogHandler.class);
    /**
        invoke,每一个handler都必须实现的方法。
     */
    public void invoke(MessageContext msgContext) throws AxisFault {
        //每当web服务被调用,都记录到log中。
    	logger.info("日志记录 : invoke : start");
        try {
            Handler handler = msgContext.getService();
            Integer counter = (Integer)handler.getOption("accesses");
            if (counter == null)
                counter = new Integer(0);

            counter = new Integer(counter.intValue() + 1);            
            Date date = new Date();
            msgContext.getMessage().writeTo(System.out);
           
            String result = "在" + date + ": Web 服务 " +
                msgContext.getTargetService() +
                " 被调用,现在已经共调用了 " + counter + " 次.";
            handler.setOption("accesses", counter);            
            logger.info(result);            
        } catch (Exception e) {
            throw AxisFault.makeFault(e);
        }
    }
}

 

package com.lsq.webservice.handler;
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.security.AuthenticatedUser;
import org.apache.axis.security.SecurityProvider;
import org.apache.axis.security.simple.SimpleSecurityProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//此handler的目的是对用户认证,只有认证的用户才能访问目标服务。
public class AuthenticationHandler extends BasicHandler {
    Log log = LogFactory.getLog(AuthenticationHandler.class);
    String securityProvider = "securityProvider";
    String unauthenticated = "unauthenticated";
    String authenticatedUser = "authenticatedUser";
    String cantAuth = "cantAuth";

    public void invoke(MessageContext msgContext) throws AxisFault {
        log.info("身份验证 : 开始");
        SecurityProvider provider = (SecurityProvider)msgContext.getProperty(securityProvider);
        if(provider == null) {
            provider = new SimpleSecurityProvider();
            msgContext.setProperty(securityProvider, provider);
        }

        if(provider != null) {
            String userId = msgContext.getUsername();
            String password = msgContext.getPassword();
            //对用户进行认证,如果authUser==null,表示没有通过认证,
            log.info(userId + ", " + password);
            //抛出Server.Unauthenticated异常。
            AuthenticatedUser authUser = provider.authenticate(msgContext);

            if(authUser == null)
                throw new AxisFault(unauthenticated, 
                    "error", null, null);
            //用户通过认证,把用户的设置成认证了的用户。
            msgContext.setProperty(authenticatedUser, authUser);
        }
        log.info("身份验证 : 结束");
    }
}

 

package com.lsq.webservice.handler;
import java.util.StringTokenizer;

import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.i18n.Messages;
import org.apache.axis.security.AuthenticatedUser;
import org.apache.axis.security.SecurityProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AuthorizationHandler extends BasicHandler {
    Log log = LogFactory.getLog(AuthorizationHandler.class);
    /**
        invoke,每一个handler都必须实现的方法。
     */
    public void invoke(MessageContext msgContext) throws AxisFault {
        log.info("start");

        AuthenticatedUser user = (AuthenticatedUser)msgContext.getProperty("authenticatedUser");
        if(user == null)
            throw new AxisFault("Server.NoUser", Messages.getMessage("needUser00"), null, null);
        String userId = user.getName();
        Handler serviceHandler = msgContext.getService();
        if(serviceHandler == null)
            throw new AxisFault(Messages.getMessage("needService00"));
        String serviceName = serviceHandler.getName();
        String allowedRoles = (String)serviceHandler.getOption("allowedRoles");
        if(allowedRoles == null) {
            log.info("不需要验证");
            return;
        }
        SecurityProvider provider = (SecurityProvider)msgContext.getProperty("securityProvider");
        if(provider == null)
            throw new AxisFault(Messages.getMessage("noSecurity00"));
        for(StringTokenizer st = new StringTokenizer(allowedRoles, ","); st.hasMoreTokens();) {
            String thisRole = st.nextToken();
            if(provider.userMatches(user, thisRole)) {
                log.info("通过验证");
                return;//访问授权通过。
            }
        }
        //没有通过授权,不能访问目标服务,抛出Server.Unauthorized异常。
        throw new AxisFault("Server.Unauthorized", 
            Messages.getMessage("cantAuth02", userId, serviceName), null, null);
    }     
}

 然后在WEB-INF下新增users.lst

里面是用户名密码信息,只有这里面的用户才能访问webservice

user1 pass1
user2 pass2
user3 pass3
admin 123456

 

   在server-config.wsdd中的SyncUserInfoService增加handler处理

<service name="SyncUserInfoService" provider="java:RPC">
		<requestFlow>
  			<handler name="authen" type="java:com.xpsoft.webservice.handler.AuthenticationHandler"/>
	    	        <handler name="author" type="java:com.xpsoft.webservice.handler.AuthorizationHandler"/>
                        <handler name="logging" type="java:com.xpsoft.webservice.handler.LogHandler"/>
  		</requestFlow> 
	   <parameter name="className" value="com.lsq.webservice.service.inner.impl.SyncUserInfoServiceImpl" />
	   <parameter name="allowedMethods" value="*" />
</service>

   

   修改测试类:新增请求用户名和密码

    

public static void testSync(){
		try {
			String wsdlUrl = "http://localhost:8080/lsq/services/SyncUserInfoService?wsdl";
			Service service = new Service();
			Call call = (Call) service.createCall();
			call.getMessageContext().setUsername("admin");
			call.getMessageContext().setPassword("123456");
            call.setTargetEndpointAddress(wsdlUrl);
            call.setOperationName("getUser");//WSDL里面描述的接口名称
            call.addParameter("updateDate", org.apache.axis.encoding.XMLType.XSD_STRING,
                          javax.xml.rpc.ParameterMode.IN);//接口的参数
            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型  
            String result = (String)call.invoke(new Object[]{"2013-05-05"});
            //给方法传递参数,并且调用方法
            System.out.println(result);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

 参考:

    http://www.ibm.com/developerworks/cn/webservices/ws-secaxis1/

    http://www.ibm.com/developerworks/cn/webservices/ws-handler/index.html

你可能感兴趣的:(axis1.4)