Nov
18
2012

wicket – rest

How to have REST in wicket application?

As you know you have you have wicket-rest project , but when I wanted to use it but I could not, because it does not work on 1.5.x version of wicket. There are a few exceptions after you change the code so you can compile … After some searching I had to create my version of this feature.

public abstract class AbstractRestPage extends WebPage {
public static final String POST = "POST";
public static final String PUT = "PUT";
public static final String GET = "GET";
public static final String DELETE = "DELETE";

public AbstractRestPage(PageParameters params) {
super(params);
}

@Override
public final boolean hasAssociatedMarkup() {
return false;
}

public abstract void doGet(PageParameters params);

public abstract void doPost(PageParameters params);

public abstract void doPut(PageParameters params);

public abstract void doDelete(PageParameters params);

@Override
public final void renderPage() {
HttpServletRequest servletReq = (HttpServletRequest) getRequest()
.getContainerRequest();
String method = servletReq.getMethod();
if (POST.equals(method)) {
doPost(getPageParameters());
} else if (GET.equals(method)) {
doGet(getPageParameters());
} else if (PUT.equals(method)) {
doPut(getPageParameters());
} else if (DELETE.equals(method)) {
doDelete(getPageParameters());
}

getResponse().write(getResponce());
}

protected abstract String getResponce();
}
//———————————
public abstract class RestJsonRequestPage extends AbstractRestPage {

private transient GsonBuilder builder;

public RestJsonRequestPage(PageParameters params) {
super(params);
builder = new GsonBuilder();
}

@Override
public final MarkupType getMarkupType() {
return new MarkupType(“json”, “application/json”);
}

protected final String getResponce() {
Gson gson = builder.create();
return gson.toJson(getDefaultModelObject());
}
———————-

In order to have your own rest page, just extend
RestJsonRequestPage and implement get, post .. methods.

if you use maven then you would need Gson
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.2.2</version>
</dependency>

Hope you find this code useful .

Comments are closed.

Twitter

Stop censorship