使用CXF开发JAX-RS类型的WebService

1、JAXRSServerFactoryBean编程方式

访问方式:http://localhost:8080/cxf_spring_rest_server/ws/rest/student/querylist/001?_type=json

发布类:

public class StudentServer {
    public static void main(String[] args) {
        
        //使用jaxrsServerFactoryBean发布rest服务
        JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
        //设置rest的服务地址
        jaxrsServerFactoryBean.setAddress("http://127.0.0.1:12345/rest");
        //设置服务对象
        jaxrsServerFactoryBean.setServiceBean(new StudentServiceImpl());
        //设置资源 对象,如果有多个pojo资源 对象中间以半角逗号隔开
        jaxrsServerFactoryBean.setResourceClasses(StudentServiceImpl.class);
        //发布rest服务
        jaxrsServerFactoryBean.create();
        
        
    }
}

接口类:

@WebService
@Path("/student")
public interface StudentService {
    
    //查询学生信息
    @GET //http的get方法
    @Path("/query/{id}")//id参数通过url传递
    @Produces(MediaType.APPLICATION_XML)//设置媒体类型xml格式
    public Student queryStudent(@PathParam("id")long id);
    
    
    //查询学生列表
    @GET //http的get方法
    @Path("/querylist/{type}")
    @Produces({"application/json;charset=utf-8",MediaType.APPLICATION_XML})//设置媒体类型xml格式和json格式
    //如果想让rest返回xml需要在rest的url后边添加?_type=xml,默认为xml
    //如果想让rest返回json需要在rest的url后边添加?_type=json
    public List<Student> queryStudentList(@PathParam("type") String type);

}

实现类:

public class StudentServiceImpl implements StudentService {

    @Override
    public Student queryStudent(long id) {
        // 使用静态数据
        Student student = new Student();
        student.setId(id);
        student.setName("张三");
        student.setBirthday(new Date());
        return student;
    }

    @Override
    public List<Student> queryStudentList(String type) {
        // 使用静态数据
        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student();
        student1.setId(1000l);
        student1.setName("张三");
        student1.setBirthday(new Date());
        
        Student student2 = new Student();
        student2.setId(1000l);
        student2.setName("张三");
        student2.setBirthday(new Date());
        
        list.add(student1);
        list.add(student2);
        return list;
    }

}

 2、与spring整合

<!-- service -->
<bean id="studentService" class="cn.allan.ws.cxf.rest.service.StudentServiceImpl"/>

<!-- 发布rest服务
使用jaxws:server和jaxws:endpoint可以发布服务
webservice地址=tomcat地址+cxf servlet的路径+/weather
 -->
<jaxrs:server address="/rest">
    <jaxrs:serviceBeans>
       <ref bean="studentService"/>
    </jaxrs:serviceBeans>
</jaxrs:server>

 

转载于:https://www.cnblogs.com/laoyeye/p/6519846.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值