写点什么

CXF webservice 之手动启动服务方法(restful )

  • 2022 年 4 月 25 日
  • 本文字数:1318 字

    阅读完需:约 4 分钟

<dependency>


<groupId>javax.ws.rs</groupId>


<artifactId>jsr311-api</artifactId>


<version>1.1.1</version>


</dependency>


<dependency>


<groupId>org.apache.cxf</groupId>


<artifactId>cxf-rt-frontend-jaxws</artifactId>


<version>3.1.4</version>


</dependency>


<dependency>


<groupId>org.apache.cxf</groupId>


<artifactId>cxf-rt-transports-http</artifactId>


<version>3.1.4</version>


</dependency>


<dependency>


<groupId>org.apache.cxf</groupId>


<artifactId>cxf-rt-transports-http-jetty</artifactId>


<version>3.1.4</version>


</dependency>


<dependency>


<groupId>org.apache.cxf</groupId>


<artifactId>cxf-rt-frontend-jaxrs</artifactId>


<version>3.1.4</version>


</dependency>


<dependency>


<groupId>org.codehaus.jettison</groupId>


<artifactId>jettison</artifactId>


<version>1.3</version>


</dependency>


<dependency>


<groupId>org.codehaus.jackson</groupId>


<artifactId>jackson-jaxrs</artifactId>


<version>1.9.8</version>


</dependency>


第三步:服务器端实现:Service.class


@Path("/baoxian")


@Produces({ MediaType.APPLICATION_JSON })


public class BaoXianService {


private final static Log logger = LogFactory.getLog(BaoXianService.class);


@GET


@Path("/before/{vincode}")


public String getinfo(@PathParam("vincode") String vincode,


@QueryParam("name") String name) {


System.out.println(vincode);


String ret = "my name is :" + name;


return ret;


}


@POST


@Path("/post/query")


@Consumes({ "application/json", "application/xml" })


pub 《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 lic String Before_query(String bx) throws Exception {


System.err.println(bx);


return bx;


}


}


下面提供了两种最基本的 GET 和 POSt 方法,目的是为了测试数据的传递;需要扩展的自行添加;


第四步:手动启动服务类:


public class Server {


public static void main(String[] args) {


//String address = PropertyUtil.getProperties("ADDRESS");


//BaoXianService bxservice = new BaoXianService();


// Service instance


<span style="white-space:pre"> </span>String address = "http://localhost:8080/rest";//端口号和端口号后面的是可以自定义的;但是要与客户端请求的地址对应;否则不会识别,无法访问


JAXRSServerFactoryBean restServer = new JAXRSServerFactoryBean();


restServer.setResourceClasses(Detail.class);


restServer.getInInterceptors().add(new IpAddressInInterceptor());//自定义的拦截器


restServer.setServiceBean(bxservice);


restServer.setAddress(address);


restServer.create();


}


服务启动成功:


第五步:客户端测试:


static String baseAddress = "localhost:8080/rest";//与启动类的地址相同


public static void main(String[] args) {


String data = "{"name":"zhangsan"}";


WebClient webclient = WebClient.create(baseAddress);


webclient.path("post/query")


.accept(MediaType.APPLICATION_JSON)


.type(MediaType.APPLICATION_JSON);

用户头像

还未添加个人签名 2022.04.13 加入

还未添加个人简介

评论

发布
暂无评论
CXF webservice之手动启动服务方法(restful )_Java_爱好编程进阶_InfoQ写作社区