DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder
  • Using Python Libraries in Java
  • ACID vs BASE: Transaction Models Explained
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  1. DZone
  2. Coding
  3. Frameworks
  4. Content Negotiation Using Spring MVC

Content Negotiation Using Spring MVC

By 
Pieter Humphrey user avatar
Pieter Humphrey
DZone Core CORE ·
Jul. 26, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
27.7K Views

Join the DZone community and get the full member experience.

Join For Free

originally written by paul chapman
paul chapman

there are two ways to generate output using spring mvc:

  • you can use the restful @responsebody approach and http message converters, typically to return data-formats like json or xml. programmatic clients, mobile apps and ajax enabled browsers are the usual clients.
  • alternatively you may use view resolution . although views are perfectly capable of generating json and xml if you wish (more on that in my next post), views are normally used to generate presentation formats like html for a traditional web-application.
  • actually there is a third possibility – some applications require both, and spring mvc supports such combinations easily. we will come back to that right at the end.

in either case you'll need to deal with multiple representations (or views) of the same data returned by the controller. working out which data format to return is called content negotiation .

there are three situations where we need to know what type of data-format to send in the http response:

  • httpmessageconverters: determine the right converter to use.
  • request mappings: map an incoming http request to different methods that return different formats.
  • view resolution: pick the right view to use.

determining what format the user has requested relies on a contentnegotationstrategy . there are default implementations available out of the box, but you can also implement your own if you wish.

in this post i want to discuss how to configure and use content negotiation with spring, mostly in terms of restful controllers using http message converters. in a later post i will show how to setup content negotiation specifically for use with views using spring's contentnegotiatingviewresolver .

how does content negotiation work?

negotiation

getting the right content

when making a request via http it is possible to specify what type of response you would like by setting the accept header property. web browsers have this preset to request html (among other things). in fact, if you look, you will see that browsers actually send very confusing accept headers, which makes relying on them impractical. see http://www.gethifi.com/blog/browser-rest-http-accept-headers for a nice discussion of this problem. bottom-line: accept headers are messed up and you can't normally change them either (unless you use javascript and ajax).

so, for those situations where the accept header property is not desirable, spring offers some conventions to use instead. (this was one of the nice changes in spring 3.2 making a flexible content selection strategy available across all of spring mvc not just when using views). you can configure a content negotiation strategy centrally once and it will apply wherever different formats (media types) need to be determined.

enabling content negotiation in spring mvc

spring supports a couple of conventions for selecting the format required: url suffixes and/or a url parameter. these work alongside the use of accept headers. as a result, the content-type can be requested in any of three ways. by default they are checked in this order:

  • add a path extension (suffix) in the url. so, if the incoming url is something like http://myserver/myapp/accounts/list.html then html is required. for a spreadsheet the url should be http://myserver/myapp/accounts/list.xls . the suffix to media-type mapping is automatically defined via the javabeans activation framework or jaf (so activation.jar must be on the class path).
  • a url parameter like this: http://myserver/myapp/accounts/list?format=xls . the name of the parameter is format by default, but this may be changed. using a parameter is disabled by default, but when enabled, it is checked second.
  • finally the accept http header property is checked. this is how http is actually defined to work, but, as previously mentioned, it can be problematic to use.

the java configuration to set this up, looks like this. simply customize the predefined content negotiation manager via its configurer. note the mediatype helper class has predefined constants for most well-known media-types.

@configuration
@enablewebmvc
public class webconfig extends webmvcconfigureradapter {
 
  /**
    * setup a simple strategy: use all the defaults and return xml by default when not sure.
    */
  @override
  public void configurecontentnegotiation(contentnegotiationconfigurer configurer) {
    configurer.defaultcontenttype(mediatype.application_xml);
  }
}

when using xml configuration, the content negotiation strategy is most easily setup via the contentnegotiationmanagerfactorybean :

