Spring整合CXF,发布RSETful 风格WebService

import javax.ws.rs.core.MediaType;

import com.hoo.entity.MapBean;

import com.hoo.entity.User;

import com.hoo.entity.Users;

/*

注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。

@Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。

@GET:这意味着以下方法可以响应 HTTP GET 方法。

@Produces:以纯文本方式定义响应内容 MIME 类型。

@Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。

@Path(“{contact}”):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。

@PathParam(“contact”):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。

@Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。

*/

/**

* function: CXF RESTful风格WebService

* @author hoojo

* @createDate 2012-7-20 下午01:23:04

* @file RESTSampleSource.java

* @package com.hoo.service

* @project CXFWebService

* @blog http://blog.csdn.net/IBM_hoojo

* @email hoojo_@126.com

* @version 1.0

*/

@Path(value = “/sample”)

public interface RESTSample {

@GET

@Produces(MediaType.TEXT_PLAIN)

public String doGet();

@GET

@Produces(MediaType.TEXT_PLAIN)

@Path(“/request/{param}”)

public String doRequest(@PathParam(“param”) String param,

@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse);

@GET

@Path(“/bean/{id}”)

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public User getBean(@PathParam(“id”) int id);

@GET

@Path(“/list”)

@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })

public Users getList();

@GET

@Path(“/map”)

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public MapBean getMap();

/*

@Consumes:声明该方法使用 HTML FORM。

@FormParam:注入该方法的 HTML 属性确定的表单输入。

@Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。

您可以使用 http://localhost:8080/Jersey/rest/contacts/ 访问新联系人

*/

@POST

@Path(“/postData”)

public User postData(User user) throws IOException;

@PUT

@Path(“/putData/{id}”)

@Consumes(MediaType.APPLICATION_XML)

public User putData(@PathParam(“id”) int id, User user);

@DELETE

@Path(“/removeData/{id}”)

public void deleteData(@PathParam(“id”) int id);

}

二、RESTSample接口的实现,这里我们只是简单的实现下,并不是涉及实际的具体业务

package com.hoo.service;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.DELETE;

import javax.ws.rs.GET;

import javax.ws.rs.POST;

import javax.ws.rs.PUT;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

import javax.ws.rs.Produces;

import javax.ws.rs.core.Context;

import javax.ws.rs.core.MediaType;

import javax.ws.rs.core.Request;

import javax.ws.rs.core.UriInfo;

import com.hoo.entity.MapBean;

import com.hoo.entity.User;

import com.hoo.entity.Users;

/*

注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。

@Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。

@GET:这意味着以下方法可以响应 HTTP GET 方法。

@Produces:以纯文本方式定义响应内容 MIME 类型。

@Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。

@Path(“{contact}”):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。

@PathParam(“contact”):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。

@Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。

*/

/**

* function: CXF RESTful风格WebService

* @author hoojo

* @createDate 2012-7-20 下午01:23:04

* @file RESTSampleSource.java

* @package com.hoo.service

* @project CXFWebService

* @blog http://blog.csdn.net/IBM_hoojo

* @email hoojo_@126.com

* @version 1.0

*/

@Path(value = “/sample”)

public class RESTSampleSource implements RESTSample {

@Context

private UriInfo uriInfo;

@Context

private Request request;

@GET

@Produces(MediaType.TEXT_PLAIN)

public String doGet() {

return “this is get rest request”;

}

@GET

@Produces(MediaType.TEXT_PLAIN)

@Path(“/request/{param}”)

public String doRequest(@PathParam(“param”) String param,

@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) {

System.out.println(servletRequest);

System.out.println(servletResponse);

System.out.println(servletRequest.getParameter(“param”));

System.out.println(servletRequest.getContentType());

System.out.println(servletResponse.getCharacterEncoding());

System.out.println(servletResponse.getContentType());

return “success”;

}

@GET

@Path(“/bean/{id}”)

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public User getBean(@PathParam(“id”) int id) {

System.out.println(“####getBean#####”);

System.out.println(“id:” + id);

System.out.println(“Method:” + request.getMethod());

System.out.println(“uri:” + uriInfo.getPath());

System.out.println(uriInfo.getPathParameters());

User user = new User();

user.setId(id);

user.setName(“JojO”);

return user;

}

@GET

@Path(“/list”)

@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })

