![](/img/trans.png)
[英]How to create/call a rest controller in springboot with both path and request parameter
[英]REST: How do I build a request path with a parameter as first token?
我是RESTful服務的新手。 我通常在JBoss / Wildfly環境中開發Java EE應用程序和SOAP服務。 我目前正在嘗試尋找進入RESTful服務的方式,以擴展我的知識。 由於我對JBoss / Wildfly感到熟悉,因此決定選擇RESTEasy。
我決定為示例寵物店鏈創建RESTful服務。 作為一個連鎖店,寵物店有多個商店,這些商店由商店ID標識(例如shop1,shop2等)。 我創建了多個REST服務,以基於技術功能對服務進行細分(例如,文章服務=> article.war,訂購服務=> orde.war等。
我想創建可讀的URL,例如:
得到:
http://mypetshop.example/rest/ {shopId} / article / {articleId}
使用JSON格式的訂單內容進行POST:
http://mypetshop.example/rest/ {shopId} / order / create
到目前為止,我只設法創建了如下URL:
得到:
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;
}
}
是的,你可以做
像下面
休息/訂單/ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.