<!--
       setup a simple strategy:
          1. take all the defaults.
          2. return xml by default when not sure.
      -->
 <bean id="contentnegotiationmanager"
            class="org.springframework.web.accept.contentnegotiationmanagerfactorybean">
      <property name="defaultcontenttype" value="application/xml" />
 </bean>
 
<!-- make this available across all of spring mvc -->
<mvc:annotation-driven content-negotiation-manager="contentnegotiationmanager" />

the contentnegotiationmanager created by either setup is an implementation of contentnegotationstrategy that implements the ppa strategy (path extension, then parameter, then accept header) described above.

additional configuration options

in java configuration, the strategy can be fully customized using methods on the configurer:

@configuration
@enablewebmvc
public class webconfig extends webmvcconfigureradapter {
 
  /**
    *  total customization - see below for explanation.
    */
  @override
  public void configurecontentnegotiation(contentnegotiationconfigurer configurer) {
    configurer.favorpathextension(false).
            favorparameter(true).
            parametername("mediatype").
            ignoreacceptheader(true).
            usejaf(false).
            defaultcontenttype(mediatype.application_json).
            mediatype("xml", mediatype.application_xml).
            mediatype("json", mediatype.application_json);
  }
}

in xml, the strategy can be configured using methods on the factory bean:

  <!-- total customization - see below for explanation. -->
  <bean id="contentnegotiationmanager"
             class="org.springframework.web.accept.contentnegotiationmanagerfactorybean">
    <property name="favorpathextension" value="false" />
    <property name="favorparameter" value="true" />
    <property name="parametername" value="mediatype" />
    <property name="ignoreacceptheader" value="true"/>
    <property name="usejaf" value="false"/>
    <property name="defaultcontenttype" value="application/json" />
 
    <property name="mediatypes">
        <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
       </map>
    </property>
</bean>

what we did, in both cases:

  • disabled path extension. note that favor does not mean use one approach in preference to another, it just enables or disables it. the order of checking is always path extension, parameter, accept header.
  • enable the use of the url parameter but instead of using the default parameter, format , we will use mediatype instead.
  • ignore the accept header completely. this is often the best approach if most of your clients are actually web-browsers (typically making rest calls via ajax).
  • don't use the jaf, instead specify the media type mappings manually – we only wish to support json and xml.

listing user accounts example

to demonstrate, i have put together a simple account listing application as our worked example – the screenshot shows a typical list of accounts in html. the complete code can be found at github: https://github.com/paulc4/mvc-content-neg .

to return a list of accounts in json or xml, i need a controller like this. we will ignore the html generating methods for now.

@controller
class accountcontroller {
    @requestmapping(value="/accounts", method=requestmethod.get)
    @responsestatus(httpstatus.ok)
    public @responsebody list<account> list(model model, principal principal) {
        return accountmanager.getaccounts(principal) );
    }
 
    // other methods ...
}

here is the content-negotiation strategy setup:

<!-- simple strategy: only path extension is taken into account -->
<bean id="cnmanager"
    class="org.springframework.web.accept.contentnegotiationmanagerfactorybean">
    <property name="favorpathextension" value="true"/>
    <property name="ignoreacceptheader" value="true" />
    <property name="defaultcontenttype" value="text/html" />
    <property name="usejaf" value="false"/>
 
    <property name="mediatypes">
        <map>
            <entry key="html" value="text/html" />
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
        </map>
    </property>
</bean>

or, using java configuration, the code looks like this:

@override
public void configurecontentnegotiation(
        contentnegotiationconfigurer configurer) {
    // simple strategy: only path extension is taken into account
    configurer.favorpathextension(true).
        ignoreacceptheader(true).
        usejaf(false).
        defaultcontenttype(mediatype.text_html).
        mediatype("html", mediatype.text_html).
        mediatype("xml", mediatype.application_xml).
        mediatype("json", mediatype.application_json);
}

