@ModelAttribute

 

  •  In Spring, if we want to send data as an object, we can use @ModelAttribute.
  •  First, we must create the class to hold the data we want to display or process.

 Model Class Programmer :

public class Programmer {

private int pId;

private String pName;

private String pLang;

public Programmer() {

super();

}


public Programmer(int pId, String pName, String pLang) {

super();

this.pId = pId;

this.pName = pName;

this.pLang = pLang;

}


public int getpId() {

return pId;

}


public void setpId(int pId) {

this.pId = pId;

}


public String getpName() {

return pName;

}


public void setpName(String pName) {

this.pName = pName;

}


public String getpLang() {

return pLang;

}


public void setpLang(String pLang) {

this.pLang = pLang;

}


@Override

public String toString() {

return "Programmer [pId=" + pId + ", pName=" + pName + ", pLang="

+ pLang + "]";

}

}


Create a Controller to Handle the Data

In your Spring controller, define a method to handle the data that will use @ModelAttribute to
receive the form data as an object.


You can return data from a controller method using either @ModelAttribute with ModelAndView
or simply as a String.

Preference

ModelAndView: Use this if you want a clear separation of model and view, as it explicitly
shows the data and the view together.
String: This is simpler and more common when you just want to return the view name. It
keeps your code concise.

Now on the Thymeleaf page, you can access the properties of an object simply by using the
syntax reference_variable.model class variableName

Explanation

  • reference_variable: This is the name used to add the object to the model in the controller.
  • variableName: This is the specific property of the object you want to display.


NOTES: When bringing data from an HTML page to the model class in Java (such as in a Spring
Boot application), the variable names in the HTML form and the variables in the model class
must be the same. This ensures that the data binds correctly between the form fields and the
model object.

For example:

  • In the HTML form, you might have an input field: <input type="text" name="username"/>
  • In your model class, you should have a variable: private String username;
By keeping the names identical, frameworks like Spring can automatically bind the form data to
the corresponding fields in your model class.

If you want to display a message across all pages of a web application, like a discount
banner, you can use @ModelAttribute in your Spring controller. This way, the message is added
to the model and is accessible in every view.

Create a Global Message Method

You can define a method in your controller that adds a global message to the model. This method
will be called automatically before every request.

Now that the global message is added to the model, you can access it in any Thymeleaf template
using ${globalMessage}.



Comments