【问题标题】:How to put <security:authentication property="principal.username"/> inside a value=" " in an input?如何在输入中将 <security:authentication property="principal.username"/> 放入 value=" " 中?
【发布时间】:2020-05-05 18:16:59
【问题描述】:

有没有人知道我怎么写这条线

<security:authentication property="principal.username"/>

value=""里面

<form:input path="contactName" cssClass="form-control"
                        placeholder="Enter your Contact Name please." value=""/>

如果我像下面显示的代码那样保留它,则用户名显示在输入字段下方而不是(obv)内。

 <form:input path="contactName" cssClass="form-control"
                        placeholder="Enter your Contact Name please." value=""/>
            <security:authentication property="principal.username"/>

非常感谢您的帮助!

关于尼可

【问题讨论】:

    标签: java maven spring-mvc jsp spring-security


    【解决方案1】:

    你使用百里香吗?

    如果是,你可以这样做。

    添加pom.xml依赖:

        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
    

    然后:

    <!-->it is necessary<-->
    <html xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
    
    <input placeholder="XXX" th:value="${#authentication.getName()}" />
    

    它可以获取用户名,但即使你没有登录它也会返回anonymousUser。 别着急,这是个小问题,可以用thymeleaf的判断表达式。

    您可以在以下位置找到更详细的文档: https://www.thymeleaf.org/doc/articles/springsecurity.html

    如果这不能解决你的问题,我会跟进。

    【讨论】:

    • 对不起,我忘了提,我只是使用“标准”mvc 安全依赖项,我不知道 thymleaf :/
    【解决方案2】:

    如果您使用的是标准 Spring-MVC,那么您可以从控制器本身发送用户名。

    在控制器文件中,使用 Principal 作为参数。使用 Principal 类的 getName() 设置模型中的用户名,并将其作为返回语句传递。

        public ModelAndView display(Principal principal){
            ModelAndView mav = new ModelAndView();
            mav.addObject("uname", principal.getName());
            return mav;
        }
    

    在 JSP 文件中,使用value="${uname}":

        <form:input path="contactName" cssClass="form-control"
                            placeholder="Enter your Contact Name please." value="${uname}"/>
    

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2017-02-04
      相关资源
      最近更新 更多