如何创建在所有控制器中工作的动态链接

jtw3ybtb  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(230)

我有profilecontroller,它必须通过springsecurityusername获取Map。

@Controller
public class ProfileController {

    @GetMapping("/profile/{profileName}")
    public String showProfilePage(@PathVariable("profileName")String profileName){
        return "profile";
    }
}

我有这样的动态链接在网站的标题,所以用户可以随时点击它

<a th:href="@{/profile/{name}(name=${username})}">profile</a>

所以如果我想使用link,我必须在每个classcontroller中找到每个time用户

@Controller
public class SearchController {

    @Autowired
    UserService userService;

    @GetMapping("/")
    public String showIndexPage(Model model){
        User user = userService.findUserByUsername(someNameFromSecurityHandler);
        model.addAttribute("username",user.getUsername());
        return "index";
    }

每次我都要找到这个链接的用户。如果我想优化这个东西我该怎么办。因为我认为每次在数据库中查找用户都是个坏主意,因为人们通常不会使用配置文件页面,这只是额外的时间开销。我在每个controll类中都创建了这个代码。

q1qsirdb

q1qsirdb1#

我假设您正在使用springsecurity来保护mvc应用程序(您提到了springsecurityusername,但并不清楚)。
如果上述为真,那么您的身份验证主体将已经包含在会话中(假设您已经登录)。您只需按以下方式访问它:

@GetMapping("/")
public String showIndexPage(Model model, Authentication auth){
    String username = auth.getName();
    ...
}

另外,您可以直接从thymeleaf访问spring的安全细节,而不是从控制器设置它(未测试,但也是可能的)https://github.com/thymeleaf/thymeleaf-extras-springsecurity). 您将需要以下依赖项:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

然后,在thymeleaf中可以执行以下操作:

<a th:href="@{|/profile/${#authentication.name}|}">profile</a>

相关问题