[英]Use Wicket as a REST API
我需要Wicket來響應AngularJS的發布請求。
我在wicket中設置了這樣的頁面,但請求參數始終為空
@MountPath(value = "/api/my/rest/url")
public class MyPostHandler extends SecureWebPage {
public MyPostHandler () {
final WebRequest webRequest = (WebRequest) getRequest();
final HttpServletRequest rawRequest = (HttpServletRequest) webRequest.getContainerRequest();
if (rawRequest.getMethod().equalsIgnoreCase("POST")) {
webRequest.getRequestParameters().getParameterNames(); //Returns an empty list
webRequest.getPostParameters().getParameterNames(); //Returns an empty list
}
}
}
發送POST請求的AngularJS代碼如下所示:
$http.post('/api/my/rest/url', {some:"data", other:"stuff"});
知道這里出了什么問題嗎? 謝謝!
不知道這是否是最好的解決方案,但是以下代碼對我有用
@MountPath(value = "/api/my/rest/url")
public class MyPostHandler extends SecureWebPage {
public MyPostHandler () {
final WebRequest webRequest = (WebRequest) getRequest();
final HttpServletRequest rawRequest = (HttpServletRequest) webRequest.getContainerRequest();
if (rawRequest.getMethod().equalsIgnoreCase("POST")) {
BufferedReader br;
try {
br = rawRequest.getReader();
String jsonString = br.readLine();
//Do something with the JSON here
}
catch (IOException e) {
}
}
}
}
我遇到的另一個潛在解決方案是該項目https://github.com/bitstorm/Wicket-rest-annotations
WicketStuff REST注釋可以通過對JSON序列化/反序列化的內置支持來幫助完成此任務。
我在我的一個項目中使用了Wicket rest注釋 。 這是它的Maven存儲庫 。 請在下面找到一個例子:
的pom.xml
<dependency>
<groupId>org.wicketstuff</groupId>
<artifactId>wicketstuff-restannotations</artifactId>
<version>8.1.0</version>
</dependency>
<dependency>
<groupId>org.wicketstuff</groupId>
<artifactId>wicketstuff-restannotations-json</artifactId>
<version>8.1.0</version>
</dependency>
創建您的Wicket REST資源:
import org.wicketstuff.rest.annotations.MethodMapping;
import org.wicketstuff.rest.annotations.parameters.RequestBody;
import org.wicketstuff.rest.resource.gson.GsonRestResource;
import org.wicketstuff.rest.utils.http.HttpMethod;
public class MyPostHandler extends GsonRestResource {
@MethodMapping(value = "/my/rest/url", httpMethod = HttpMethod.POST)
public boolean handlePost(@RequestBody SomeObject someObject) {
...
}
}
然后在您的Wicket WebApplication init()方法中,注冊其余資源:
mountResource("/api", new ResourceReference("restReference") {
MyPostHandler resource = new MyPostHandler();
@Override
public IResource getResource() {
return resource;
}
});
REST Web服務啟動后,您可以發出HTTP POST請求:
POST URL: http://localhost:8080/api/my/rest/url
POST data: {json data for SomeObject}
Content-Type: application/json
而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.