Rest Service 常见结构

来源:互联网 发布:长春亿成网络技术开发 编辑:程序博客网 时间:2024/06/11 16:32

Rest Service 常见结构

Restful API目前是非常常见的一种构建API的信息,下面是关于jaxrs/swagger 这种常见方式的一个介绍:
- API 类
- JSON Model 类
- Filter 类
- web.xml配置

API 类

一般的API类中包含:
- Path(请求路径)
- Http Method(请求方法)

如下例: 所有的请求路径,请求参数,都是一目了然的。同时返回也是Response也是标准的jaxrs Resp

@Path("/estimates")@com.wordnik.swagger.annotations.Api(value = "/estimates", description = "the estimates API")public class EstimatesApi {  @GET  @Path("/price")  @com.wordnik.swagger.annotations.ApiOperation(value = "Price Estimates", notes = "The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.<br><br>The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier. ", response = PriceEstimate.class, responseContainer = "List")  @com.wordnik.swagger.annotations.ApiResponses(value = {     @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "An array of price estimates by product"),    @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "Unexpected error") })  public Response estimatesPriceGet(@ApiParam(value = "Latitude component of start location.",required=true) @QueryParam("start_latitude") Double start_latitude,    @ApiParam(value = "Longitude component of start location.",required=true) @QueryParam("start_longitude") Double start_longitude,    @ApiParam(value = "Latitude component of end location.",required=true) @QueryParam("end_latitude") Double end_latitude,    @ApiParam(value = "Longitude component of end location.",required=true) @QueryParam("end_longitude") Double end_longitude)      throws NotFoundException {      // do some magic!      return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();  }

JSON Model 类

通过注解方式构建API的JSON Model 类,每个属性通过注解描述,都是非常清楚的

@ApiModel(description = "")public class Activities  {  private Integer offset = null;  private Integer limit = null;  private Integer count = null;  private List<Activity> history = new ArrayList<Activity>() ;  /**   * Position in pagination.   **/  @ApiModelProperty(required = false, value = "Position in pagination.")  @JsonProperty("offset")  public Integer getOffset() {    return offset;  }  public void setOffset(Integer offset) {    this.offset = offset;  }  /**   * Number of items to retrieve (100 max).   **/  @ApiModelProperty(required = false, value = "Number of items to retrieve (100 max).")  @JsonProperty("limit")  public Integer getLimit() {    return limit;  }  public void setLimit(Integer limit) {    this.limit = limit;  }  /**   * Total number of items available.   **/  @ApiModelProperty(required = false, value = "Total number of items available.")  @JsonProperty("count")  public Integer getCount() {    return count;  }  public void setCount(Integer count) {    this.count = count;  }  /**   **/  @ApiModelProperty(required = false, value = "")  @JsonProperty("history")  public List<Activity> getHistory() {    return history;  }  public void setHistory(List<Activity> history) {    this.history = history;  }  @Override  public String toString()  {    StringBuilder sb = new StringBuilder();    sb.append("class Activities {\n");    sb.append("  offset: ").append(offset).append("\n");    sb.append("  limit: ").append(limit).append("\n");    sb.append("  count: ").append(count).append("\n");    sb.append("  history: ").append(history).append("\n");    sb.append("}\n");    return sb.toString();  }}

Filter类

使用Filter类可以定制一些过滤器,如下例:

public class ApiOriginFilter implements javax.servlet.Filter {    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {        HttpServletResponse res = (HttpServletResponse) response;        res.addHeader("Access-Control-Allow-Origin", "*");        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");        res.addHeader("Access-Control-Allow-Headers", "Content-Type");        chain.doFilter(request, response);    }    @Override    public void destroy() {    }    @Override    public void init(FilterConfig filterConfig) throws ServletException {    }}

上例没有做任何特殊的事情,只是给response 加了一些header

web.xml 配置

<?xml version="1.0" encoding="ISO-8859-1"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  <servlet>    <servlet-name>jersey</servlet-name>    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>    <init-param>      <param-name>com.sun.jersey.config.property.packages</param-name>      <param-value>com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;io.swagger.api</param-value>    </init-param>    <init-param>      <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>      <param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>    </init-param>    <init-param>      <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>      <param-value>true</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet>    <servlet-name>DefaultJaxrsConfig</servlet-name>    <servlet-class>com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class>    <init-param>      <param-name>api.version</param-name>      <param-value>1.0.0</param-value>    </init-param>    <init-param>      <param-name>swagger.api.title</param-name>      <param-value>Swagger Server</param-value>    </init-param>    <init-param>      <param-name>swagger.api.basepath</param-name>      <param-value>http://localhost:8002</param-value>    </init-param>    <load-on-startup>2</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>jersey</servlet-name>    <url-pattern>/*</url-pattern>  </servlet-mapping>  <filter>    <filter-name>ApiOriginFilter</filter-name>    <filter-class>io.swagger.api.ApiOriginFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>ApiOriginFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping></web-app>
0 0