I've only just started to work with Wicket myself, but I would simply mount the resource as a shared resource with its own URL. You just override init()
in your Application
and register the resource with
getSharedResources().add(resourceKey, dynamicImageResource);
Then, you mount it as a shared resource with
mountSharedResource(path, resourceKey);
For some reason, that I still do not completely grasp, you have to prepend the class name of the application to the resource key you pass to mountSharedResource()
.
Let's add a fully working example for some bonus votes! First create an empty Wicket template with
mvn archetype:create -DarchetypeGroupId=org.apache.wicket
-DarchetypeArtifactId=wicket-archetype-quickstart
-DarchetypeVersion=1.4.0 -DgroupId=com.mycompany
-DartifactId=myproject
Then, override the init()
method in WicketApplication
by adding:
@Override
protected void init() {
final String resourceKey = "DYN_IMG_KEY";
final String queryParm = "id";
getSharedResources().add(resourceKey, new Resource() {
@Override
public IResourceStream getResourceStream() {
final String query = getParameters().getString(queryParm);
// generate an image containing the query argument
final BufferedImage img = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_RGB);
final Graphics2D g2 = img.createGraphics();
g2.setColor(Color.WHITE);
g2.drawString(query, img.getWidth() / 2, img.getHeight() / 2);
// return the image as a PNG stream
return new AbstractResourceStreamWriter() {
public String getContentType() {
return "image/png";
}
public void write(OutputStream output) {
try { ImageIO.write(img, "png", output); }
catch (IOException ex) { /* never swallow exceptions! */ }
}
};
}
});
mountSharedResource("/resource", Application.class.getName() + "/" +
resourceKey);
}
The little dynamic PNG resource just writes the query parameter on black background. Of course, you can access your DB or do whatever you like to produce the image data.
Finally, execute mvn jetty:run
, and you will be able to access the resource at this URL.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…