Content Negotiation using Views

Engineering | Paul Chapman | June 03, 2013 | ...

In my previous post I introduced the concept of content negotiation and the three strategies Spring MVC uses to determine the content requested.

In this post I want to extend the concept specifically to supporting multiple views for different content-types using the ContentNegotiatingViewResolver (or CNVR).

Quick Overview

Since we already know how to setup content-negotiation from the previous post, using it to select between multiple views is very straightforward. Simply define a CNVR like this:


    <!--
      // View resolver that delegates to other view resolvers based on the
      // content type…

This Week in Spring - May 28, 2013

Engineering | Josh Long | May 29, 2013 | ...

Welcome to another installment of This Week in Spring. In case you missed it last week, the vast majorty of the SpringOne2GX 2013 agenda has been published, so book now and get the early bird rate on the conference, and airfare! As usual, we've got a lot to cover this week, so let's get to it!

  1. Spring Batch lead Michael Minella announced Spring Batch 2.2.0 RC2. The new release is chalk full of great new features including support for the Spring Batch Java configuration API and a Spring Data GemFire ItemReader and ItemWriter.
  2. Gary Russell just announced Spring Integration 3.0 milestone 2. Be sure to check out the new features and kick the tires!
  3. Join me for a webinar on Building REST-ful Services with Spring - June 13th, 2013. I'll discuss OAUTH, Spring MVC and Spring HATEOAS as it relates to REST.
  4. Rossen Stoyanchev's blogged about the upcoming support for WebSockets in Spring 4 and it looks very compelling!
  5. Gary Russell also just announced the Spring Integration MQTT extension adapter, milestone 1, that makes it easy to work with MQTT - a messaging technology that lends itself to lightweight messaging - from Spring Integration.
  6. Oliver Gierke has written up a great response to the question, how do I return a Spring Data page as JSON on Stack Overflow.
  7. Long-time readers of this roundup will know about Thymeleaf, the templating engine that breathes new life into your web application view templates and that works really well with Spring. The first, stable 2.0.0 version of Thymeleaf-testing has just been released.
  8. Joris Kuipers, on the Trifork blog, has announced a new set of macros for doing form inputs with Spring applications using Freemarker, an alternative - and very powerful - templating engine.
  9. Oleg Tsal-Tsalko put together a talk on the new bits in Spring 4. Nicely done, Oleg!
  10. Johnathan Mark Smith is back at it again, this time with a video on how to do Java configuration with Spring. Check it out!
  11. Maciej Walkowiak put together a great post on how to audit entities using Spring Data MongoDB.
  12. The poorly-named Java2J2EE blog has a great, short-and-sweet post on how to setup JPA and Spring MVC with Spring's Java configuration style. I would however discourage users from calling the lifecycle methods on a Spring FactoryBean directly, and instead choose to dereference the configured result:
    @Bean public EntityManagerFactory emf(){
       LocalContainerEntityManagerFactoryBean lcemfb = ..
       return lcemfb;
    } 
    
    @Bean public PlatformTransactionManager transactionManager(){
      EntityManagerFactory emf = emf().getObject();
      return new JpaTransactionManager( emf );
    } 
    
    

Spring Framework 4.0 M1: WebSocket Support

Engineering | Rossen Stoyanchev | May 23, 2013 | ...

As you may have seen, the first milestone of Spring Framework 4.0 was already announced and with it we've released early WebSocket support. Why WebSocket matters? It enables efficient, two-way communication over the web that is essential in applications where messages need to be exchanged between client (typically browser) and server at high frequency and with low latency. Common examples include trading, games, collaboration, data visualization, and others but the range of scenarios and use cases will grow over time.

WebSocket is a very broad subject! You can watch our “Intro to WebSocket” on…

This Week in Spring - May 21, 2013

Engineering | Josh Long | May 22, 2013 | ...

This Week in Spring

