SpringBoot开发WebService之Axis_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > SpringBoot开发WebService之Axis

SpringBoot开发WebService之Axis

 2019/7/15 1:09:23  log_cd  程序员俱乐部  我要评论(0)
  • 摘要:一、服务器端发布WebService服务1、POM.xml文件中引入相关依赖包<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http
  • 标签:Web Service Webservice Spring 开发
一、服务器端发布WebService服务
1、POM.xml文件中引入相关依赖包
class="xml" name="code">
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.logcd</groupId>
	<artifactId>springboot-axis</artifactId>
	<version>1.0.0</version>
	<packaging>war</packaging>

	<name>springboot-axis</name>
	<description></description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.RELEASE</version>
		<relativePath/>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.7</java.version>
		<maven.test.skip>true</maven.test.skip>  
		<maven.test.failure.ignore>true</maven.test.failure.ignore>  
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!-- 打war包时移除嵌入式tomcat插件 -->
			<!-- 
		    <exclusions>
		        <exclusion>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-tomcat</artifactId>
		        </exclusion>
		    </exclusions>
		     -->
		</dependency>
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-web-services</artifactId>
		</dependency>

        <!-- axis 1.4 jar start -->
   		<dependency>
   			<groupId>org.apache.axis</groupId>
   			<artifactId>axis</artifactId>
   			<version>1.4</version>
   		</dependency>
   		<dependency>
   			<groupId>axis</groupId>
   			<artifactId>axis-jaxrpc</artifactId>
   			<version>1.4</version>
   		</dependency>
   		<dependency>
   			<groupId>commons-discovery</groupId>
   			<artifactId>commons-discovery</artifactId>
   			<version>0.2</version>
   		</dependency>
   		<dependency>
   			<groupId>wsdl4j</groupId>
   			<artifactId>wsdl4j</artifactId>
   			<version>1.6.3</version><!--$NO-MVN-MAN-VER$-->
   		</dependency>
        <!-- axis 1.4 jar end -->
		<dependency>
		    <groupId>javax.mail</groupId>
		    <artifactId>mail</artifactId>
		    <version>1.4.7</version>
		</dependency>
		<dependency>
		    <groupId>javax.activation</groupId>
		    <artifactId>activation</artifactId>
		    <version>1.1.1</version>
		</dependency>
		
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <version>3.1.0</version><!--$NO-MVN-MAN-VER$-->
		    <scope>provided</scope>
		</dependency>		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>  
					<skip>${maven.test.skip}</skip>  
					<testFailureIgnore>${maven.test.failure.ignore}</testFailureIgnore>  
				</configuration>				
			</plugin>
            <plugin>
	            <groupId>org.springframework.boot</groupId>
	            <artifactId>spring-boot-maven-plugin</artifactId>
	            <executions>
	                <execution>
	                    <goals>
	                        <goal>repackage</goal>
	                    </goals>
	                </execution>
	            </executions>
	        </plugin>
		</plugins>
	</build>

</project>

2、定义spring服务
@Service("helloService")
public class HelloService {

	public String sayHello(String username) {
		return "hello,"+username;
	}
	
}

3、配置并发布AxisServlet
@Configuration
public class WSAxisConfig {

	/**
	 * servlet过滤规则
	 * @return
	 */
	@Bean
	public ServletRegistrationBean dispatcherServlet() {
		ServletRegistrationBean axisServlet = new ServletRegistrationBean(new AxisServlet(), "/axis/*");
		axisServlet.setName("axisServlet");
		axisServlet.setLoadOnStartup(1);
		
		return axisServlet;
	}	
	
}

4、修改启动类,并重写初始化方法(打包war发布时需要改变启动方式)
@SpringBootApplication
@ServletComponentScan
public class Application {

	public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
	
}

public class SpringBootStartApplication extends SpringBootServletInitializer{

	@Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }	
	
}

