![](/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.