Welcome to another installment of This Week in Spring! We are finally running out of SpringOne2GX video recordings.. this is the last week in Spring that you'll see them, so refer back to the replays page for an index. As usual, we've got a lot to cover so let's get to it!

  1. Spring lead Juergen Hoeller just announced the release of Spring Framework 4.0 M1 and 3.2.3.RELEASE The 3.2.3 update mainly includes updates and fixes related to Java 8 support. The 4.0 milestone, on the other hand, is a look ahead to the many awesome features in Spring 4.0 including support for web sockets, Java EE 7, the @Conditional annotation (in the same vein as the @Profile annotation) and much more, so be sure to check it out!
  2. TcServer 2.9.2 is now available! The release contains security fixes and updates, for more details check out the release notes.
  3. Jennifer Hickey's talk -- Thinking outside the container - Standalone Applications on CloudFoundry has been released in HD on YouTube.
  4. Stephen Bohlen's talk --An Introduction to Spring.NET for Java developers, has been released in HD on YouTube.
  5. InfoQ has done a nice writeup of Spring HATEOAS
  6. Johnathan Mark Smith has put together a nice post on how to use Spring's Java configuration style.
  7. Xavier Padró has put together a nice post on how to communicate within a Spring Web Flow flow
  8. Static.com has announced their Hadoop and Cloud Foundry-powered service. Frankly, it looks really cool and cost-effective as a public platform on which to host applications that need a backoffice Hadoop solution.
  9. I can't believe I missed this! RabbitMQ 3.1.0 is out (slightly old news) and, to introduce it, you should check out this amazing RabbitMQ 3.1.0 in pictures.
  10. The HMKCode blog has a nice post on doing the not-so-well-documented, but common, things with a MyBatis, Spring and jUnit integration.
  11. The Java Code Geeks have put together a nice tutorial on how to process radio buttons in a form in Spring MVC.
  12. Gerry Tan has put together a nice blog on how to bind form date values with Spring MVC.

Spring Framework 4.0 M1 & 3.2.3 available

Engineering | Juergen Hoeller | May 21, 2013 | ...

Dear Spring community,

It's my pleasure to announce the first milestone towards Spring Framework 4.0, delivering a first cut of our work on several key themes:

  • the first wave of Java SE 8 / OpenJDK 8 support (some details following below)
  • initial support for JMS 2.0, JPA 2.1, Bean Validation 1.1, and JSR-236 concurrency (from the EE 7 umbrella)
  • a first cut of our generalized condition mechanism for bean definitions (@Conditional along the lines of @Profile)
  • Spring's WebSocket endpoint model (which Rossen will be introducing in more detail soon)

With respect to Java SE 8, we support OpenJDK 8 build 88+ in several areas of the framework:

  • support for the 1.8 bytecode format in component scanning and subclass generation
  • lambda expressions and method references against Spring callback interfaces
  • JSR-310 Date-Time value types for Spring data binding and formatting
  • initial support for the JDK 8 parameter name discovery mechanism

Note: Spring's Java 8 support is a work in progress and tracking OpenJDK 8 snapshots on their way to the JDK 8 Developer Preview date in September (see http://openjdk.java.net/projects/jdk8/). We expect to release a corresponding Spring Framework 4.0 release candidate around that time, to be presented at SpringOne (September 9-12; see http://springone2gx.com

This Week in Spring - May 14, 2013

Engineering | Josh Long | May 15, 2013 | ...

Welcome to another installment of This Week in Spring! Some rather exciting projects have been announced this week, and if you can believe it, we're almost out of SpringOne 2012 replay content! Good thing the SpringOne 2013 agenda grid is going live very soon, so we'll be able to look ahead. As usual, we've got a lot to cover so let's get to it!

In preparation for the agenda grid going live, a lot of new SpringOne 2013 sessions have been accepted:

  1. Jon Brisbin announced the Reactor project. The Reactor project aims to provide a solid foundation for asynchronous IO-based applications, on top of which it is natural to provide integrations for technologies like Grails and Spring. Reactor already features a good multi-language story with support for Groovy and Java (and, particularly, the upcoming Java 8 release!) Be sure to check this out, especially the comments section if you have questions about how this compares to other asynch technology!
  2. Spring Security lead Rob Winch has been busily enhancing the Spring Security and Spring Security OAuth Java Configuration story. He's got a first cut of the Spring Security OAuth Java Configuration API available, and I'm sure he'd appreciate any feedback on the new DSL, so definitely be sure to check it out! Nice work, Rob!
  3. Webinar on Thursday May 16th with Chris Richardson, author of POJOs in Action, on Decomposing Application for Deployability and Scalabilty. Register Now!
  4. Join Broadleaf Commerce's Andre Azzolini for a Webinar on Tuesday, May 28th as they discuss their Lessons Learned Moving from GWT to SpringMVC.
  5. Paul Chapman introduces some of the diverse support for content negotiation in Spring MVC on the SpringSource blog.
  6. Chris Harris's talk, the Spring Data MongoDB Project, from SpringOne2GX 2012 is now available in HD on YouTube!
  7. Lee Faus's talk, Extreme Makeover - Application Edition, from SpringOne2GX 2012 is now available HD on YouTube!
  8. The JIWHIZ blog, and blogger Yuan Ji, has put together a nice post introducing Spring's Java configuration support.
  9. This post - from blogger Chris Wong in a January post called "JmsTemplate is not evil" - explains some of the subtleties of using Spring's CachingConnectionFactory with a raw ConnectionFactory and then, for extra points, introduces one approach to dramatically speeding up ActiveMQ, in particular.
  10. The HMKcode blog has a nice, exhaustive post introducing how to use the jQuery-file-upload plugin with Spring MVC.
  11. Have you taken a look at HATEOAS yet? HATEOAS is a design pattern, an approach, for building better RESTful web services. Spring HATEOAS makes doing so dead simple atop Spring MVC, and this blog by Geraint Jones introduces Spring HATEAOS very nicely
  12. Blogger Alexey Zvolinskiy answers a common question: how do I bind checkboxes to the model object that's sent back and forth to the server in Spring MVC?
  13. Our friend @baeldung maintains a daily Twitter feed of awesome posts about Spring on StackOverflow, and I think he's dug up some absolutely amazing content. One post answers a question I am frequently asked: how do I enumerate all the Spring MVC @Controller-annotated beans at runtime?
  14. Another great post that I found while trawling through the @SpringAtSO handle was this post, explaining how to propagate request-scoped attributes beyond the thread of the current request. This post applies generally to any situation where a request-scoped attribute needs to propagate beyond its original thread and request.

Reactor - a foundation for asynchronous applications on the JVM

Engineering | Jon Brisbin | May 13, 2013 | ...

We’re pleased to announce that, after a long period of internal incubation, we’re releasing a foundational framework for asynchronous applications on the JVM which we’re calling Reactor. It provides abstractions for Java, Groovy and other JVM languages to make building event and data-driven applications easier. It’s also really fast. On modest hardware, it's possible to process over 15,000,000 events per second with the fastest non-blocking Dispatcher. Other dispatchers are available to provide the developer with a range of choices from thread-pool style, long-running task execution to non…

Content Negotiation using Spring MVC

Engineering | Paul Chapman | May 11, 2013 | ...

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

This Week in Spring - 7 May, 2013

Engineering | Josh Long | May 07, 2013 | ...

Welcome to An Epic Week in Spring! Lots of new sessions have been posted to SpringOne Conference, so head over to the site and check out the featured sessions! We'll have the agenda grid online before the end of May.

Featured SpringOne2GX 2013 sessions accepted!

      <li><a href="http://www.springone2gx.com/conference/santa_clara/2013/09/session?id=29165">Tackling Big Data Complexity with Spring</a> (Mark Fisher and Mark Pollack)</li>
          <li><a href="http://www.springone2gx.com/conference/santa_clara/2013/09/session?id=29395">Reactor - an asynch  framework for distributed web and enterprise architectures</a> (Jon Brisbin)</li>
      
    • Spring for Snowboarders (Dave Syer and Phil Webb)

Many other new sessions accepted as well:

And now, back to our regularly scheduled week in Spring... as usual, we've got a lot to cover, so let's get to it!

  1. Juergen Hoeller and Marius Bogoevici's talk, Java EE services for Spring applications, from SpringOne2GX 2012 is now available in HD on YouTube!
  2. John Davies's talk, Spring Integration in the Wild, from SpringOne2GX 2012 is now available HD on YouTube!
  3. Kim Saabye Pedersen has written a small example on using @Transactional on an interface with Spring's transaction management infrastructure. Nice job, Kim!
  4. Would it be possible to take Spring Petclinic as it is now and scale it up to 1000 requests per second on a single server instance? Julien Dubois from Ippon Technologies has written a great series of five blog entries on that topic. If you missed them from the previous roundups, check out the whole series, starting here!
  5. Petri Kainulainen has written a great post introducing how to sort data using Spring Data SOLR.
  6. By the by, I know I've mentioned this before, but it really is handy. Have you checked out Alvaro Videla's RabbitMQ simulator?
  7. Spring Data ninja Oliver Gierke has written a great response to the question, How do I use Spring Data MongoDB in a multi-tenant fashion? Be sure to check it out. Generally, his advice is applicable to many such scenarios.
  8. Serkan ÖZAL has put together an awesome, bytecode-based RowMapper that can be used with Spring's JDBC infrastructure (like JdbcTemplate) and that can handle relationships like an ORM might. Because it's bytecode-based, it's very fast and not given to the same reflection-based performance limitations of Spring's own BeanPropertyRowMapper. I haven't tried this out yet, but it looks very promising!
  9. Our friend Roger Hughes is back with a tutorial (of two posts, thus far). The first, RESTful Ajax with Spring MVC, establishes an application (without REST and Ajax) and the second then introduces serializing data objects using Jackson, a JSON serializer.
  10. Bharat Sharma also wrote a nice post on serializing to JSON with Spring MVC this week!
  11. Blogger Kal wrote up a nice post on how Spring MVC simplifies file-uploads with Spring MVC and commons-fileupload.

This Week In Spring - April 30th, 2013

Engineering | Josh Long | April 30, 2013 | ...

Welcome to another installment of This Week in Spring! We've got a lot to cover this week, as usual, so let's get to it. Did you miss last week's Pivotal public launch? Catch the replay and learn about GE's investment in the new entity! Pivotal's mission is about bringing consumer-grade software to the enterprise -- where open source technology like Spring, Groovy, Grails, RabbitMQ, Redis, and Cloud Foundry, are already widely adopted. Check out the new Pivotal website, under the Community link (top right) for some other open source initiatives that might surprise you!

  1. Oliver Gierke has announced Spring HATEOAS 0.5, which contains lots of new features!
  2. Spring Security lead Rob Winch has announced that Spring Security 3.1.4 is now available. This is a maintenance release with a number of bug fixes including OSGi support for Spring 3.2.
  3. Spring Data ninja Oliver Gierke also (boy that guy gets around!) tweeted a look at the Spring Data roadmap: introducing Spring Data "Babbage."
  4. Spring Data Arora SR1 released this week (named for Sanjeev Arora). As an aside, you have probably noticed that the names of the various Spring Data release trains are adapted from various influential names in computer science. The new release is named for Charles Babbage.
  5. Adam Shook and Dr. Mark Pollack's webinar, Hadoop, Pivotal HD and Spring for Apache Hadoop, is now available online.
  6. Gil Tene, of Azul Systems, gave an amazing talk at SpringOne2GX 2012 called Understanding Java Garbage Collection and what you can do about it, which is now online.
  7. New SpringOne2GX replays now available in HD on YouTube: Building for Performance with Spring Integration & Spring Batch, Case Study: Provisioning a Multi-Site In-Memory Database
  8. James Watters shared a video he'd discovered on setting up Cloud Foundry and BOSH. It's pretty epic and worth a watch if you want to get a handle on BOSH.
  9. What people write blog posts about sometimes surprises me. The Javarevisted blog has a nice post introducing Spring's (fairly internal, albeit stable) org.springframework.util.StringUtils class, with examples on how to convert collections to delimited strings. I think this is perhaps too much information on the subject, but I love the enthusiasm!
  10. RabbitMQ developer-advocate Alvaro Videla has put together a post on how to unit-test RabbitMQ from PHPUnit. This approach is pretty cool, though I wonder how well it would play in Java and jUnit with concurrent test suite execution. Either way, this is a nice way to unit test my favorite message queue!
  11. Do you need a Spring Integration adapter? Have you checked out the Spring Integration extensions repository? This repository simply collects adapters that move faster than the Spring Integration core, or that are still being polished. It's a great place to find solutions to various problems. Heck, even the pull requests are chock full of useful stuff - I see an MQTT adapter in there by the amazing Gary Russell!
  12. Check out this amazing post on @gopivotal blog called 800,000 Messages/Minute: How Nokia’s HERE Uses #RabbitMQ to Make Real-time Traffic Maps over on the @gopivotal blog. It introduces the Nokia HERE architecture that builds on Spring AMQP and RabbitMQ.

Get the Spring newsletter

Stay connected with the Spring newsletter

Subscribe

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Get support

Tanzu Spring offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Learn more

Upcoming events

Check out all the upcoming events in the Spring community.

View all