5、logback日志配置
<?xml version="1.0"?>
<configuration>
  
    <!-- 日志目录 -->
    <property name="logdir" value="logs" />  
  
    <!-- 控制台 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">  
        <encoder charset="UTF-8">  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%-5level] %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  

	<appender name="netLogcdAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">  
	    <file>${logdir}/net_logcd.log</file>  
	    <append>true</append> 
	    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">  
            <fileNamePattern>${logdir}/net_logcd.%d{yyyy-MM-dd}.%i.log</fileNamePattern> 
            <MaxHistory>3</MaxHistory>
            <maxFileSize>20MB</maxFileSize> 
            <totalSizeCap>100MB</totalSizeCap>	        
	    </rollingPolicy>  
	    <encoder>  
	        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>  
	    </encoder>  
	</appender>
  
    <!-- 日志级别 TRACE, DEBUG, INFO, WARN, ERROR, ALL,OFF-->  
    <root>  
        <level value="info" />  
        <appender-ref ref="console" />  
    </root>  
 
	<logger name="net.logcd.ws" level="info" additivity="false">  
	    <appender-ref ref="netLogcdAppender" />  
	</logger>
  
</configuration>

二、客户端测试调用WebService
public class TestClientAxisWS {

	@Test
	public void invokeHelloService_WS() throws Exception {
		String endPointUrl = "http://127.0.0.1:8080/axis/helloService";
		String namespaceURI = "http://net.logcd.axis";
		Service service = new Service();
		Call call = (Call) service.createCall();

		call.addParameter("userName", XMLType.XSD_STRING, ParameterMode.IN);
		call.setReturnType(XMLType.XSD_STRING);

		URL url = new URL(endPointUrl);
		call.setTargetEndpointAddress(url);
		QName opName = new QName(namespaceURI, "sayHello");
		call.setOperationName(opName);
		Object retObj = call.invoke(new Object[] { "lucy" });

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

	/**
	 * 取天气预报信息(.net开发的WebService)
	 * @throws Exception
	 */
	@Test
	public void invokeWeatherService() throws Exception {
		String endPointUrl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
		String namespaceURI = "http://WebXml.com.cn/";
		String soapActionURI = "http://WebXml.com.cn/getWeatherbyCityName";
		String method = "getWeatherbyCityName";

		Service service = new Service();
		Call call = (Call) service.createCall();

		call.addParameter(new QName(namespaceURI, "theCityName"), XMLType.XSD_STRING, ParameterMode.IN);
		call.setReturnType(XMLType.XSD_SCHEMA);

		call.setTargetEndpointAddress(new URL(endPointUrl));
		call.setUseSOAPAction(true);
		call.setSOAPActionURI(soapActionURI);
		call.setOperationName(new QName(namespaceURI, method));
		Schema result = (Schema) call.invoke(new Object[] { "成都" });

		StringBuffer buff = new StringBuffer();
		for (int i = 0; i < result.get_any().length; i++) {
			buff.append(result.get_any()[i]);
		}
		//把&#x591A替换成\u591A
		System.out.println(unicodeToString(buff.toString().replaceAll("&#x(.*?);","\\\\u$1")));
	}

	public static String unicodeToString(String str) {
		Charset set = Charset.forName("UTF-16");
		Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
		Matcher m = p.matcher(str);
		int start = 0;
		int start2 = 0;
		StringBuffer sb = new StringBuffer();
		while (m.find(start)) {
			start2 = m.start();
			if (start2 > start) {
				String seg = str.substring(start, start2);
				sb.append(seg);
			}
			String code = m.group(1);
			int i = Integer.valueOf(code, 16);
			byte[] bb = new byte[4];
			bb[0] = (byte) ((i >> 8) & 0xFF);
			bb[1] = (byte) (i & 0xFF);
			ByteBuffer b = ByteBuffer.wrap(bb);
			sb.append(String.valueOf(set.decode(b)).trim());
			start = m.end();
		}
		start2 = str.length();
		if (start2 > start) {
			String seg = str.substring(start, start2);
			sb.append(seg);
		}
		return sb.toString();
	}

}
发表评论
用户名: 匿名