aiolos
aiolos

Reputation: 4697

How to set prefered view resolution when mixing GSP and JSON views

I'm maintaining a grails 3.3.8 app using the angularjs profile.

The REST API and angularjs assets are provided by the same grails application. For now I don't want to split the app into two applications.

The app uses JSON views to render the JSON response for the resources. The app also uses the GSP view plugin to provide the initial index.gsp to serve the angularjs app.

Due to the usage of the GSP view plugin the app always renders the default gsp error views instead of using the JSON views in case of 500, 404, 401, ... errors.

When I remove the grails-gsp plugin, all request are served with a JSON response. Also in case of an error. But then the index.gsp can't be rendered.

Is it possible to tell the grails app that it should use the JSON views by default and just in case of the index it should use the gsp view?

Update: I would like to render views directly from URLMapping without creating a controller.

Upvotes: 0

Views: 140

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27200

Is it possible to tell the grails app that it should use the JSON views by default and just in case of the index it should use the gsp view?

Yes. You can serve many different view types from the same app, including GSON Views working along side GSP Views.

See the project at https://github.com/jeffbrown/webjsonviews.

If you run that app and send a request to http://localhost:8080/person/index with your browser, you will see HTML rendered which was server side rendered using GSP.

If you send a request to http://localhost:8080/person/index.json with your browser, you will see the JSON rendered using GSON Views.

This will render HTML:

curl http://localhost:8080/person/index

This will render JSON:

curl http://localhost:8080/person/index.json

This will render JSON:

curl -H "Accept: application/json" http://localhost:8080/person/index

If you would like the default content type to be application/json, you can add the following to the PersonController:

static responseFormats = ['json', 'html']

That will cause the following to return JSON instead of HTML:

curl http://localhost:8080/person/index

I hope that helps.

Upvotes: 1

Related Questions