Passing POST Data as JSON

20 views
Skip to first unread message

Craig Phillips

unread,
Dec 5, 2013, 11:09:53 AM12/5/13
to mojav...@googlegroups.com
Thanks again for the framework. The application I'm building using Mojave is slowly coming together and its been great having an MVC framework that works with Guice.

I'm attempting to create a couple of action methods that respond to POST requests that provide data via JSON in the request body and I'm having trouble figuring out how to get at that data to convert it from JSON into my standard Java objects.

I've used Gson to convert to and and from JSON data before so that part I can handle. In fact, I'm already converting from POJOs to JSON for a couple of action methods which don't take any arguments. For example:

              /* Retrieves the default menu for the current user.

       * @return The JSON representation of the default menu for the current user.

       */

       @Action("default")

       @POSTAction

       public JSON getDefaultMenu() {

               MenuViewModel viewModel = menuViewModelProvider.get();

                              /* Logic to add data to viewModel goes here but is omitted for brevity. */

               return new JSON(jsonSerializer.toJson(viewModel));

       }


In that example, jsonSerializer is a an object of type Gson provided via Guice injection in the constructor. Now I'm trying to do the opposite and convert JSON data coming from the client into POJOs for my controller.

My first attempt at this was to write an action method interceptor that inspects the incoming request, converts the request body from JSON into POJOs and then assigns them to the correct arguments in the action method. So I did this:
  1. Created a class called JsonPostParameterTranslator which has a method marked with the @BeforeAction annotation and is registered with an @InterceptedBy annotation on the relevant controller.
  2. Get the HttpServletRequest object via the RequestContext that is passed to @BeforeAction-annotated method.
  3. Open the input stream representing the request body on the HttpServletRequest object.
At this point, an exception is thrown indicating that the reader on the request object has already been opened so I can't get that content. Digging into the MojaveMVC source, that makes sense since HttpActionInvoker (line 92) opens the input stream representing the request body itself in order to assign values to arguments.

Before digging any further, I thought I would ask if you have a suggested approach for proceeding here. Any thoughts? Is there an attribute I should be assigning to my action method parameters to make them available to that interceptor? Some other way to get at that request data? Or a different approach entirely?

Thanks in advance for any help you're able to give and again nice work on the framework!

Craig

Reply all
Reply to author
Forward
0 new messages