provided i have jaxb2 and jackson on my classpath, spring mvc will automatically setup the necessary httpmessageconverters . my domain classes must also be marked up with jaxb2 and jackson annotations to enable conversion (otherwise the message converters don't know what to do). in response to comments (below), the annotated account class is shown below .

here is the json output from our accounts application (note path-extension in url).

how does the system know whether to convert to xml or json? because of content negotiation – any one of the three ( ppa strategy ) options discussed above will be used depending on how the contentnegotiationmanager is configured. in this case the url ends in accounts.json because the path-extension is the only strategy enabled.

in the sample code you can switch between xml or java configuration of mvc by setting an active profile in the web.xml . the profiles are "xml" and "javaconfig" respectively.

combining data and presentation formats

spring mvc's rest support builds on the existing mvc controller framework. so it is possible to have the same web-applications return information both as raw data (like json) and using a presentation format (like html).

both techniques can easily be used side by side in the same controller, like this:

@controller
class accountcontroller {
    // restful method
    @requestmapping(value="/accounts", produces={"application/xml", "application/json"})
    @responsestatus(httpstatus.ok)
    public @responsebody list<account> listwithmarshalling(principal principal) {
        return accountmanager.getaccounts(principal);
    }
 
    // view-based method
    @requestmapping("/accounts")
    public string listwithview(model model, principal principal) {
        // call restful method to avoid repeating account lookup logic
        model.addattribute( listwithmarshalling(principal) );
 
        // return the view to use for rendering the response
        return ¨accounts/list¨;
    }
}

there is a simple pattern here: the @responsebody method handles all data access and integration with the underlying service layer (the accountmanager ). the second method calls the first and sets up the response in the model for use by a view. this avoids duplicated logic.

to determine which of the two @requestmapping methods to pick, we are again using our ppa content negotiation strategy. it allows the produces option to work. urls ending with accounts.xml or accounts.json map to the first method, any other urls ending in accounts.anything map to the second.

another approach

alternatively we could do the whole thing with just one method if we used views to generate all possible content-types. this is where the contentnegotiatingviewresolver comes in and that will be the subject of my next post .

acknoweldgements

i would like to thank rossen stoyanchev for his help in writing this post. any errors are my own.

addendum: the annotated account class

added 2 june 2013 .

since there were some questions on how to annotate a class for jaxb, here is part of the account class. for brevity i have omitted the data-members, and all methods except the annotated getters. i could annotate the data-members directly if preferred (just like jpa annotations in fact). remember that jackson can marshal objects to json using these same annotations.

/**
 * represents an account for a member of a financial institution. an account has
 * zero or more {@link transaction}s and belongs to a {@link customer}. an aggregate entity.
 */
@entity
@table(name = "t_account")
@xmlrootelement
public class account {

	// data-members omitted ...

	public account(customer owner, string number, string type) {
		this.owner = owner;
		this.number = number;
		this.type = type;
	}

	/**
	 * returns the number used to uniquely identify this account.
	 */
	@xmlattribute
	public string getnumber() {
		return number;
	}

	/**
	 * get the account type.
	 *
	 * @return one of "credit", "savings", "check".
	 */
	@xmlattribute
	public string gettype() {
		return type;
	}

	/**
	 * get the credit-card, if any, associated with this account.
	 *
	 * @return the credit-card number or null if there isn't one.
	 */
	@xmlattribute
	public string getcreditcardnumber() {
		return stringutils.hastext(creditcardnumber) ? creditcardnumber : null;
	}

	/**
	 * get the balance of this account in local currency.
	 *
	 * @return current account balance.
	 */
	@xmlattribute
	public monetaryamount getbalance() {
		return balance;
	}

	/**
	 * returns a single account transaction. callers should not attempt to hold
	 * on or modify the returned object. this method should only be used
	 * transitively; for example, called to facilitate reporting or testing.
	 *
	 * @param name
	 *            the name of the transaction account e.g "fred smith"
	 * @return the beneficiary object
	 */
	@xmlelement   // make these a nested <transactions> element
	public set<transaction> gettransactions() {
		return transactions;
	}

    // setters and other methods ...

}



Spring Framework

Published at DZone with permission of Pieter Humphrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!