【问题标题】:how can i create dynamic link that will work in all controllers我如何创建适用于所有控制器的动态链接
【发布时间】:2021-05-30 14:16:42
【问题描述】:

我有必须通过 SpringSecurityUsername 获取映射的 ProfileController。

@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>

所以如果我想使用链接,我必须在每个 classController 中找到每次用户

@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";
    }

每次我必须为此链接查找用户。如果我想优化这个东西,我必须做什么。因为我认为每次都在数据库中找到用户是个坏主意,因为人们通常不会使用个人资料页面,这只是额外的时间成本。我已经在每个控件类中创建了这段代码。

【问题讨论】:

    标签: java html spring spring-mvc url


    【解决方案1】:

    我假设您正在使用 Spring Security 来保护您的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多