JAX-RS开发 hello world

1.建立maven webapp工程aty-rest。

2. 在pom文件增加spring框架、jax-rs接口、CXF实现

  1. <dependency>
  2. <groupId>javax.ws.rs</groupId>
  3. <artifactId>javax.ws.rs-api</artifactId>
  4. <version>2.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework</groupId>
  8. <artifactId>spring-web</artifactId>
  9. <version>3.1.1.RELEASE</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.cxf</groupId>
  13. <artifactId>cxf-rt-frontend-jaxrs</artifactId>
  14. <version>3.0.0</version>
  15. </dependency>

3.编写rest接口和实现类

  1. public interface INameService
  2. {
  3. @GET
  4. @Path("/welcome/")
  5. @Produces(MediaType.APPLICATION_JSON)
  6. public String welcome();
  7. }
  8. //
  9. @Component("nameServiceImpl")
  10. public class NameServiceImpl implements INameService
  11. {
  12. public String welcome()
  13. {
  14. return "{\"name\":123}";
  15. }
  16. }

4.web.xml中启动sping和cxf

  1. <!-- Spring -->
  2. <context-param>
  3. <param-name>contextConfigLocation</param-name>
  4. <param-value>classpath:spring.xml</param-value>
  5. </context-param>
  6. <listener>
  7. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  8. </listener>
  9. <!-- CXF -->
  10. <servlet>
  11. <servlet-name>cxf</servlet-name>
  12. <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>cxf</servlet-name>
  16. <url-pattern>/rest/*</url-pattern>
  17. </servlet-mapping>

4.配置cxf-spring.xml,并在spring.xml中将其包含进去

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://cxf.apache.org/jaxrs
  8. http://cxf.apache.org/schemas/jaxrs.xsd">
  9. <jaxrs:server address="/greet">
  10. <jaxrs:serviceBeans>
  11. <ref bean="nameServiceImpl"/>
  12. </jaxrs:serviceBeans>
  13. </jaxrs:server>
  14. </beans>

5.用maven打包,将war部署到tomcat下。

一切正常即可通过http://127.0.0.1:8080/aty-rest/rest/greet/welcome访问我们发布的rest服务。

上一篇:Java nio 笔记:系统IO、缓冲区、流IO、socket通道


下一篇:Java的ResultSet中rs.next()含义