<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Spring &#8211; Selenium Express</title>
	<atom:link href="https://www.seleniumexpress.com/category/spring/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.seleniumexpress.com</link>
	<description>Express your coding skills</description>
	<lastBuildDate>Thu, 17 Sep 2020 08:54:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.seleniumexpress.com/wp-content/uploads/2020/09/Untitled-design-1.png</url>
	<title>Spring &#8211; Selenium Express</title>
	<link>https://www.seleniumexpress.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>@ModelAttribute at the Method Level &#8211; The impact of @ModelAttribute when paced over a method.</title>
		<link>https://www.seleniumexpress.com/modelattribute-at-the-method-level/</link>
					<comments>https://www.seleniumexpress.com/modelattribute-at-the-method-level/#respond</comments>
		
		<dc:creator><![CDATA[Abhilash]]></dc:creator>
		<pubDate>Wed, 16 Sep 2020 06:57:50 +0000</pubDate>
				<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[@ModelAttribute]]></category>
		<category><![CDATA[@modelattribute at method level]]></category>
		<category><![CDATA[model attribute in spring]]></category>
		<category><![CDATA[model.addattribute in spring mvc]]></category>
		<category><![CDATA[spring boot interview questions]]></category>
		<category><![CDATA[spring interview questions]]></category>
		<category><![CDATA[spring interview questions for experienced]]></category>
		<category><![CDATA[spring mvc @modelattribute]]></category>
		<guid isPermaLink="false">https://www.seleniumexpress.com/?p=26034</guid>

					<description><![CDATA[Why should we annotate a method with @ModelAttribute? Learn Spring's @ModelAttribute annotation in depth.]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">1. Overview</h2>



<p><br>A method with a <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html" class="rank-math-link" target="_blank" rel="noopener"><strong>@ModelAttribute</strong> </a>on top of it <strong>executes</strong> <strong>first</strong>, <strong>followed</strong> by a handler method.</p>



<p>Using @ModelAttribute at the method level, We can set data in the <strong>Model</strong> before a handler method executes. In simple words, It helps us to <strong>prepopulate</strong> the Model object before a Request Mapping method invokes.</p>



<p>We can set all the<strong> common attributes </strong>inside a method by marking it with a @ModelAttribute So that those data will be available during <strong>each request</strong>.</p>



<p>By using @ModelAttribute at the method level, We can also set <strong>global data </strong>for our web-app.</p>



<p>A controller can have <strong>any number</strong> of methods marked with a @ModelAttribute annotation.</p>



<p><strong>In this article, I will cover the following questions on @ModelAttribute.</strong></p>



<ol class="wp-block-list"><li><em>How to use @ModelAttribute?</em></li><li><em>Why should we use @ModelAttribute?</em></li><li><em>When to use @ModelAttribute?</em> (The Top 2 reasons)</li><li><em>How to make @ModelAttribute data global?</em></li></ol>



<h2 class="wp-block-heading">2. Setting Up</h2>



<p><strong>Let&#8217;s create a sample MVC app that will show our Website Name and Website Category on a webpage.</strong></p>



<p>To demonstrate, I am going to use a DTO called &#8220;WebsiteInfoDTO&#8221; to hold our website information.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class WebsiteInfoDTO {

	private String websiteName;
	private String websiteCategory;
	
	public WebsiteInfoDTO() {
		System.out.println(&quot;WebsiteInfoDTO constructor called!&quot;);
	}

	//getters and setters 
	public String getWebsiteName() {
		return websiteName;
	}

	public void setWebsiteName(String websiteName) {
		this.websiteName = websiteName;
	}

	public String getWebsiteCategory() {
		return websiteCategory;
	}

	public void setWebsiteCategory(String websiteCategory) {
		this.websiteCategory = websiteCategory;
	}

}
</pre></div>


<p>As per requirement, we need to show the website name and category on a JSP page called &#8220;index.jsp&#8221;.</p>



<p>Let&#8217;s First Create a controller through which we can send the desired data to the JSP page.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
public class MyWebsiteController {

	@RequestMapping(&quot;/showInfo&quot;)
	public String showWebsiteInfo(Model model) {

		System.out.println(&quot;showWebsiteInfo method called..&quot;);

		// Setting the web site Information
		WebsiteInfoDTO websiteInfoDTO = new WebsiteInfoDTO();
		websiteInfoDTO.setWebsiteName(&quot;Selenium Express&quot;);
		websiteInfoDTO.setWebsiteCategory(&quot;Education&quot;);

		// adding the websiteInfoDTO to model
		model.addAttribute(&quot;websiteInfo&quot;, websiteInfoDTO);

		return &quot;index&quot;;
	}
}

</pre></div>


<p>Now Let&#8217;s Develop the &#8220;Index.jsp&#8221; where we will fetch the Website name and website category from the model attribute.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
	pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;html&gt;
&lt;body&gt;

	Web site Name : ${websiteInfo.websiteName}
	&lt;br /&gt;
	Web site Category : ${websiteInfo.websiteCategory}

&lt;/body&gt;
&lt;/html&gt;
</pre></div>


<p>Now, When we hit &#8220;<em><strong>http://localhost:8080/model-attribute-demo/showInfo</strong></em>&#8220;, we can see the website name and category data on the &#8220;index.jsp&#8221; page.</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="972" height="408" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.20.45-PM.png" alt="" class="wp-image-26040" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.20.45-PM.png 972w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.20.45-PM-300x126.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.20.45-PM-768x322.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.20.45-PM-400x168.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.20.45-PM-600x252.png 600w" sizes="(max-width: 972px) 100vw, 972px" /></figure>



<p>If we look at our console right now, We can see the below <strong>logs</strong> as the &#8220;WebsiteInfoDTO constructor&#8221; and the &#8220;showWebsiteInfo()&#8221;  got invoked.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="536" height="304" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.21.36-PM.png" alt="" class="wp-image-26041" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.21.36-PM.png 536w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.21.36-PM-300x170.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-2.21.36-PM-400x227.png 400w" sizes="(max-width: 536px) 100vw, 536px" /></figure>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<div class="ast-oembed-container " style="height: 100%;"><iframe title="2 Key reasons to use @ModelAttribute at the Method level | Spring MVC Interview Questions &amp; Answers" width="1200" height="675" src="https://www.youtube.com/embed/_Nafv53TKYY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div></figure>



<h2 class="wp-block-heading">3. Bringing in @ModelAttribute</h2>



<p>Let&#8217;s try and answer the following questions.<br><em>How to use @ModelAttribute?</em><br><em>Why should we use @ModelAttribute?</em></p>



<p>The Below handler method handles the &#8220;<em>/showInfo</em>&#8221; request.<br>We may have multiple @RequestMapping methods, where you will be needing the WebsiteInfoDTO&#8217;s data. <br>For example, we may need the WebsiteInfoDTO data inside &#8220;<em>/abc</em>&#8220;, &#8220;<em>/xyz</em>&#8221; request mapping methods too.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [7,8,9]; title: ; notranslate">
@RequestMapping(&quot;/showInfo&quot;)
	public String showWebsiteInfo(Model model) {

		System.out.println(&quot;showWebsiteInfo method called..&quot;);

		// Setting the web site Information
		WebsiteInfoDTO websiteInfoDTO = new WebsiteInfoDTO();
		websiteInfoDTO.setWebsiteName(&quot;Selenium Express&quot;);
		websiteInfoDTO.setWebsiteCategory(&quot;Education&quot;);

		// adding the websiteInfoDTO to model
		model.addAttribute(&quot;websiteInfo&quot;, websiteInfoDTO);

		return &quot;index&quot;;
	}
</pre></div>


<p>So, If we need some <em>default model data on each request</em>, It is batter to move these highlighted codes to a new method and annotate that with @ModelAttribute.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [0,1]; title: ; notranslate">
@ModelAttribute(&quot;websiteInfo&quot;)
	public WebsiteInfoDTO getWebsiteInfoDTO() {

		System.out.println(&quot;@ModelAttribute : inside getWebsiteDTO method&quot;);

		// setting website information
		WebsiteInfoDTO websiteInfoDTO = new WebsiteInfoDTO();
		websiteInfoDTO.setWebsiteName(&quot;Seleniumexpress.com&quot;);
		websiteInfoDTO.setWebsiteCategory(&quot;Education&quot;);
		System.out.println(&quot;************&quot;);

		return websiteInfoDTO;
	}
</pre></div>


<ul class="wp-block-list"><li><strong>When we annotate a method with @ModelAttribute, It invokes first before any handler/@RequestMapping methods.</strong></li><li><strong><strong>Any data we set inside a method annotated with @ModelAttribute, Available to every request of a controller.</strong></strong></li></ul>



<p><em>Let&#8217;s Prove it by updating our Controller code.</em></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [4,18]; title: ; notranslate">
@Controller
public class MyWebsiteController {

	@ModelAttribute(&quot;websiteInfo&quot;)
	public WebsiteInfoDTO getWebsiteInfoDTO() {

		System.out.println(&quot;@ModelAttribute : inside getWebsiteDTO method&quot;);

		// setting website information
		WebsiteInfoDTO websiteInfoDTO = new WebsiteInfoDTO();
		websiteInfoDTO.setWebsiteName(&quot;Seleniumexpress.com&quot;);
		websiteInfoDTO.setWebsiteCategory(&quot;Education&quot;);
		System.out.println(&quot;************&quot;);

		return websiteInfoDTO;
	}

	@RequestMapping(&quot;/showInfo&quot;)
	public String showWebsiteInfo(Model model) {
		
        System.out.println(&quot;@RequestMapping: showWebsiteInfo method called..&quot;);

		// fetching the model attribute&quot;websiteInfo&quot; from the model

		WebsiteInfoDTO websiteInfoDTO = (WebsiteInfoDTO) model.getAttribute(&quot;websiteInfo&quot;);
		System.out.println(websiteInfoDTO.getWebsiteName());
		System.out.println(websiteInfoDTO.getWebsiteCategory());

		return &quot;index&quot;;
	}
}

</pre></div>


<p>If we hit the &#8220;<em>http://localhost:8080/model-attribute-demo/showInfo</em>&#8220;, <strong>First </strong>the method with<strong> @ModelAttribute</strong> will be called, <strong>followed by</strong> the <strong>@Requestmapping</strong>.</p>



<p>Once the @ModelAttribute method got executed, the WebsiteInfoDTO data will be available to &#8220;/showInfo&#8221; handler method.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="325" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM-1024x325.png" alt="@ModelAttribute : In Action" class="wp-image-26050" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM-1024x325.png 1024w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM-300x95.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM-768x244.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM-400x127.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM-600x191.png 600w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.39.24-PM.png 1278w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><em style=""><b>If we </b></em><strong><em>analyse the above log</em></strong>,</p>



<p>When there is an incoming request(&#8220;<em>/showInfo</em>&#8220;), The method with @ModelAttribute places the available model data inside the Model object of the @RequestMapping.&nbsp;</p>



<p>In short, Our Common data is now available to each request coming to the MyWebsiteController.</p>



<p>That&#8217;s why you can see the WebsiteInfoDTO related information in the log when the &#8220;<em>/showInfo&#8221; invokes.</em></p>



<p><em>When the handler method &#8220;showWebsiteInfo()&#8221; invocation is complete, the model is attached to it, going to the view. Hense you can see your data on the webpage as well.</em></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="928" height="328" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.31.53-PM.png" alt="" class="wp-image-26049" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.31.53-PM.png 928w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.31.53-PM-300x106.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.31.53-PM-768x271.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.31.53-PM-400x141.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-3.31.53-PM-600x212.png 600w" sizes="(max-width: 928px) 100vw, 928px" /></figure>



<h2 class="wp-block-heading">4. Let&#8217;s Introduce a new handler method</h2>



<p>For more clarity, Let me create another @RequestMapping method inside our MyWebsiteController.<br>But this time, let&#8217;s use <strong>@ModelAttribute</strong> inside the handler <strong>method parameter</strong> instead of a normal Model.<br></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [2]; title: ; notranslate">
@RequestMapping(&quot;/showCompanyInfo&quot;)
	public String showCompanyInfo(@ModelAttribute(&quot;websiteInfo&quot;) WebsiteInfoDTO websiteInfoDTO) {
		
		System.out.println(&quot;@RequestMapping: showCompanyInfo method called..&quot;);

		// fetching the model attribute&quot;websiteInfo&quot; from the model
	
		System.out.println(websiteInfoDTO.getWebsiteName());
		System.out.println(websiteInfoDTO.getWebsiteCategory());

		return &quot;index&quot;;
	}
</pre></div>


<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>When we use a <strong>@ModelAttribute(&#8220;websiteInfo&#8221;)</strong> inside the <strong>@RequestMapping </strong>method parameter, first, it looks for the websiteInfoDTO object inside the model object. If the object is not available, the @ModelAttribute inside the method argument creates a new object for the given instance.</p></blockquote>



<p>In Our Case, We already have a method annotated with @ModelAttribute over it i.e getWebsiteInfoDTO().<br>So when a new request comes, the getWebsiteInfoDTO() method will execute first and, the &#8220;WebsiteInfoDTO&#8221; instance will available to the request(&#8220;/showCompanyInfo&#8221;).</p>



<p>Hence, when spring handles the  &#8220;/showCompanyInfo&#8221; request,  The &#8220;WebsiteInfoDTO&#8221; object will be retrieved from the model and pushed to the handler method parameter&#8217;s  @ModelAtrribute.</p>



<p><strong>So when we write this line, </strong></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
showCompanyInfo(@ModelAttribute(&quot;websiteInfo&quot;) WebsiteInfoDTO websiteInfoDTO) {
</pre></div>


<p>No new WebsiteInfoDTO object will be created and,<strong> the parameter level @ModelAttribute will use the instance created by the getWebsiteInfoDTO().</strong></p>



<p><em>now let&#8217;s update our controller with our new handler method called <strong>showCompanyInfo().</strong></em></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [33]; title: ; notranslate">
@Controller
public class MyWebsiteController {

	@ModelAttribute(&quot;websiteInfo&quot;)
	public WebsiteInfoDTO getWebsiteInfoDTO() {

		System.out.println(&quot;************&quot;);
		System.out.println(&quot;@ModelAttribute : inside getWebsiteDTO method&quot;);

		// setting website information
		WebsiteInfoDTO websiteInfoDTO = new WebsiteInfoDTO();
		websiteInfoDTO.setWebsiteName(&quot;Seleniumexpress.com&quot;);
		websiteInfoDTO.setWebsiteCategory(&quot;Education&quot;);
		System.out.println(&quot;************&quot;);

		return websiteInfoDTO;
	}

	@RequestMapping(&quot;/showInfo&quot;)
	public String showWebsiteInfo(Model model) {
		System.out.println(&quot;@RequestMapping: showWebsiteInfo method called..&quot;);

		// fetching the model attribute&quot;websiteInfo&quot;) from the model

		WebsiteInfoDTO websiteInfoDTO = (WebsiteInfoDTO) model.getAttribute(&quot;websiteInfo&quot;);
		System.out.println(websiteInfoDTO.getWebsiteName());
		System.out.println(websiteInfoDTO.getWebsiteCategory());
		

		return &quot;index&quot;;
	}
	
	@RequestMapping(&quot;/showCompanyInfo&quot;)
	public String showCompanyInfo(@ModelAttribute(&quot;websiteInfo&quot;) WebsiteInfoDTO websiteInfoDTO) {
		
		System.out.println(&quot;@RequestMapping: showCompanyInfo method called..&quot;);

		// fetching the model attribute&quot;websiteInfo&quot;) from the model
	
		System.out.println(websiteInfoDTO.getWebsiteName());
		System.out.println(websiteInfoDTO.getWebsiteCategory());

		return &quot;index&quot;;
	}
}

</pre></div>


<p>If we hit the &#8220;<em>http://localhost:8080/model-attribute-demo/showInfo</em>&#8220;<br>followed by<br><em>http://localhost:8080/model-attribute-demo/showCompanyInfo</em><br>You can see our method with @ModelAttribute i.e getWebsiteInfoDTO(), invoked before each request.<br><br><strong>Log:</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="551" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM-1024x551.png" alt="@ModelAttribute : In Action" class="wp-image-26054" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM-1024x551.png 1024w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM-300x161.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM-768x413.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM-400x215.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM-600x323.png 600w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-4.55.02-PM.png 1104w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>Index.jsp</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="352" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM-1024x352.png" alt="" class="wp-image-26055" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM-1024x352.png 1024w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM-300x103.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM-768x264.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM-400x138.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM-600x206.png 600w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-5.07.06-PM.png 1064w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">5. Access your @ModelAttribute data globally<br></h2>



<p>If we want to access the <strong>@ModelAttribute</strong> method data <strong>globally</strong>, annotate your controller class with<strong> a @ControllerAdvice annotation. </strong>Make sure the controller class that you are marking with <strong>@ControllerAdvice</strong> should be the same class, which contains a method marked with @ModelAttribute. </p>



<p>Now, In our example, Let&#8217;s annotate <strong>MyWebsiteController</strong> with <strong>a @ControllerAdvice </strong>so that we can access the model data inside any other controller&#8217;s request method.</p>



<p><em>Updated the MyWebsiteController with @ControllerAdvice annotation</em></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [2]; title: ; notranslate">
@Controller
@ControllerAdvice
public class MyWebsiteController {
</pre></div>


<p><strong><em>Let&#8217;s create a new controller called TestController.</em></strong></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; first-line: 1; highlight: [4]; title: ; notranslate">
@Controller
public class TestController {

	@RequestMapping(&quot;/test&quot;)
	public String test(@ModelAttribute(&quot;websiteInfo&quot;) WebsiteInfoDTO websiteInfoDTO) {
		
		System.out.println(&quot;@RequestMapping: Inside test method&quot;);
		System.out.println(&quot;Website name is : &quot; + websiteInfoDTO.getWebsiteName());
		System.out.println(&quot;Website Cetagory is : &quot; + websiteInfoDTO.getWebsiteCategory());
		
		return &quot;index&quot;;
	}

}
</pre></div>


<p>Now, Let&#8217;s execute the test() by hitting <br><em>http://localhost:8080/model-attribute-demo/test</em></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="400" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM-1024x400.png" alt="" class="wp-image-26071" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM-1024x400.png 1024w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM-300x117.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM-768x300.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM-400x156.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM-600x234.png 600w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.20.40-PM.png 1070w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>Amazing !!</strong><br>So, even though the <strong>@RequestMapping(&#8220;/test&#8221;) present inside a different controller</strong>, still, we can access the model data which we set inside <strong>MyWebsiteController</strong>. </p>



<p><em>The below screenshot proves that our model data are now <strong>global</strong> and, We can access it inside any controller.</em></p>



<p><strong>Let&#8217;s analyse the Log : </strong></p>



<figure class="wp-block-image size-large is-style-default"><img loading="lazy" decoding="async" width="1024" height="378" src="http://seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM-1024x378.png" alt="" class="wp-image-26072" srcset="https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM-1024x378.png 1024w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM-300x111.png 300w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM-768x283.png 768w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM-400x148.png 400w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM-600x221.png 600w, https://www.seleniumexpress.com/wp-content/uploads/2020/09/Screen-Shot-2020-09-08-at-10.28.33-PM.png 1160w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Therefore,  Marking a controller class with a @ControllerAdvice converts the Model Attributes to Global Attributes.</p></blockquote>



<p>I<strong>f you want to restrict the scope </strong>for @<strong>ControllerAdvice</strong>, use the  <strong>assignableTypes</strong> or <strong>basePackages</strong> inside <strong>@ControllerAdvice parameters.</strong></p>



<p><em>By following the below code, we can restrict the ModelAttribute data between limited classes.</em></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [2]; title: ; notranslate">
@Controller
@ControllerAdvice(assignableTypes = {TestController.class,TestController2.class})
public class MyWebsiteController {
</pre></div>


<p><em>By following the below code, we can restrict the ModelAttribute data between limited packages.</em></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [2]; title: ; notranslate">
@Controller
@ControllerAdvice(basePackages = {&quot;com.seleniumexpress.service&quot;,&quot;com.seleniumexpress.controllers&quot;})
public class MyWebsiteController {
</pre></div>


<h2 class="wp-block-heading">6. When to use @ModelAttribute?</h2>



<ol class="wp-block-list"><li>We can use the @ModelAttribute on method level to share default data, which we need during any handler method&#8217;s invocation. For Example, We can prepopulate a model object with specific attributes by loading it from the database. Note that the same model object can be further accessed by a handler method annotated with @ModelAttribute (inside parameter). Now, As the model object inside the handler method parameter is already carrying the data, We can apply validation to it by placing a @Valid annotation before the @ModelAttribute.</li><li>A method marked with @ModelAttribute is generally used with the @SessionAttribute to instantiate a model attribute in advance. You can watch the below video from 53:14 to get more clarity on this statement.</li></ol>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<div class="ast-oembed-container " style="height: 100%;"><iframe title="2 Key reasons to use @ModelAttribute at the Method level | Spring MVC Interview Questions &amp; Answers" width="1200" height="675" src="https://www.youtube.com/embed/_Nafv53TKYY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div></figure>



<p>If you are new to Spring&#8217;s @SessionAttributes annotation, Please consider watching the below video.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<div class="ast-oembed-container " style="height: 100%;"><iframe title="@SessionAttributes - Unraveling the mystery | HttpSession Vs @SessionAttributes |ConversationalScope" width="1200" height="675" src="https://www.youtube.com/embed/ezty6XhOpF8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div></figure>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>If you enjoyed reading this post and passionate about learning Spring MVC from scratch, Do check out my Spring MVC beginners and <a href="http://seleniumexpress.com/all-courses/" class="rank-math-link">Spring MVC Intermediate</a> courses for FREE.<br></p></blockquote>



<h2 class="wp-block-heading">7. Conclusion</h2>



<p class="has-text-align-left">In this tutorial, we have investigated the uses of @ModelAttribute on the method level. To practice this concept, you can pull the same code from the GitHub. You can alwayes watch the video attached with this blog to get more clarity.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.seleniumexpress.com/modelattribute-at-the-method-level/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