public Users getList() {

System.out.println(“####getList#####”);

System.out.println(“Method:” + request.getMethod());

System.out.println(“uri:” + uriInfo.getPath());

System.out.println(uriInfo.getPathParameters());

List list = new ArrayList();

User user = null;

for (int i = 0; i < 4;i ++) {

user = new User();

user.setId(i);

user.setName(“JojO-” + i);

list.add(user);

}

Users users = new Users();

users.setUsers(list);

return users;

}

@GET

@Path(“/map”)

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public MapBean getMap() {

System.out.println(“####getMap#####”);

System.out.println(“Method:” + request.getMethod());

System.out.println(“uri:” + uriInfo.getPath());

System.out.println(uriInfo.getPathParameters());

Map<String, User> map = new HashMap<String, User>();

User user = null;

for (int i = 0; i < 4;i ++) {

user = new User();

user.setId(i);

user.setName(“JojO-” + i);

map.put(“key-” + i, user);

}

MapBean bean = new MapBean();

bean.setMap(map);

return bean;

}

/*

@Consumes:声明该方法使用 HTML FORM。

@FormParam:注入该方法的 HTML 属性确定的表单输入。

@Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。

您可以使用 http://localhost:8080/Jersey/rest/contacts/ 访问新联系人

*/

@POST

@Path(“/postData”)

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public User postData(User user) throws IOException {

System.out.println(user);

user.setName(“jojo##12321321”);

return user;

}

@PUT

@Path(“/putData/{id}”)

@Produces({ MediaType.APPLICATION_XML })

public User putData(@PathParam(“id”) int id, User user) {

System.out.println(“#####putData#####”);

System.out.println(user);

user.setId(id);

user.setAddress(“hoojo#gz”);

user.setEmail(“hoojo_@126.com”);

user.setName(“hoojo”);

System.out.println(user);

return user;

}

@DELETE

@Path(“/removeData/{id}”)

public void deleteData(@PathParam(“id”) int id) {

System.out.println(“#######deleteData#######” + id);

}

}

三、配置我们的WebService,修改applicationContext-server.xml。这里主要是添加jaxrs标签的支持,修改头部文件如下:

<?xml version\="1.0" encoding\="UTF-8"?\>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:context\="http://www.springframework.org/schema/context"
xmlns:jaxws\="http://cxf.apache.org/jaxws"
**_xmlns:jaxrs\="http://cxf.apache.org/jaxrs"_**
xmlns:xsi\="http://www.w3.org/2001/XMLSchema-instance"
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://cxf.apache.org/jaxws 
http://cxf.apache.org/schemas/jaxws.xsd
**_http://cxf.apache.org/jaxrs_**
**_http://cxf.apache.org/schemas/jaxrs.xsd_**"\>

特别注意上面加粗带下划线的部分,这是新增加的配置。我们发布restful WebService需要用到它。

然后在配置文件中添加如下配置

<import resource=“classpath:META-INF/cxf/cxf.xml”/>

<import resource=“classpath:META-INF/cxf/cxf-extension-soap.xml”/>

<import resource=“classpath:META-INF/cxf/cxf-servlet.xml”/>

<bean id=“restSample” class=“com.hoo.service.RESTSampleSource”/>

<jaxrs:server id=“restServiceContainer” address=“/rest”>

<jaxrs:serviceBeans\>
    <ref bean\="restSample" />
</jaxrs:serviceBeans\>
<jaxrs:extensionMappings\>
    <entry key\="json" value\="application/json" />
    <entry key\="xml" value\="application/xml" />
</jaxrs:extensionMappings\>
<jaxrs:languageMappings\>
       <entry key\="en" value\="en-gb"/>  
</jaxrs:languageMappings\>

</jaxrs:server>

这样服务器端就完成了CXF RESTful WebService的发布,启动你的tomcat。然后在浏览器中服务地址:http://localhost:8000/CXFWebService/ (其实这里请求的是CXFServlet,你可以看看上一篇Spring整合CXF文章的web.xml的配置)

你就可以看到我们这里刚刚发布的RESTSample rest的WebService

你也可以看看里面的xml,也就是WebService的wsdl文件内容。我们找一个GET方式的WebService的方法,在浏览器中调用一下试试

http://localhost:8000/CXFWebService/rest/sample/bean/123

这个url对应到下面这个方法

@GET

@Path(“/bean/{id}”)

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public User getBean(@PathParam(“id”) int id)

结果如下

一篇xml文档内容。

四、编写客户端代码,调用RESTful WebService

package com.hoo.client;

import java.io.IOException;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hoo.entity.MapBean;

import com.hoo.entity.User;

import com.hoo.entity.Users;

import com.hoo.service.RESTSample;

/**

* function: RESTful风格WebService

* @author hoojo

* @createDate 2012-7-20 下午03:31:03

* @file RSETServiceClient.java

* @package com.hoo.client

* @project CXFWebService

* @blog http://blog.csdn.net/IBM_hoojo

* @email hoojo_@126.com

* @version 1.0

*/

public class RSETServiceClient {

private static WebClient client;
@Before
public void init() {
    // 手动创建webClient对象,注意这里的地址是发布的那个/rest地址
    //String url = "http://localhost:8000/CXFWebService/rest/";
    //client = WebClient.create(url);
    // 从Spring Ioc容器中拿webClient对象
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-client.xml");
    client = ctx.getBean("webClient", WebClient.class);
}
@After
public void destory(){
}
@Test
public void testGet() {
    System.out.println(client.path("sample").accept(MediaType.TEXT\_PLAIN).get(String.class));
总结一下

面试前要精心做好准备,简历上写的知识点和原理都需要准备好,项目上多想想难点和亮点,这是面试时能和别人不一样的地方。

还有就是表现出自己的谦虚好学,以及对于未来持续进阶的规划,企业招人更偏爱稳定的人。

万事开头难,但是程序员这一条路坚持几年后发展空间还是非常大的,一切重在坚持。

为了帮助大家更好更高效的准备面试,特别整理了《前端工程师面试手册》电子稿文件。

前端面试题汇总

  • 28
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
spring + cxf + restful + soap 方便初学者很快上手。 注解描述 @Path注解的值是一个相对的URI路径,这个路径指定了该Java类的位置,例如/helloworld。在这个URI中可以包含变量,例如可以获取用户的姓名然后作为参数传入URI中:/helloworld/{username}。 @GET注解是请求方法指示符,这个指示符注解的Java方法会处理HTTPGET请求。资源的行为由资源回应的HTTP方法决定。 @POST注解是请求方法指示符,这个指示符注解的Java方法会处理HTTPPOST请求。资源的行为由资源回应的HTTP方法决定。 @PUT注解是请求方法指示符,这个指示符注解的Java方法会处理HTTPPUT请求。资源的行为由资源回应的HTTP方法决定。 @DELETE注解是请求方法指示符,这个指示符注解的Java方法会处理HTTPDELETE请求。资源的行为由资源回应的HTTP方法决定。 @HEAD注解是请求方法指示符,这个指示符注解的Java方法会处理HTTPHEAD请求。资源的行为由资源回应的HTTP方法决定。 @PathParam注解是可以抽取并用在资源类中的一类参数。URIpath参数是从请求的URI中抽取的,而且参数的名称和@Path注解中定义的变量名对应。 @QueryParam注解是可以抽取并在资源类中使用的一类参数。Query参数是从请求URI的查询参数中抽取的。 @Consumes注解是用来指定资源能够接受的客户发送的MIME媒体类型。 @Produces注解用来指定资源能够生成并发送给客户端的MIME媒体类型,例如“text/plain”. @Provider注解用在任何对JAX-RS运行时(如MessageBodyReader和MessageBodyWriter)有意义的事物上。对HTTP请求,MessageBodyReader用来将HTTP请求实体段映射为方法参数。在响应的时候,返回的值使用MessageBodyWriter来映射成HTTP响应实体段。如果应用程序需要提供其他的元数据,如HTTP头或不同的状态代码,方法可以返回一个打包了实体的Response,该Response可以使用Response.ResponseBuilder创建。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值