CXF JAX-RS实现Rest service
1. Resource
import javax.ws.rs.*;
@Path(value = "/student")
public interface StudentService
{
@GET
@Path(value = "/getinfo")
@Produces({"application/xml","application/json"})
Student getStudent(@PathParam("id") long id);
@POST
@Path(value = "/addinfo")
@Produces({"application/xml","application/json"})
void addStudent(Student stu);
}
2. Resource 的实现类
public class StudentServiceImpl implements StudentService
{
public Student getStudent(long id)
{
Student s = new Student();
s.setId(id);
s.setName("abc");
return s;
}
public void addStudent(Student stu) {
// TODO Auto-generated method stub
System.out.println(stu);
System.out.println(stu.getName());
}
}
3. JavaBean
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student
{
private long id;
private String name;
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
4. Server 配置
public class App
{
public static void main( String[] args )
{
Map<Object,Object> extend = new HashMap<Object,Object>();
extend.put("json", "application/json");
extend.put("xml", "application/xml");
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(StudentService.class);
sf.setResourceProvider(StudentService.class, new SingletonResourceProvider(new StudentServiceImpl()));
sf.setAddress("http://localhost:9000/");
sf.setExtensionMappings(extend);
BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = new JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
sf.create();
}
}
5、Spring config example
jaxrs:server id="restServer" address="/rest/">
<jaxrs:serviceBeans>
<ref bean="helloWorldService"/>
</jaxrs:serviceBeans>
<jaxrs:extensionMappings>
<entry key="feed" value="application/atom+xml"/>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
<entry key="html" value="text/html"/>
</jaxrs:extensionMappings>
</jaxrs:server>