Utilice el marco cxf para crear un servicio de servicio web (modo Spring xml y modo SpringBoot)

1. Basado en el marco cxf, cree un servicio de servicio web en el marco Spring

Paso 1, cree un proyecto maven, primero importe las dependencias relacionadas con Spring, luego importe las dependencias cxf, configure los complementos de tomcat y otros complementos relacionados

 <properties>
		<spring.version>4.2.4.RELEASE</spring.version>
  </properties>
  
  
  <dependencies>
		<!-- spring -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.8</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency> 
			<groupId>org.apache.cxf</groupId> 
			<artifactId>cxf-rt-frontend-jaxws</artifactId> 
			<version>3.0.1</version> 
		</dependency> 
		<dependency> 
			<groupId>org.apache.cxf</groupId> 
			<artifactId>cxf-rt-transports-http</artifactId> 
			<version>3.0.1</version> 
		</dependency>

	</dependencies>
	
	 <build>
	<pluginManagement>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
					<showWarnings>true</showWarnings>
				</configuration>
			</plugin>
			<plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>8080</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
		</plugins>
	</pluginManagement>
  </build>

2. Escriba una interfaz simple, la descripción de la función es ingresar el nombre de la ciudad, devolver las condiciones climáticas actuales de la ciudad, la anotación @WebParam (name = "cityName") indica el nombre del parámetro

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface WeatherService {
	
	public String getCityInfo(@WebParam(name="cityName")String cityName);

}

3. Clase de implementación

public class WeatherServiceImpl implements WeatherService {
	@Override
	public String getCityInfo(String cityName) {
		String res = "";
		if(cityName.equals("北京")) {
			res = cityName+":大雨";
		}
		if(cityName.equals("上海")) {
			res = cityName+":多云";
		}
		return res;
	}
}

4. El archivo de configuración del resorte se configura de la siguiente manera

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cxf="http://cxf.apache.org/core"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd
        ">

	<!-- 服务类,将服务类注入到spring容器 -->
	<bean id="weather" class="com.enjoy.ws.WeatherServiceImpl"></bean>
	
	<!-- 将服务发布 -->
	<jaxws:server address="/weather">
		<jaxws:serviceBean>
			<ref bean="weather"/>
		</jaxws:serviceBean>
	</jaxws:server>
</beans>	

5.web.xml realiza la siguiente configuración

<!--加载spring配置文件-->
<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>

	</context-param>
<!--配置监听-->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

