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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring 3 and JSON

Spring 3 and JSON

Alex Collins user avatar by
Alex Collins
·
Sep. 17, 10 · Interview
Like (0)
Save
Tweet
Share
52.87K Views

Join the DZone community and get the full member experience.

Join For Free

Spring 3 has brought some excellent features to the table but one that really shines is its REST integration.

You may or may not be wondering what REST really means, I know I did when I heard it banded about for the first time. My first thought - and one that remains today - was that it's another "web 2.0" like marketing phrase that doesn't really mean anything; not entirely fair perhaps, not everyone's as cynical as I.

REST, in essence, means using the HTTP specification properly. For a while now POST has been used as a 'catch all' approach for development, when as per section 9.5 of the spec. it's purely for creating data and is an idempotent method i.e. it shouldn't be used for everything and there are other methods for specific purposes (OK there's more to REST than this, but let's start on familiar ground);

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line 

 So what this basically says is: the server should take the contents of the request body and create an item as it sees fit. You may think this is what we're doing all along, but when - speaking hypothetically - you submit a form to delete a user from your CMS app, POST isn't the right method, DELETE is.

Part of REST is also about abstracting resources so that the data model doesn't matter - a resource will accept JSON, XML or AIML, it's all the same - and behave in the same way. This further opens the door for cross-device interoperability. One example would be to utilise the Accept header from the client to determine how to respond; a request for application/xml would return an XML document. Similarly, your service could respond based on file extensions - .pd, .json, .html and so on.

Spring therefore has extended its annotation based MVC API to provide REST support out of the box, and it's wonderful. For any given controller, you can annotate a method as you would normally but with additional touches you can treat a JSON or standard request the same.

@RequestBody

 This annotation, applied at the method parameter level, maps the request body to a type of your choosing. Taking JSON as an example, and a simple bean whose getters & setters (encapsulating your fields) match the properties of the request, Spring will map the request into your bean without any interference your end. It's very neat and tidy. Something like the following would work nicely (in fact, having this and only the mvc:annotation-driven element plus context scanning in my dispatcher-servlet.xml was all I needed to get up and running;

@RequestMapping(value = "/user", RequestMethod.POST)
public String addUser(@RequestBody User user) {
    // do something with user.name, user.email; etc
    return "success";
}

@ResponseBody

Much the same as @RequestBody, this serialises the response as necessary. If the client sent its Accept header containing application/json then Spring will convert the response - say a UserBean - to a JSON message ready for the client to consume. All you'd need to do for this is use @ResponseBody on your method's return value - lovely and simple.

Path Variables, Atom, RSS and more

That's not all that's in Spring's bag of RESTful treats (pun?!), most notably of which would be its path variable support. If you've used frameworks in Ruby or Python then this is old hat, but forus Java developers it's not so common.

Given a URI, you include the identifier for the resource you're referring to. So, if you wanted to retrieve an employee you might use a URL structure like "/employee/" and instead of using GET parameters you include the identifier you need e.g. "/employee/alex-collins" or "/employee/1337". This makes for a very customisable site. Here's how you'd use it in an annotated controller:

@RequestMapping(value = "/employee/{id}", RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable long empID) {
    Employee employee = employeeService.getByID(empID);
    return employee;
}

 All very fun stuff of course, and there's more. You can get more info over at the Spring documentation.

In the mean time - what's your opinion? Like Spring 3? Using something easier or much more fun? Have you utilised Spring MVC in your organisation for a similar purpose?

JSON Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Set Up and Run Cypress Test Cases in CI/CD TeamCity
  • Unlock the Power of Terragrunt’s Hierarchy
  • Important Data Structures and Algorithms for Data Engineers
  • 5 Common Firewall Misconfigurations and How to Address Them

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: