<?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 MVC &#8211; My Shitty Code</title>
	<atom:link href="https://myshittycode.com/tag/spring-mvc/feed/" rel="self" type="application/rss+xml" />
	<link>https://myshittycode.com</link>
	<description>Embracing the Messiness in Search of Epic Solutions</description>
	<lastBuildDate>Fri, 06 Jan 2023 17:10:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://myshittycode.com/wp-content/uploads/2022/04/cropped-icon-32x32.png</url>
	<title>Spring MVC &#8211; My Shitty Code</title>
	<link>https://myshittycode.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">205304208</site>	<item>
		<title>Spring MVC: Failed to convert value of type &#8216;java.lang.String&#8217; to required type &#8216;java.time.LocalDateTime&#8217;</title>
		<link>https://myshittycode.com/2017/06/22/spring-mvc-failed-to-convert-value-of-type-java-lang-string-to-required-type-java-time-localdatetime/</link>
					<comments>https://myshittycode.com/2017/06/22/spring-mvc-failed-to-convert-value-of-type-java-lang-string-to-required-type-java-time-localdatetime/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Thu, 22 Jun 2017 23:07:57 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1050</guid>

					<description><![CDATA[<p>PROBLEM Given the following controller &#8230; When executing &#8230; &#8230; the web service call returns 400 Bad Request with the following error in the console log:- SOLUTION One solution is to change the data type from java.time.LocalDateTime to java.lang.String before parsing it to java.time.LocalDateTime. However, it is a little more verbose than I like. A [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/06/22/spring-mvc-failed-to-convert-value-of-type-java-lang-string-to-required-type-java-time-localdatetime/">Spring MVC: Failed to convert value of type &#8216;java.lang.String&#8217; to required type &#8216;java.time.LocalDateTime&#8217;</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Given the following controller &#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
@RestController
@RequestMapping(value = &#039;/controller&#039;)
class MyController {

    @RequestMapping(method = RequestMethod.GET)
    ResponseEntity main(@RequestParam(name = &#039;dateTime&#039;) LocalDateTime dateTime) {
        // ...

        return ResponseEntity.noContent().build()
    }
}
</pre></div>


<p>When executing &#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
GET https://localhost:8443/controller?dateTime=2017-06-22T17:38
</pre></div>


<p>&#8230; the web service call returns <strong>400 Bad Request</strong> with the following error in the console log:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type &#039;java.lang.String&#039; to required type &#039;java.time.LocalDateTime&#039;; nested exception
is org.springframework.core.convert.ConversionFailedException: Failed to convert from type &#x5B;java.lang.String]
to type &#x5B;@org.springframework.web.bind.annotation.RequestParam java.time.LocalDateTime] for value &#039;2017-06-22T17:38&#039;;
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value &#x5B;2017-06-22T17:38]
</pre></div>


<h2 class="wp-block-heading">SOLUTION</h2>



<p>One solution is to change the data type from <code>java.time.LocalDateTime</code> to <code>java.lang.String</code> before parsing it to <code>java.time.LocalDateTime</code>. However, it is a little more verbose than I like.</p>



<p>A better way is to leverage <code>@DateTimeFormat</code>:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [6]; title: ; notranslate">
@RestController
@RequestMapping(value = &#039;/controller&#039;)
class MyController {

    @RequestMapping(method = RequestMethod.GET)
    ResponseEntity main(@RequestParam(name = &#039;dateTime&#039;) @DateTimeFormat(pattern = &quot;yyyy-MM-dd&#039;T&#039;HH:mm&quot;) LocalDateTime dateTime) {
        // ...

        return ResponseEntity.noContent().build()
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2017/06/22/spring-mvc-failed-to-convert-value-of-type-java-lang-string-to-required-type-java-time-localdatetime/">Spring MVC: Failed to convert value of type &#8216;java.lang.String&#8217; to required type &#8216;java.time.LocalDateTime&#8217;</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/06/22/spring-mvc-failed-to-convert-value-of-type-java-lang-string-to-required-type-java-time-localdatetime/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1050</post-id>	</item>
		<item>
		<title>Spring MVC: Handling Joda Data Types as JSON</title>
		<link>https://myshittycode.com/2015/03/28/spring-mvc-handling-joda-data-types-as-json/</link>
					<comments>https://myshittycode.com/2015/03/28/spring-mvc-handling-joda-data-types-as-json/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Sat, 28 Mar 2015 23:49:18 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Joda-Time]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=681</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we have the following bean that contains Joda&#8217;s LocalDate and LocalDateTime objects:- This simple Spring MVC rest controller creates this bean and returns the JSON data back to the client:- By default, the generated JSON looks like this:- How do we nicely format these values and still retain the correct data types [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2015/03/28/spring-mvc-handling-joda-data-types-as-json/">Spring MVC: Handling Joda Data Types as JSON</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we have the following bean that contains Joda&#8217;s <b>LocalDate</b> and <b>LocalDateTime</b> objects:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class MyBean {
    private LocalDate date;
    private LocalDateTime dateTime;

    public LocalDate getDate() {
        return date;
    }

    public void setDate(LocalDate date) {
        this.date = date;
    }

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime = dateTime;
    }
}
</pre></div>


<p>This simple Spring MVC rest controller creates this bean and returns the JSON data back to the client:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@RequestMapping(value = &quot;/joda&quot;, method = RequestMethod.GET)
public ResponseEntity joda() {
    MyBean myBean = new MyBean();
    myBean.setDate(LocalDate.now());
    myBean.setDateTime(LocalDateTime.now());

    return new ResponseEntity&lt;mybean&gt;(myBean, HttpStatus.OK);
}
</pre></div>


<p>By default, the generated JSON looks like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
{
   &quot;date&quot;:
   &#x5B;
       2015,
       3,
       28
   ],
   &quot;dateTime&quot;:
   &#x5B;
       2015,
       3,
       28,
       18,
       12,
       58,
       992
   ]
}
</pre></div>


<p>How do we nicely format these values and still retain the correct data types (<b>LocalDate</b> and <b>LocalDateTime</b>) in <b>MyBean</b> instead of writing our custom formatter and store the values as <b>String</b>?</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>First, add a dependency for <b>jackson-datatype-joda</b>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [16,17,18,19,20]; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupid&gt;com.fasterxml.jackson.core&lt;/groupid&gt;
    &lt;artifactid&gt;jackson-core&lt;/artifactid&gt;
    &lt;version&gt;2.5.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupid&gt;com.fasterxml.jackson.core&lt;/groupid&gt;
    &lt;artifactid&gt;jackson-databind&lt;/artifactid&gt;
    &lt;version&gt;2.5.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupid&gt;com.fasterxml.jackson.core&lt;/groupid&gt;
    &lt;artifactid&gt;jackson-annotations&lt;/artifactid&gt;
    &lt;version&gt;2.5.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupid&gt;com.fasterxml.jackson.datatype&lt;/groupid&gt;
    &lt;artifactid&gt;jackson-datatype-joda&lt;/artifactid&gt;
    &lt;version&gt;2.5.1&lt;/version&gt;
&lt;/dependency&gt;
</pre></div>


<p>Next, instruct <b>MappingJackson2HttpMessageConverter</b> to accept a custom <b>ObjectMapper</b>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;objectMapper&quot; class=&quot;org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean&quot; p:indentoutput=&quot;true&quot; p:simpledateformat=&quot;yyyy-MM-dd&#039;T&#039;HH:mm:ss.SSSZ&quot;&gt;
&lt;/bean&gt;

&lt;bean class=&quot;org.springframework.beans.factory.config.MethodInvokingFactoryBean&quot; p:targetobject-ref=&quot;objectMapper&quot; p:targetmethod=&quot;registerModule&quot;&gt;
    &lt;property name=&quot;arguments&quot;&gt;
        &lt;list&gt;
            &lt;bean class=&quot;com.fasterxml.jackson.datatype.joda.JodaModule&quot;&gt;
        &lt;/bean&gt;&lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;mvc:annotation-driven&gt;
    &lt;mvc:message-converters&gt;
        &lt;bean class=&quot;org.springframework.http.converter.StringHttpMessageConverter&quot;&gt;
        &lt;bean class=&quot;org.springframework.http.converter.ResourceHttpMessageConverter&quot;&gt;
        &lt;bean class=&quot;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter&quot;&gt;
            &lt;property name=&quot;objectMapper&quot; ref=&quot;objectMapper&quot;&gt;
        &lt;/property&gt;&lt;/bean&gt;
    &lt;/bean&gt;&lt;/bean&gt;&lt;/mvc:message-converters&gt;
&lt;/mvc:annotation-driven&gt;
</pre></div>


<p>The generated JSON output now looks like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
{
   &quot;date&quot;: &quot;2015-03-28&quot;,
   &quot;dateTime&quot;: &quot;2015-03-28T18:11:16.348&quot;
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2015/03/28/spring-mvc-handling-joda-data-types-as-json/">Spring MVC: Handling Joda Data Types as JSON</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2015/03/28/spring-mvc-handling-joda-data-types-as-json/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">681</post-id>	</item>
		<item>
		<title>Spring Security: Handling 403 Error Page</title>
		<link>https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/</link>
					<comments>https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 11 Apr 2014 14:58:31 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[SiteMesh]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=480</guid>

					<description><![CDATA[<p>If you are already using Spring, then you might want to use Spring Security to secure your web resources. To do that, we specify the URI to be secured with &#60;security:intercept-url/&#62; tag:- When users without role ROLE_TOPSECRET access /top-secrets/kfc-secret, they will see this default error page:- This proves that Spring Security is doing its job. [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/">Spring Security: Handling 403 Error Page</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you are already using Spring, then you might want to use Spring Security to secure your web resources.</p>



<p>To do that, we specify the URI to be secured with <code>&lt;security:intercept-url/&gt;</code> tag:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;beans ...&gt;
    &lt;!-- Error pages don&#039;t need to be secured --&gt;
    &lt;security:http pattern=&quot;/error/**&quot; security=&quot;none&quot;/&gt;

    &lt;security:http auto-config=&quot;true&quot;&gt;
        &lt;security:form-login ... /&gt;
        &lt;security:logout ... /&gt;
        &lt;security:intercept-url pattern=&quot;/top-secrets/**&quot; access=&quot;ROLE_TOPSECRET&quot;/&gt;
    &lt;/security:http&gt;
	...
&lt;/beans&gt;
</pre></div>


<p>When users without role <code>ROLE_TOPSECRET</code> access <code>/top-secrets/kfc-secret</code>, they will see this default error page:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" src="http://myshittycode.files.wordpress.com/2014/04/screen-shot-2014-04-11-at-8-47-53-am.png" alt="" class="wp-image-484"/></figure>



<p>This proves that Spring Security is doing its job. However, the default error page looks rather F.U.G.L.Y. Further, the error page may reveal too much information about the application server. The above error page shows the application runs on Jetty. If I&#8217;m a motherhacker, I would research all the possible vulnerabilities on this particular application server in attempt to hack it.</p>



<p>A better solution is to provide a friendly error page when the user access is denied. This can be done by specifying <code>&lt;security:access-denied-handler/&gt;</code> tag:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;beans ...&gt;
    &lt;!-- Error pages don&#039;t need to be secured --&gt;
    &lt;security:http pattern=&quot;/error/**&quot; security=&quot;none&quot;/&gt;

    &lt;security:http auto-config=&quot;true&quot;&gt;
        &lt;security:form-login ... /&gt;
        &lt;security:logout ... /&gt;
        &lt;security:access-denied-handler error-page=&quot;/error/access-denied&quot;/&gt;
        &lt;security:intercept-url pattern=&quot;/top-secrets/**&quot; access=&quot;ROLE_TOPSECRET&quot;/&gt;
    &lt;/security:http&gt;
	...
&lt;/beans&gt;
</pre></div>


<p>Then, we create a simple error controller that returns the error page:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/error&quot;)
public class ErrorController {
    @RequestMapping(value = &quot;/access-denied&quot;, method = RequestMethod.GET)
    public String accessDenied() {
        return &quot;error-access-denied&quot;;
    }
}
</pre></div>


<p>Now, the user will see this custom error page:-</p>



<figure class="wp-block-image aligncenter"><img fetchpriority="high" decoding="async" width="721" height="205" src="https://myshittycode.com/wp-content/uploads/2014/04/screen-shot-2014-04-11-at-8-38-16-am-1.png?x45560" alt="" class="wp-image-483" srcset="https://myshittycode.com/wp-content/uploads/2014/04/screen-shot-2014-04-11-at-8-38-16-am-1.png 721w, https://myshittycode.com/wp-content/uploads/2014/04/screen-shot-2014-04-11-at-8-38-16-am-1-300x85.png 300w" sizes="(max-width: 721px) 100vw, 721px" /></figure>



<p>This solution is better than the previous one. However, SiteMesh doesn&#8217;t have the opportunity to decorate this error page before it gets rendered.</p>



<p>To fix this, we can create a simple redirect to allow the request to make a full-round trip to the server so that SiteMesh can decorate the error page:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [4,5,6,7]; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/error&quot;)
public class ErrorController {
    @RequestMapping(value = &quot;/router&quot;, method = RequestMethod.GET)
    public String errorRouter(@RequestParam(&quot;q&quot;) String resource) {
        return &quot;redirect:/error/&quot; + resource;
    }&lt;/code&gt;
&lt;code&gt;
&lt;/code&gt;
&lt;code&gt;    @RequestMapping(value = &quot;/access-denied&quot;, method = RequestMethod.GET)
    public String accessDenied() {
        return &quot;error-access-denied&quot;;
    }
}

</pre></div>


<p>Then, we tweak the Spring Security to use the error router URI:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;beans ...&gt;
    &lt;!-- Error pages don&#039;t need to be secured --&gt;
    &lt;security:http pattern=&quot;/error/**&quot; security=&quot;none&quot;/&gt;&lt;/code&gt;
&lt;code&gt;

    &lt;security:http auto-config=&quot;true&quot;&gt;
        &lt;security:form-login ... /&gt;
        &lt;security:logout ... /&gt;
        &lt;security:access-denied-handler error-page=&quot;/error/router?q=access-denied&quot;/&gt;
        &lt;security:intercept-url pattern=&quot;/top-secrets/**&quot; access=&quot;ROLE_TOPSECRET&quot;/&gt;
    &lt;/security:http&gt;
&lt;/code&gt;
&lt;code&gt;		...
&lt;/beans&gt;

</pre></div>


<p>Now, the user will see this nice beautiful error page:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" width="845" height="290" src="https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1.png?x45560" alt="" class="wp-image-485" srcset="https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1.png 845w, https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1-300x103.png 300w, https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1-768x264.png 768w" sizes="(max-width: 845px) 100vw, 845px" /></figure>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/">Spring Security: Handling 403 Error Page</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">480</post-id>	</item>
		<item>
		<title>Spring MVC: Centralizing Common Configurations using @ControllerAdvice</title>
		<link>https://myshittycode.com/2014/03/14/spring-mvc-centralizing-common-configurations-using-controlleradvice/</link>
					<comments>https://myshittycode.com/2014/03/14/spring-mvc-centralizing-common-configurations-using-controlleradvice/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 14 Mar 2014 17:45:53 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=386</guid>

					<description><![CDATA[<p>Handling Exceptions using HandlerExceptionResolver Once upon a time, Spring 2.0 introduced HandlerExceptionResolver to handle thrown exceptions. While this approach works, it is like throwing a big net to catch all types of fish. If we are only interested in catching piranhas and clownfish, this approach becomes a little tedious because we need to weed out [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/03/14/spring-mvc-centralizing-common-configurations-using-controlleradvice/">Spring MVC: Centralizing Common Configurations using @ControllerAdvice</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Handling Exceptions using <code>HandlerExceptionResolver</code></h2>



<p>Once upon a time, Spring 2.0 introduced <code>HandlerExceptionResolver</code> to handle thrown exceptions. While this approach works, it is like throwing a big net to catch all types of fish. If we are only interested in catching piranhas and clownfish, this approach becomes a little tedious because we need to weed out the types of fish we don&#8217;t care.</p>


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

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         Object o,
                                         Exception e) {

        ModelAndView modelAndView = new ModelAndView(&quot;error&quot;);

        if (e instanceof PiranhaException) {
            // stir fry it
        }
        else if (e instanceof ClownfishException) {
            // make me laugh first
        }
        else {
            // don&#039;t care...
        }

        return modelAndView;
    }

    @RequestMapping(value = &quot;/error&quot;, method = RequestMethod.GET)
    public String error() {
        return &quot;error&quot;;
    }
}
</pre></div>


<h2 class="wp-block-heading">Handling Exceptions using <code>@ExceptionHandler</code></h2>



<p>Then, Spring 3.0 introduced a more elegant way to handle exceptions using <code>@ExceptionHandler</code>. Now, we can easily catch the types of fish we need and handle accordingly.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/fish&quot;)
public class FishController {

    @ExceptionHandler(PiranhaException.class)
    public String piranhaException(Exception e) {
        // stir fry it
        return &quot;error&quot;;
    }

    @ExceptionHandler(ClownfishException.class)
    public String clownfishException(Exception e) {
        // make me laugh first
        return &quot;error&quot;;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String home() {
        return &quot;home&quot;;
    }
}
</pre></div>


<p>While this is a more elegant solution than the previous approach, <code>@ExceptionHandler</code> has to be defined within the <code>Controller</code> class. If we want to apply the same exception handling across multiple controllers, we either have to define <code>@ExceptionHandler</code> in every <code>Controller</code> class or create something &#8220;clever&#8221; such as extending a parent controller that contains the common configurations.</p>



<h2 class="wp-block-heading">Handling Exceptions using <code>@ControllerAdvice</code></h2>



<p>Then, Spring 3.2 introduced an even better approach to centralize common configurations using <code>@ControllerAdvice</code>. Instead of defining <code>@ExceptionHandler</code> all over places or extending a parent controller, we can create a separate class that contains these common configurations and annotate it with <code>@ControllerAdvice</code>.</p>


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

    @ExceptionHandler(PiranhaException.class)
    public String piranhaException(Exception e) {
        // stir fry it
        return &quot;error&quot;;
    }

    @ExceptionHandler(ClownfishException.class)
    public String clownfishException(Exception e) {
        // make me laugh first
        return &quot;error&quot;;
    }
}
</pre></div>


<p>&#8230; and now, the controller will look as simple as this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/fish&quot;)
public class FishController {

    @RequestMapping(method = RequestMethod.GET)
    public String home() {
        return &quot;home&quot;;
    }
}
</pre></div>


<p>In fact, <code>@ControllerAdvice</code> can be used to define <code>@ExceptionHandler</code>, <code>@ModelAttribute</code> and <code>@InitBinder</code> that apply to all <code>@RequestMapping</code> methods.</p>



<p>Here&#8217;s an example:-</p>


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

    @ExceptionHandler(PiranhaException.class)
    public String piranhaException(Exception e) {
        // stir fry it
        return &quot;error&quot;;
    }

    @ExceptionHandler(ClownfishException.class)
    public String clownfishException(Exception e) {
        // make me laugh first
        return &quot;error&quot;;
    }

    // Catch all other exceptions
    @ExceptionHandler(Exception.class)
    public String exception(Exception e) {
        // when shit happens
        return &quot;error&quot;;
    }

    // Return a list of tech support emails
    @ModelAttribute(&quot;techSupportEmails&quot;)
    public List&amp;lt;String&amp;gt; getTechSupportEmails() {
        return Arrays.asList(&quot;generaltso@chicken.com&quot;, &quot;bat@man.com&quot;);
    }

    // Handles `String` and Joda Time&#039;s `LocalDate` object
    @InitBinder
    private void initBinder(WebDataBinder binder) {
        // Trim string and set empty string as `null` value
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));

        // Convert Joda Time&#039;s `LocalDate` object to text, vice versa
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            private final DateTimeFormatter pattern = DateTimeFormat.forPattern(&quot;MM/dd/yyyy&quot;);

            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(StringUtils.isBlank(text) ? null : pattern.parseLocalDate(text));
            }

            @Override
            public String getAsText() throws IllegalArgumentException {
                LocalDate localDate = (LocalDate) getValue();
                return localDate != null ? pattern.print(localDate) : &quot;&quot;;
            }
        });
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2014/03/14/spring-mvc-centralizing-common-configurations-using-controlleradvice/">Spring MVC: Centralizing Common Configurations using @ControllerAdvice</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/03/14/spring-mvc-centralizing-common-configurations-using-controlleradvice/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">386</post-id>	</item>
		<item>
		<title>MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again</title>
		<link>https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/</link>
					<comments>https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 17 Jan 2014 12:13:19 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Spring MVC Test Framework]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=332</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we want to test this controller:- Here&#8217;s the test file:- When executing this test, we get the following error:- SOLUTION The reason this is happening is because the uri &#8220;/help&#8221; matches the returned view name &#8220;help&#8221; and we didn&#8217;t set a ViewResolver when constructing the standalone MockMvc. Since MockMvcBuilders.standaloneSetup(...) doesn&#8217;t load Spring [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/">MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we want to test this controller:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/help&quot;)
public class HelpController {

    @RequestMapping(method = RequestMethod.GET)
    public String main() {
        return &quot;help&quot;;
    }
}
</pre></div>


<p>Here&#8217;s the test file:-</p>


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

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(new HelpController()).build();
    }

    @Test
    public void main() throws Exception {
        mockMvc.perform(get(&quot;/help&quot;))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;help&quot;));
    }
}
</pre></div>


<p>When executing this test, we get the following error:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
javax.servlet.ServletException: Circular view path &#x5B;help]: would dispatch
back to the current handler URL &#x5B;/help] again. Check your ViewResolver
setup! (Hint: This may be the result of an unspecified view, due to default
view name generation.)
	at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:263)
	at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:186)
	at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:266)
</pre></div>


<h2 class="wp-block-heading">SOLUTION</h2>



<p>The reason this is happening is because the uri &#8220;/help&#8221; matches the returned view name &#8220;help&#8221; and we didn&#8217;t set a <code>ViewResolver</code> when constructing the standalone <code>MockMvc</code>. Since <code>MockMvcBuilders.standaloneSetup(...)</code> doesn&#8217;t load Spring configuration, the Spring MVC configuration under <code>WEB-INF/spring-servlet.xml</code> will not get loaded too.</p>



<p>A typical <code>WEB-INF/spring-servlet.xml</code> looks something like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans ...&gt;

    &lt;context:component-scan base-package=&quot;edu.mayo.requestportal.controller&quot;/&gt;

    &lt;mvc:annotation-driven/&gt;

    &lt;mvc:resources location=&quot;/resources/&quot; mapping=&quot;/resources/**&quot;/&gt;

    &lt;bean id=&quot;viewResolver&quot; class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
        &lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/jsp/view/&quot;/&gt;
        &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;messageSource&quot; class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;messages&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre></div>


<p>To fix this, we need to defined a <code>ViewResolver</code> that mimics the configuration defined under <code>WEB-INF/spring-servlet.xml</code> in the test file:-</p>


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

    private MockMvc mockMvc;

    @Before
    public void setup() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix(&quot;/WEB-INF/jsp/view/&quot;);
        viewResolver.setSuffix(&quot;.jsp&quot;);

        mockMvc = MockMvcBuilders.standaloneSetup(new HelpController())
                                 .setViewResolvers(viewResolver)
                                 .build();
    }

    @Test
    public void main() throws Exception {
        mockMvc.perform(get(&quot;/help&quot;))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;help&quot;));
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/">MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">332</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Lazy Loading (feed)
Database Caching using Disk

Served from: myshittycode.com @ 2026-02-18 23:31:06 by W3 Total Cache
-->