Grails4:自定义域模型封送器不适用于Grails4
我目前的问题是,我从grails2.4.5到grails3.3.0创建的自定义对象封送器不适用于grails4.0.0。Grails4默认响应域模型,而不是我创建的自定义模型 下面是我的代码。请回顾一下,如果你发现有什么不对劲,请务必让我知道,伙计们,如果你能帮助我,我会很高兴的Grails4:自定义域模型封送器不适用于Grails4,grails,groovy,Grails,Groovy,我目前的问题是,我从grails2.4.5到grails3.3.0创建的自定义对象封送器不适用于grails4.0.0。Grails4默认响应域模型,而不是我创建的自定义模型 下面是我的代码。请回顾一下,如果你发现有什么不对劲,请务必让我知道,伙计们,如果你能帮助我,我会很高兴的 响应sender.groovy package com.problem.solve.common import org.springframework.http.HttpStatus trait Response
响应sender.groovy
package com.problem.solve.common
import org.springframework.http.HttpStatus
trait ResponseSender {
void sendResponse() {
render status: HttpStatus.NO_CONTENT
}
void sendResponse(def responseData) {
respond (responseData)
}
void sendResponse(HttpStatus status, def responseData) {
response.status = status.value()
respond (responseData)
}
}
此响应sender.groovy特性在控制器上实现
MarshallerInitializer.groovy 引导初始化时将调用此MarshallerInitializer.groovy
package com.problem.solve.marshaller
class CustomObjectMarshallers {
List marshallers = []
void register() {
marshallers.each {
it.register()
}
}
}
这CustomObjectMarshallers.groovy将注册所有封送器
UserMarshaller.groovy 这是一个示例域模型,我想将它从域模型转换为json响应
resources.groovy 此设置的问题不是在Grails4上工作,而是在Grails2.4.5和Grails3.3.0上工作 我真的需要你们的帮助
非常感谢:)我通过创建DomainModelResponseDto作为响应域模型来解决这个封送员问题 例如:
class UserResponseDto {
String id
String username
String email
UserResponseDto(User user) {
id = user.id
username = user.username
email = user.email
}
}
我有另一个解决这个问题的办法。封送员正在工作,问题是视图。我必须删除创建域类时生成的视图,并且所有视图都与当前封送器和设置完美配合。我通过创建DomainModelResponseDto作为响应域模型来解决封送器问题。示例:
class UserResponseDto{String id String username String email UserResponseDto(用户用户){id=User.id username=User.username=email=User.email}}
您对@injecteer或我如何处理封送器的最佳实践有什么想法吗?引入DTO会破坏类似Grails的框架的整个想法。您的对象有什么特别之处,需要一个特别的封送员?我从来都不需要
package com.problem.solve.marshaller.marshalls
import com.problem.solve.security.User
import grails.converters.JSON
class UserMarshaller {
void register() {
JSON.registerObjectMarshaller(User) { User user ->
return [
id: user.id,
fullName: user.fullName,
username: user.username,
emailAddress: user.emailAddress,
roles: user.authorities.authority,
dateCreated: user.dateCreated,
lastUpdated: user.lastUpdated,
_entityType: 'User'
]
}
}
import com.problem.solve.marshaller.CustomObjectMarshallers
import com.problem.solve.marshaller.MarshallerInitializer
import com.problem.solve.marshaller.marshalls.*
// Place your Spring DSL code here
beans = {
customObjectMarshallers(CustomObjectMarshallers) {
marshallers = [
new UserMarshaller()
]
}
marshallerInitializer(MarshallerInitializer) {
customObjectMarshallers = ref('customObjectMarshallers')
}
}
class UserResponseDto {
String id
String username
String email
UserResponseDto(User user) {
id = user.id
username = user.username
email = user.email
}
}