json - 混合GSP和JSON View 时如何设置首选 View 分辨率

标签 json angularjs rest grails grails3

我正在使用angularjs配置文件维护grails 3.3.8应用程序。

REST API和angularjs Assets 由同一grails应用程序提供。目前,我不想将应用程序分为两个应用程序。

该应用程序使用JSON View 来呈现资源的JSON响应。
该应用程序还使用GSP View 插件提供初始index.gsp以服务angularjs应用程序。

由于使用了GSP View 插件,因此在出现500404401,...错误的情况下,该应用始终会呈现默认的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/

相关文章:

json - Angular 2 : How to preserve class methods on deserialization?

java - FileNotFound 错误(JSON 文件)

javascript - 从 Protractor 的右键菜单中选择翻译选项

rest - Polymer:如何在配置文件中存储 REST API 基本 URL

node.js - 如何将我的 REST API 与我的 Express 网络应用分开?

json - Jackson JSON 到 Java 映射,用于具有不同数据类型的相同属性

AngularJS - 自定义指令范围 "&"做什么?

javascript - Angular 滑动切换动画在 ng-repeat 中不起作用?

java - JAX-RS 2.0/RESTeasy 中的版本 API

json - 使用未声明的类型 'JSON' 和使用未解析的标识符 'JSONEncoding'