我正在使用Spring Security核心插件实现身份验证。现在,我有一个带有生成的CRUD View 的类,我想对其进行调整。
域类的一部分是用户。如果用户只有“用户权限”,则他将无法选择用户(默认用户是当前用户)。
如果用户是管理员(权限:ROLE_ADMIN),则他应该能够选择所有可用用户。
在我的 Controller 中,我尝试使用springSecurityService.getCurrentUser()在我的gsp中设置默认用户。不幸的是,这会导致错误:
Controller :
def currentUser(){
User user = springSecurityService.getCurrentUser()
return user
}
form.gsp:
<div class="fieldcontain ${hasErrors(bean: daybookingInstance, field: 'user', 'error')} required">
<label for="user">
<g:message code="daybooking.user.label" default="User" />
<span class="required-indicator">*</span>
</label>
<g:select id="user" name="user.id" from="${usermanagement.User.list()}" optionKey="id" required="" value="${package.controller.currentUser().id}" class="many-to-one"/>
最后,我不知道如何使选择变量的内容(管理员:所有用户,普通用户:无选择)以及如何设置默认用户(当前已登录)
编辑:错误消息:
Caused by MissingMethodException: No signature of method: usermanagement.User.currentUser() is applicable for argument types: () values: []
Possible solutions: currentUser()
编辑:
这是我在 Controller 中的方法:
User userInstance = springSecurityService.getCurrentUser()
integer id = userInstance.id
log.error(id)
render(view: '_form.gsp', model : [id: id])
}
我尝试通过传递整个userInstance来尝试它,但是随后我总是收到一个nullpointer异常,说我无法从null获取ID(在 View 中:userInstance.id)
这是我的观点(由grails创建的_form.gsp):
<div class="fieldcontain ${hasErrors(bean: dailyBookingInstance, field: 'user', 'error')} required">
<label for="user">
<g:message code="dailyBooking.user.label" default="User" />
<span class="required-indicator">*</span>
</label>
<g:select id="user" name="user.id" from="${usermanagement.User.list()}" optionKey="id" required="" value="${id}" class="many-to-one"/>
</div>
该方法工作正常,因为id / userInstance被正确记录。不知何故,我觉得我不应该将数据传递给生成的东西。
最佳答案
编辑:要将用户从 Controller 传递到 View ,请执行以下操作。
def controllerAction()
{
//get the user instance
User userInstance = springSecurityService.currentUser;
//pass the user to your view
render(view: 'theviewname', model : [userInstance: userInstance])
}
然后,您可以使用$ {userInstance}访问 View 中的userInstance
旧
您可以使用Spring Security taglib。
例如:
<sec:ifAllGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">secure stuff here</sec:ifAllGranted>
您可以看到here可用的各种选项。
关于grails - Grails,gsp中的调用 Controller 方法,在表单中设置默认用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30057120/