Here we have a basic webapp using JSP which needs to provide a few JSON based REST service URLs.
These urls will all reside under /services and be generated by a MyRestServicesController.
The examples I see for settings up JSON based views all use ContentNegotiatingViewResolver. But it seems like overkill to me as this resolver seems meant for situations where the same URL might produce different output.
I just want my one RestServicesController to always produce MappingJacksonJsonView(s).
Is there a cleaner, more straight forward way to simply direct the controller to do this?
Is there a cleaner, more straight forward way to simply direct the controller to do this?
Yes there is. You can have a look at this sample I posted in Spring forums. In short the way I prefer to do it is through the following.
ApplicationContext:
<!-- json view, capable of converting any POJO to json format -->
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
Controller
#RequestMapping("/service")
public ModelAndView getResultAsJson() {
Object jsonObj = // the java object which we want to convert to json
return new ModelAndView("jsonView", "result", jsonObj);
}
EDIT 2013: In these modern days, #skaffman's approach would be a nice alternative.
If all you need to do is output JSON, then the view layer itself is redundant. You can use the #ResponseBody annotation to instruct Spring to serialize your model directly, using Jackson. It requires less configuration than the MappingJacksonJsonView approach, and the code is less cluttered.
As long as you are using mvc:annotation-driven and Jackson is on the classpath then all you should need to do is use #ResponseBody on on your methods and the return type will be converted to JSON per Spring's standard HTTP Message Conversion functionality.
Also check out this video at around 37:00: Mastering Spring MVC.
Related
All examples that I have found around internet were about to use content negotiation with json, xml etc. Is there any chance to have only one method producing all kind of contents, like:
#RequestMapping(produces={"text/html","application/json"})
public List<Product> list() {
return productDAO.list();
}
I tried to use the ContentNegotiationManager, but nothing worked for me.
One method can return responses of different content types. Some you can get with default settings, some you have to additionally configure. Take for example a following method, quite similar to yours,
#RequestMapping(value="/response", method=RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public #ResponseBody Foo multipleTypes() {
return new Foo();
}
this method is capable of returning both XML and JSON, even more Spring MVC will automatically configure the converters if you have JAXB2 and Jackson libs on the classpath.
When reasoning whether it will return an XML or JSON its where content negotiation comes to play. If the request is suffixed with a path e.g. /response.json or /response.xml the response will be set based on it. The resolution can be based on a parameter as well, so /response?format=xml. Finally, if the request has an Accept header set to XML or JSON a response will be converted to the respective type. This constitutes a PPA strategy (Path, Parameter, Accept).
In other words, if you provide a proper converter implementations and configure them properly (some are available out of the box), you can get a single method that returns different representations, that you can control based on the PPA strategy.
Content Negotiation Using Spring MVC is a great post on Spring's Blog site with working examples.
I tried to generate a json response earlier using spring-mvc (annotation) . After so may failure i find out some check point :
I need to add <mvc:annotation-driven/> in my servelet mapper. although i don't know the reason.
Then I need to add #ResponseBody annotation which should bound the return value as http response as the documentation says.
And I also need add some jacson dependency.
Did i missed something?
Now i have bunch of questions
why we have to add that in my servelet xml and how this whole process is working?
As json response is most commonly used when why spring need jackson dependency to generate json?
some days ago i was doing Struts2 generating json response there was much simple.
Is there any way to do it more easily in spring-mvc .?
At first you should understand that <mvc:annotation-driven/> annotation used for many cases not only for generating json response in Spring. This annotation allow to use different annotations in Spring mvc classes like:#NumberFormat #DateFormat #Controller #Valid and of course #ResponseBody.
To generate json response you just need #ResponseBody annotation in your controller or servlet and import libraries for processing JSON.
Recently java has oun set of APIs for processing JSON as part of Java EE 7 JSR 353 actually it has clean Oracle tutorial. Also you can use third party libraries like Jackson. To process (parse, generate, transform, and query) JSON text it's necessarily to have one of this libs.
You can learn about most popular third party libraries and their performance in this article
Here you can see simple example.
If you are using jacson you can do something like:
Your Model
public class Shop {
String name;
String staffName[];
}
Your Controller
#Controller
#RequestMapping("/shop/list")
public class JSONController {
#RequestMapping(value="{name}", method = RequestMethod.GET)
public #ResponseBody Shop getShopInJSON(#PathVariable String name) {
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
return shop;
}
}
mvc-dispatcher-servlet.xml
<context:component-scan base-package="com.example.mypackage" />
<mvc:annotation-driven />
Basically, you need check if:
Your Jackson library is existed in the project classpath
The mvc:annotation-driven is enabled
Return method annotated with #ResponseBody
Before AJAX was popular, it was possible to convert between id's and entities by using a custom property editor and registering that in your controllers. So if you had a User form backing object that contained a Company, if company.id was 5, Spring would call your custom property editor to so that you could go fetch the Company with id 5 and set it onto your user.company property.
Now in the Ajax way of doing things, we have similar requirements. Instead of using a form backing object, we want to do an HTTP POST or PUT of a User object as JSON data and have Spring automatically convert that JSON to a User object on our behalf. Spring has made this possible with the #RequestBody annotation, and by using Jackson to marshall the JSON back and forth to Java objects.
This is just a fictitious example. Imagine a User containing a Company object with the appropriate getters/setters.
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.NO_CONTENT)
public void create(#Valid #RequestBody User user) {
userService.saveUser(user);
}
Since property editors are a thing of the past as far as Spring is concerned, we are expected to use the new Conversion Service API. For my application, I have successfully created a factory that does what my old property editor did before - converting id's back to entities.
My question is, how can I get Spring to call into the conversion service during or after Jackson marshals the JSON data? I know it is possible to create a custom JsonDeserializer, but I find writing/testing these to be a pain and lengthy process as I need to do it for a massive number of entities, and each deserializer would take anywhere from 60 to 200 lines of code each.
I'd love it if Spring could do the id to entity mapping for me on my behalf, just as it did for form backing objects. Is there a way?
It will only work the root object User in this case it will not work for nested components. Spring Data REST has a `DomainClassConverter' which you can take a look at.
Basically you want to create ConditionalGenericConverter which checks if it can convert the requested object (i.e. can it be loaded by the EntityManager/SessionFactory). (A non-conditional version is here.
This all goes a bit against REST (basically) to do the lookup on the serverside as you should be sending everything needed with the request (Representational State Transfer and Hypermedia as Transfer Engine of All State). But that is for another discussion :) .
Links
Domain Entity Converter blog
Spring Reference guide
The M. Deinum's answer was great.
But for a practical work , think about AOP ;)
It can be interesting to use it in your problem :).
is their a neat way to pass a model to jsp, render the jsp and return the html as string using Spring. The html is then used in an e-mail that is fired off programmitcally, I do not want to use freemarker, but maybe I should ?
The url being requested is part of the same app.
I want one of my service layer classes to be able to call a view and use the html as a String.
You can call requestDispatcher.include(request, response) method.
You will need to implement the request and response objects. The request object will provide all information to the dispatcher which page should be rendered, the response object you will pass to the call will then capture the result to a string (using e.g. a StringBuilder).
See e.g. this tutorial for more info.
I'm guessing a servlet filter will do the trick? Not really a Spring solution, but easy enough to do.
Also this answer seems relevant, although it is DWR that you may not necessarily want to use in this instance.
You can use Velocity to create an email template:
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "emailTemplate.vm", model);
There is a complete chapter in the Spring reference docs of how Spring can be used to send emails of various types.
I am using Java with Spring framework.
I have a multiaction controller which is having lots of service methods, and I want to to create restful URLs like as following:
http://server.com/url/events/multiActionMethod1
http://server.com/url/events/multiActionMethod2
http://server.com/url/events/multiActionMethod3
http://server.com/url/events/multiActionMethod4
http://server.com/url/events/multiActionMethod5
How can I achieve above tasks?
I think maybe something isn't coming through clearly in your question. It reads like all you're looking for is this:
#RequestMapping("/events/multiActionMethod1")
public ReturnType multiActionMethod1(SomeParameter param) {
//request handling logic
}
is there more to the question you could elaborate on?
edit: ugh no, none of that is in 2. You'd need 2.5 for annotations and 3 if you want support for using parts of the url as parameters. The easiest thing to do if you really want it to work that way in an older version is slap a URL rewriter on the front and convert it to regular query string before it hits spring.