我正在使用angularjs配置文件维护grails 3.3.8应用程序。
REST API和angularjs Assets 由同一grails应用程序提供。目前,我不想将应用程序分为两个应用程序。
该应用程序使用JSON View 来呈现资源的JSON响应。
该应用程序还使用GSP View 插件提供初始index.gsp
以服务angularjs应用程序。
由于使用了GSP View 插件,因此在出现500
,404
,401
,...错误的情况下,该应用始终会呈现默认的gsp错误 View ,而不是使用JSON View 。
当我删除grails-gsp
插件时,所有请求都将带有JSON响应。同样在发生错误的情况下。但是然后index.gsp
无法呈现。
是否可以告诉grails应用程序默认情况下应使用JSON View ,以防出现索引时应使用gsp View ?
更新:
我想直接从URLMapping渲染 View 而不创建 Controller 。
最佳答案
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?
是。您可以在同一应用程序中提供许多不同的 View 类型,包括GSON View 和其他GSP View 一起使用。
请参阅https://github.com/jeffbrown/webjsonviews上的项目。
如果运行该应用程序,并使用浏览器将请求发送到http://localhost:8080/person/index,您将看到HTML渲染的HTML,它是使用GSP在服务器端渲染的。
如果使用浏览器向http://localhost:8080/person/index.json发送请求,您将看到使用GSON View 呈现的JSON。
这将呈现HTML:
curl http://localhost:8080/person/index
这将呈现JSON:
curl http://localhost:8080/person/index.json
这将呈现JSON:
curl -H "Accept: application/json" http://localhost:8080/person/index
如果您希望默认的内容类型为
application/json
,则可以将以下内容添加到PersonController
:static responseFormats = ['json', 'html']
这将导致以下代码返回JSON而不是HTML:
curl http://localhost:8080/person/index
希望对您有所帮助。
关于json - 混合GSP和JSON View 时如何设置首选 View 分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56239985/