我是RESTful服务的新手。我通常在JBoss / Wildfly环境中开发Java EE应用程序和SOAP服务。我目前正试图找到进入RESTful服务的方式来拓宽我的知识面。由于我对JBoss / Wildfly很熟悉,所以我决定选择RESTEasy。
我决定为示例宠物连锁店创建一个RESTful服务。作为连锁店,宠物店有多个商店,这些商店由商店ID(例如商店1,商店2等)识别。我已经创建了多个REST服务来根据技术功能对服务进行细分(例如,文章服务=> article.war,订单服务=> orde.war等。
我想创建人类可读的网址,例如:
GET:
http://mypetshop.example/rest/ {shopId} /条/ {条款ArticleID}
使用JSON格式化订单内容的POST:
http://mypetshop.example/rest/ {shopId} /顺序/创建
到目前为止,我只设法创建了以下网址:
GET:
http://mypetshop.example/rest/article/ {shopId} / {条款ArticleID}
使用JSON格式化订单内容的POST:
http://mypetshop.example/rest/order/create/ {shopId}
我想要的REST路径是否可行,还是我必须跟上当前的解决方案?
祝你好运, CB
以下是文章服务的示例代码:
ArticleRestApplication.java:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath(ArticleRestApplication.ROOT_PATH)
public class OrderRestApplication extends Application {
public static final String ROOT_PATH = "/article";
}
ArticleService.java
public interface ArticleService{
Article getArticle(String shopId, Integer articleId);
}
ArticleServiceImpl.java:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
@Path("/")
@Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public class ArticleServiceImpl implements ArticleService {
public ArticleServiceImpl() {
super();
}
@GET
@Path("/{shopId}/{articleId}")
public Article getArtikel(
@PathParam("shopId") String shopId,
@PathParam("articleId") Integer articleId) {
System.out.println(String.format("Shop ID: \"%s\"", shopId));
System.out.println(String.format("Article ID: \"%s\"", articleId));
return gson.toJson(new Article(articleId));
}
}
Article.java:
import java.io.Serializable;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlRootElement;
@SuppressWarnings("serial")
@XmlRootElement(name = "article")
public class Article implements Serializable {
private String shopId;
private int articleId;
private String name = "Super pet food";
private BigDecimal price = new BigDecimal("1.00");
private int unitsInStock = 1000;
public Article(String shopId, int articleId) {
super();
this.shopId = shopId;
this.articleId = articleId;
}
}
答案 0 :(得分:1)
是的,你可以做到 如下所示
<强>休息/命令/ 1 /完成强>
这里休息的是servlet路径,类的命令,然后使用@Path("{orderId}/completed")
@Path("orders")
public class OrderService {
@GET
@Path("{orderId}/completed")
public String getOrders(@PathParam("orderId") String orderId) {
return "orderId: " + orderId;
}
@GET
@Path("summary")
public String getOrdersSummary() {
return "orders summary";
}
}
http://jerseyexample-ravikant.rhcloud.com/rest/orders/1/completed
的现场演示