0

I'm new in Spring-MVC and I am trying to display a class property that is being assigned to the model.

I am doing the following with a simple string:

model.addAttribute("user", "username" );

And it is being display as expected using:

<P>  The user is  ${username}. </P>

But now I have the following class:

public class User { 
          private String name;  
          public User(){
            this.setName("Unknown");
          } 
          public String getName() {
            return name;
          }
          public void setName(String name) {
            this.name = name;
          }
        }

And I am trying to display the "Name" property in jsp output without success:

     User myuser = new User();
     myuser.setName("CARLOS");
     model.addAttribute("user",myuser);

In jsp view I am using:

     <p>User name is ${user.Name}</p>

Also tried with:

     <c:out value="${$user.Name}"></c:out>

How can I achieve it?.

Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82

3 Answers3

4

Java is case-sensitive. name is not the same as Name.

Try <p>User name is ${user.name}</p>.

<c:out value="${user.name}"></c:out> will also work (without $ inside parentheses).
Note that using <c:out> escapes all HTML characters see this answer.

Community
  • 1
  • 1
Michał Rybak
  • 8,648
  • 3
  • 42
  • 54
0

You have defined the attribute as name. Name wont be found in that case.

public class User { 
      private String name;  
      public User(){
        this.setName("Unknown");
      } 
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
    }


<p>User name is ${user.name}</p>
Adarsh
  • 3,613
  • 2
  • 21
  • 37
0

where you are trying this section:

 model.addAttribute("user", "username" );

and where you are trying this one:

 User myuser = new User();
 myuser.setName("CARLOS");
 model.addAttribute("user",myuser);

confusing.. Its ok

//In your controller welcome is a request parameter you have to pass

@RequestMapping(value="/welcome", method = RequestMethod.GET)
public String welcome(ModelMap model) {
 User myuser = new User();
 myuser.setName("CARLOS");
 model.addAttribute("user",myuser);
 return "/*your jsp file*/";
}

In your jsp file

<p>User name is ${user}</p>.