LaVOZs

The World’s Largest Online Community for Developers

'; java - How to put <security:authentication property="principal.username"/> inside a value=" " in an input? - LavOzs.Com

does anyone have an idea how I can put this line

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

inside the value=""

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

If i keep it like in the code shown beneath, the username is shown underneath the input field and not within (obv).

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

Much appreciate for any help!

With regards Niko

Do you using Thymeleaf?

If yes, you can do like this.

Add pom.xml Dependency:

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

Then:

<!-->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()}" />

It can get the username, but it will return anonymousUser even if you are not logged in. Don't worry, this is a little problem, you can use thymeleaf's judgment expression.

You can find more detailed documentation at: https://www.thymeleaf.org/doc/articles/springsecurity.html

If this doesn't solve your problem, I will follow up.

If you are using Standard Spring-MVC, then you can send the username from the controller itself.

In the controller file, use Principal as the parameter. Use getName() of Principal class to set the username in model and pass it as return statement.

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

In the JSP file, use value="${uname}":

    <form:input path="contactName" cssClass="form-control"
                        placeholder="Enter your Contact Name please." value="${uname}"/>
Related
Is Java “pass-by-reference” or “pass-by-value”?
How do I efficiently iterate over each entry in a Java Map?
How do I read / convert an InputStream into a String in Java?
How do I generate random integers within a specific range in Java?
How to get an enum value from a string value in Java?
How do I determine whether an array contains a particular value in Java?
How to avoid Java code in JSP files?
How do I convert a String to an int in Java?
How to create a memory leak in Java?
How do I POST JSON data with cURL?