【问题标题】:Social media like profile page URL's in Spring Boot社交媒体,例如 Spring Boot 中的个人资料页面 URL
【发布时间】:2018-10-22 06:07:57
【问题描述】:

在我的 Spring Boot Web 应用程序中有用户。我想做的是为每个个人资料创建私人 URL,就像在大多数社交媒体网站中一样。

例如;

www.example.com/jennifer

www.example.com/david

在 php 中使用带有 .htaccess 文件的重定向链接是解决方案。

RewriteCond %{QUERY_STRING} ^username=([^&\s]+)$
RewriteRule ^(?:userinfo\.php|)$ /%1? [R=301,L]

RewriteCond %{QUERY_STRING} ^username=([^&\s]+)&username=([^&\s]+)$
RewriteRule ^(?:userinfo\.php|)$ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\s\/]+)/?$ userinfo.php?username=$1&r [L,QSA]

我如何在 Spring Boot mvc Web 应用程序中实现这一点

【问题讨论】:

    标签: spring spring-mvc spring-boot spring-security


    【解决方案1】:

    有很多方法可以做到这一点,但在我的脑海中,你可以使用@ControllerModelAndView 和模板来完成这项工作

    @Controller
    public class ViewController {
    
        @GetMapping("/{username}")
        public ModelAndView userPage(@PathVariable String username) {
            User userFromDatabase = someMethodThatGetsYourUserFromTheDatabase(username);
            ModelAndView modelAndView = new ModelAndView("userInfo");
            modelAndView.addObject("user", userFromDatabase);
            return modelAndView;
        }
    
    }
    

    以上暗示您有一个名为userInfo 的视图(例如,像 Thymeleaf 甚至 JSP 这样的模板)。

    通过使用上述方法,转到/bob/potato 将显示视图userInfo,但您可能希望在返回视图之前检查用户是否存在,在这种情况下,您可以将它们返回到页面上面写着“您要查找的用户不存在”

    您可能想阅读http://www.baeldung.com/spring-mvc-model-model-map-model-viewhttps://www.mkyong.com/spring-mvc/spring-mvc-and-list-example/ 了解一些基本示例。

    【讨论】:

    • 感谢您的快速回答,所以在我的 spring 配置中,我是否必须删除 anyRequest().authenticated();或者是否有特定的模式来实现 antMatchers("/{username}").permitAll()
    猜你喜欢
    • 2014-10-09
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2016-06-29
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多