Customized content handling
Scooter comes with a default content handler which can handle content in html, json, text, and xml. But what if you want response content to be returned in pdf format or excel format? It is fairly easy. Just do the following:
- Call the view in Controller class by using render methods
- Write a content handler plugin
- Register the plugin in environment.properties
- Put your plugin class in a jar file in the plugins directory
Call the view in Controller class by using render methods
You can specify the response content type by using the overloaded render method:
public class PostsController { /** * show method returns a post record. * Example request url: GET /posts/101 */ public String show() { ActiveRecord post = Post.findById(p("id")); if (post == null) { flash("notice", "There is no post record with primary key id as " + p("id") + "."); } return render(post, "pdf");//return result in pdf format } }
Write a content handler plugin
To let Scooter knows that you need to handle content of pdf, you simply write a content handler plugin class. A content handler knows how to convert the content to the format you choose.
The following is an example implementation of MyPDFHandler:
package com.example.pdf; import com.scooterframework.admin.Plugin; import com.scooterframework.web.controller.ContentHandler; public class MyPDFHandler extends Plugin implements ContentHandler { /** * Handles result content of a http request. The format is the * format corresponding to a mime type such as "html", "xml" etc. * * @param request The http request object. * @param response The http response object. * @param content The content to be sent. * @param format The content format. * @throws IOException * @throws ServletException */ public void handle( HttpServletRequest request, HttpServletResponse response, Object content, String format) throws IOException, ServletException { ... } }
You can see an implementation of handle method in com.scooterframework.web.controller.DefaultContentHandler.
Register the plugin in environment.properties
Registering a content handler plugin in the environment.properties property file:
# Configure a pdf content handler plugin to return content in pdf format: plugin.content.handler.pdf=\ plugin_class=com.example.pdf.MyPDFHandler
You can add other properties too if your handler class requires some special properties:
# Configure a pdf content handler plugin to return content in pdf format: plugin.content.handler.pdf=\ plugin_class=com.example.pdf.MyPDFHandler,\ other_property_name=other_value,\ more_property_name=more_value
When you register the plugin, please follow the naming convention of the content handler plugin:
plugin.content.handler.{content format}=...
Put your plugin class in a jar file in the plugins directory
All jar files in the plugins directory are loaded by the framework at startup time. Other required 3rd-party jar files should also be there in the same subdirectory.