How to Use CDATA in Spring Configuration Entries

Today I had to create a map in Spring XML configuration file, where both keys and values ought to be XML elements by their own. Obviously, using CDATA is the most readable way to achieve that – but it was not immediately clear how to use CDATA for entry’s key and value attributes.

Here is what I ended with:

<util:map id="patterns">
  <entry>
    <key><value><![CDATA[<original>old-value</original>]]></value></key>
    <value><![CDATA[<replacement>new-value</replacement>]]></value>
  </entry>
</util:map>

Enjoy!

Spring MVC: return view or send error from the same handler

There are many Spring MVC primers on the web that explains Spring MVC basics to some extent. Example of request handler that creates some model data and returns view name is definitely one of the basics and appears in almost each and every primer. Many of those primers also mention HttpServletResponse.sendError() call as a way to produce custom HTTP error codes. However, I did not find any comprehensive example that combines the two and demonstrates the typical REST flow – respond with data object in some cases and send “204 No Content” in others.

So, here comes the example:

	@RequestMapping( value = "/get/{name}", method = RequestMethod.GET )
	public ModelAndView get( @PathVariable( "name" ) String name, HttpServletResponse resp ) throws IOException
	{
		// Check if we have value
		Object value = map.get( name );
		if ( value == null )
		{
			resp.sendError( HttpServletResponse.SC_NO_CONTENT );
			return null; // no further processing needed
		}
		
		// Continue to the view
		ModelAndView mv = new ModelAndView( "show-value" );
		mv.addObject( "value", value );
		return mv;
	}

Note that it is OK to return null in line 9 – at this point there is enough data in the response object to generate valid output.