用户有条件地在JSP中渲染 [英] Conditionally Render In JSP By User
问题描述
我正试图建立一个简单的论坛,以期摆脱Spring Security和MVC框架的束缚.
I'm trying to make a simple forum just to get the hang of the Spring Security and MVC frameworks.
为简单起见,让我们有一个JSP来查看论坛帖子,如下所示:
For simplicity's sake, let's I have a JSP to view a forum post, which looks like the following:
<body>
...
Title: ${forumPost.title} <br>
Author: ${forumPost.author.name} <br>
Message: {forumPost.message} <br>
<security:authorize ifAnyGranted="ROLE_ADMIN">
Edit: <a href="/edit">Edit</a>
</security:authorize>
...
</body>
我的问题是:管理员不仅应该能够编辑此帖子,而且原始作者也应该能够进行编辑.因此,我只希望ROLE_ADMIN和原始作者能够看到编辑"链接.但是,我不确定如何使用 security:authorize 标签按用户进行过滤,或者我是否需要以其他方式进行处理.
My problem is: not only should an Administrator be able to edit this post, but the original author should be able to as well. Therefore, I only want ROLE_ADMIN and the original author to be able to see the Edit link. However I'm not sure how to filter by user with the security:authorize tag, or if I'll need to go about this a different way.
任何建议将不胜感激.谢谢!
Any suggestions would be much appreciated. Thanks!
推荐答案
假设您在此页面后面有一个控制器,我只需在ModelAndView
中添加一个看起来像(<-伪代码):
Assuming that you have a controller that sits behind this page, I would simply add a canEditPost
field to the ModelAndView
that looks something like (semi-pseudocode):
private boolean isAdmin() {
Authentication currentAuthObj = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = Arrays.asList(currentAuthObj.getAuthorites());
for (GrantedAuthority auth : authorities) {
if ("ROLE_ADMIN".equals(auth.getAuthority())) {
return true;
}
}
return false;
}
boolean currentUserIsAuthor = ...;
modelAndView.addObject("canEditPost",
Boolean.valueOf(currentUserIsAuthor || isAdmin());
然后在您的视图中仅引用$ canEditPost.
And then in your view just reference $canEditPost.
通常,视图只引用模型中的一个简单标志比使视图/模板执行实际逻辑要好.
It's generally better for the view to just reference a simple flag in the model than have the view/template doing the actual logic.
这篇关于用户有条件地在JSP中渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!