<!--配置cxf的servlet-->
	<servlet>
		<servlet-name>cxf</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>cxf</servlet-name>
		<url-pattern>/ws/*</url-pattern>
	</servlet-mapping>

6. Inicie el proyecto, ejecútelo como -> maven build. Ingrese tomcat7: run, inicie el proyecto a través del complemento tomcat configurado

Entrada del navegador localhost: 8080 / ws / weather? Wsdl

ip + puerto + el contenido de la etiqueta <path> del complemento tomcat configurado + la ruta de interceptación del cxf configurado por web.xml + el valor de la dirección en la que el archivo de configuración de Spring publicará el servicio +? wsdl

Los siguientes resultados demuestran que el lanzamiento es exitoso

 

Aquí hay una descripción detallada del servicio de publicación.

7. Escribe un método principal para probar el servicio de llamada.

Necesita introducir las siguientes dependencias

<dependency>
        <groupId>axis</groupId>
        <artifactId>axis</artifactId>
        <version>1.4</version>
    </dependency>
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;

import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

public class Weather {
	
	public static void main(String[] args) throws Exception {
		Service service = new Service();
		Call call = service.createCall();
		call.setTargetEndpointAddress("http://localhost:8080/ws/weather?wsdl");//服务地址
		call.setOperationName(new QName("http://ws.enjoy.com/","getCityInfo"));
	 	  //参数设置,这里写cityName是服务端通过注解配置的,如果服务端不指定,需要写args0
        call.addParameter("cityName",XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);
	    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
	    String res = (String) call.invoke(new Object[]{"北京"});
		System.out.println(res);
	}

}

Obtenga el resultado, la llamada de servicio es exitosa

 

En segundo lugar, el método springboot es esencialmente el mismo que el método xml.Los siguientes pasos se comparan con los pasos anteriores para construir el método springboot.

1. Cree un proyecto maven, seleccione el paquete war, introduzca las dependencias, preste atención a la selección de la versión del padre, aquí hay un hoyo, hablemos de ello en detalle a continuación

<parent>
  		<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
  </parent>
  
  <dependencies>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        
        <dependency> 
			<groupId>org.apache.cxf</groupId> 
			<artifactId>cxf-rt-frontend-jaxws</artifactId> 
			<version>3.3.0</version> 
		</dependency> 
		
		<dependency> 
			<groupId>org.apache.cxf</groupId> 
			<artifactId>cxf-rt-transports-http</artifactId> 
			<version>3.3.0</version> 
		</dependency>
        
    </dependencies>

2. Escribir interfaz de servicio

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService
public interface WeatherService {
	
	@WebMethod
	@WebResult(name = "String")
	public String getCityInfo(@WebParam(name="cityName")String cityName);
	
}

3. Escriba la clase de implementación de la interfaz, la anotación de servicio aquí es para inyectar esta clase de implementación en el contenedor de primavera, o puede inyectarse a través de la clase de configuración

import org.springframework.stereotype.Service;
import com.enjoy.service.WeatherService;
@Service
public class WeatherServiceImpl implements WeatherService{

	@Override
	public String getCityInfo(String cityName) {
		String res = "";
		if(cityName.equals("北京")) {
			res = cityName+":大雨";
		}
		if(cityName.equals("上海")) {
			res = cityName+":多云";
		}
		return res;
	}
}

4. Configure la clase, configure la interceptación de cxf, configure la ruta del servicio WeatherServiceImpl

import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.enjoy.service.WeatherService;


@Configuration
public class WSConfig {
	
		@Autowired
		private WeatherService WeatherServiceImpl;
	
	//这个相当于在web.xml中配置cxf的拦截配置
		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Bean(name="disServlet")
        /*这里有一个坑,如果bean的name属性不指定,则默认引用方法名称dispatcherServlet,
          在不同的springboot版本中效果不同,在2.0.3中可以正常启动,高版本会报错,
          这是因为会覆盖掉默认的dispatcherServlet,所以这个注入的bean的名字不能用 
          dispatcherServlet,要不就在bean的name属性上指定,要么就将方法名换成别的
        */
		public ServletRegistrationBean dispatcherServlet() {
			return new ServletRegistrationBean(new CXFServlet(), "/ws/*");
		}
		
		@Bean(name = Bus.DEFAULT_BUS_ID)
		public SpringBus springBus() {
		    return new SpringBus();
		}
		
		@Bean
		public Endpoint endpoint() {
            //指定weatherService服务的路径
		    EndpointImpl endpoint = new EndpointImpl(springBus(), WeatherServiceImpl);
		    endpoint.publish("/weather");
		    return endpoint;
		}

5. Escribe un método principal para iniciar el proyecto.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}

6. Prueba, ingresa localhost: 8080 / ws / weather? Wsdl en el navegador.

Reglas: ip + puerto + ruta de interceptación cxf configurada + ruta de clase de servicio +? Wsdl, debido a que springboot no configura la ruta del proyecto y el puerto, no hay ruta del proyecto y el puerto predeterminado es 8080. Si desea modificarlo, puede modificarlo en el archivo de configuración.

Servicio publicado con éxito

Utilice el método principal de prueba anterior, complete los parámetros y pruebe para obtener el valor de retorno

import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
public class Weather {
	
	public static void main(String[] args) throws Exception {
		Service service = new Service();
		Call call = service.createCall();
		call.setTargetEndpointAddress("http://localhost:8080/ws/weather?wsdl");//服务地址
		String add2= "http://service.enjoy.com/";
		call.setOperationName(new QName(add2,"getCityInfo"));
	 	  //参数设置
        call.addParameter("cityName",XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);
	    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
	    String res = (String) call.invoke(new Object[]{"上海"});
		System.out.println(res);
	}

}

 

Supongo que te gusta

Origin blog.csdn.net/csdnbeyoung/article/details/95546507
Recomendado
Clasificación