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>