Mined and Summarized Use Cases For API: org.springframework

  1. Spring MVC REST Json Conversion exception

    None .. details

    1. public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, @PathVariable String id) { final ResponseEntity<Property> response = new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK)
    2. return response
    3. }

    • See Also (4)
    1. ModelAttribute for Restful PUT method not populated value ( JSON )

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestBody PositionGPS positionGPS, @PathVariable Long id, Model model)

    2. JSON to Java Mapping Parametric / Generic types

      As an example JSON doesn't have an equivalent to polymorphic types and yet Jackson is able to handle those through annotations. A solution would be to declare a parametric type and use this as the target of RequestBody this way Note that the MyCustomTypeContainer has to be a parametric type(generic types fully realized). details

      Reactions - Positive 2, Negative 0, Others 0

      1. public class MyCustomTypeContainer extends Container<SubContainerItem> {..}public void updateContainer(@RequestBody MyCustomTypeContainer container) { realService.updateContainer(container)
      2. }

      Positive Reactions
      1. Yes true Josh, actually your approach does sound good also.
      2. One change that I can think of is not having the class name in xml, that does not look clean, instead you an try put this information in a custom annotation and use that annotation along with a [HandlerMethodArgumentResolver]( URL_http://docs.spring.io/spring/docs/3.2.x /javadoc- api/org/springframework/web/method/support/HandlerMethodArgumentResolver.html) to create the appropriate JavaType and do the unmarshalling there.
      Other Reactions
      1. Hi Biju, this solution would work if I want to only updateContainer with one concrete type of sub container (SubContainerItem) - but what if I also want to be able to update a container full of SubContainerItem2?

    3. Spring MVC: Don't deserialize JSON request body

      I'm guessing your body is not simply a String but some full JSON object. If you have a java model of the JSON object you are expecting then you could replace the String parameter with that in your doSomething declaration such as If you don't have a Java object that matches the JSON then you could try to get it working by replacing the String type with a Map<String Object and see if that gets you closer to a working solution. details

      Reactions - Positive 5, Negative 5, Others 0

      1. public void doSomething(@RequestBody MyObject myobj) {

      Positive Reactions
      1. I'd be interested in how Bart's solution would work.
      2. As a workaround you could simply define a simple class that exposes a string value.
      3. Don't use @RequestBody, and send the json value as a regular request param in a form.
      4. It does work!
      5. That looks like it should work perfectly, thanks @digitaljoel.
      Negative Reactions
      1. Never mind, that was my own fault, actually.
      2. Sorry about that.
      3. It throws this exception: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of javax.servlet.http.HttpServletRequest, problem: abstract types can only be instantiated with additional type information.
      4. To make matters more complex, the application only accepts Content-Type values of application/json so even if every client could send this particular request as plaintext it would be rejected by the application (I can't change this).
      5. Sorry to double comment, but I can't edit my above comment.
      Other Reactions
      1. I enabled debug logging in Spring and came up with this exception: org.codehaus.jackson.map.JsonMappingException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_ARRAY token - so how would I skip the deserializing part and just retrieve the JSON data as a string?
      2. I normally would map it to a Java object but I need to modify the raw JSON before I create the object, hence why I need the raw JSON string.
      3. I don't know how Jackson would map it appropriately.
      4. I updated my answer with a new possible solution.
      5. If you want it as a string then you should send it as a String.
      6. I'm unaccepting this answer as it doesn't seem to work, actually.
      7. This is for a REST API interfacing with middleware, the middleware will be directly calling the routes with the JSON as the body of the request.
      8. Just because the String contains JSON content doesn't mean you need to tell Spring MVC that.
      9. e.g.
      10. You're right - the body is a full JSON object.
      11. class JsonValue { getValue(); }.

    4. Spring REST multiple @RequestBody parameters, possible?

      I'm pretty sure that won't work. There may be a workaround but the much easier way would be to introduce a wrapper Object and change your signature . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public class PersonContext{ private UserContext userContext
      2. private Person person
      3. // getters and setters}public Person createPerson(@RequestBody PersonContext personContext)

      Positive Reactions
      1. Thanks, I'm considering a wrapper Array as the last resort.
      Other Reactions
      1. What is the work around you were referring to?
      2. @Srirangan I said there may be a workaround.
      3. @Srirangan: the workarround is the PersonContext class - it is some kind of DTO.
      4. I am not aware of one myself.

  2. Right way to write JSON deserializer in Spring or extend it

    None .. details

    1. @Servicepublic
    2. class AnchorService {}

  3. Sending a JComponent as an image

    Instead of them receiving it as a series of x,y co-ordinates they've asked me to send an image. To capture an image of a component create an image get a graphics context for the image then ask the component to paint itself using that graphics context import java.awt.image.BufferedImage if not already. .. details

    1. Component comp = ...
    2. BufferedImage image = new BufferedImage(comp.getWidth(), comp.getHeight(), BufferedImage.TYPE_INT_RGB)
    3. Graphics2D g = image.createGraphics()
    4. comp.paint(g)
    5. g.dispose()

    Positive Reactions
    1. Thanks Boann, I will look into this as soon as I can and then tick it if it works.
    Other Reactions
    1. I haven't forgotten you, just had a another large task fall on my lap and haven't had a chance to give this a second look.

  4. Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

    None .. details

    1. @RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

    • See Also (1)
    1. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller
      2. @RequestMapping("/test")
      3. public class TestController {
      4. @RequestMapping(method = RequestMethod.POST, value = "math")
      5. @ResponseBody
      6. public Result math(@RequestBody final Request request) {
      7. final Result result = new Result()
      8. result.setAddition(request.getLeft() + request.getRight())
      9. result.setSubtraction(request.getLeft() - request.getRight())
      10. result.setMultiplication(request.getLeft() * request.getRight())
      11. return result
      12. }
      13. }

  5. Convert Entity object to JSON

    And i put jackson libraries to classpath. is what you need and DO NOT FORGET to make a POST request in your JS code not GET). .. details

    1. @RequestMapping(produces="application/json")

    • See Also (7)
    1. JSONMappingException - cannot desierialize Java object

      Your best bet would be to write a custom bean to deserialize the JSON into then instantiate a PageImpl with the values from this custom bean. I ended up using something like this creating a bean as Perception suggested and then modify your code to use the concrete class and get the PageImpl . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.springframework.data.domain.PageImpl
      4. import org.springframework.data.domain.PageRequest
      5. import org.springframework.data.domain.Sort
      6. public class PageImplBean<T> extends PageImpl<T> {
      7. private static final long serialVersionUID = 1L
      8. private int number
      9. private int size
      10. private int totalPages
      11. private int numberOfElements
      12. private long totalElements
      13. private boolean previousPage
      14. private boolean firstPage
      15. private boolean nextPage
      16. private boolean lastPage
      17. private List<T> content
      18. private Sort sort
      19. public PageImplBean() {
      20. super(new ArrayList<T>())
      21. }
      22. public int getNumber() {
      23. return number
      24. }
      25. public void setNumber(int number) {
      26. this.number = number
      27. }
      28. public int getSize() {
      29. return size
      30. }
      31. public void setSize(int size) {
      32. this.size = size
      33. }
      34. public int getTotalPages() {
      35. return totalPages
      36. }
      37. public void setTotalPages(int totalPages) {
      38. this.totalPages = totalPages
      39. }
      40. public int getNumberOfElements() {
      41. return numberOfElements
      42. }
      43. public void setNumberOfElements(int numberOfElements) {
      44. this.numberOfElements = numberOfElements
      45. }
      46. public long getTotalElements() {
      47. return totalElements
      48. }
      49. public void setTotalElements(long totalElements) {
      50. this.totalElements = totalElements
      51. }
      52. public boolean isPreviousPage() {
      53. return previousPage
      54. }
      55. public void setPreviousPage(boolean previousPage) {
      56. this.previousPage = previousPage
      57. }
      58. public boolean isFirstPage() {
      59. return firstPage
      60. }
      61. public void setFirstPage(boolean firstPage) {
      62. this.firstPage = firstPage
      63. }
      64. public boolean isNextPage() {
      65. return nextPage
      66. }
      67. public void setNextPage(boolean nextPage) {
      68. this.nextPage = nextPage
      69. }
      70. public boolean isLastPage() {
      71. return lastPage
      72. }
      73. public void setLastPage(boolean lastPage) {
      74. this.lastPage = lastPage
      75. }
      76. public List<T> getContent() {
      77. return content
      78. }
      79. public void setContent(List<T> content) {
      80. this.content = content
      81. }
      82. public Sort getSort() {
      83. return sort
      84. }
      85. public void setSort(Sort sort) {
      86. this.sort = sort
      87. }
      88. public PageImpl<T> pageImpl() {
      89. return new PageImpl<T>(
      90. getContent(), new PageRequest(getNumber(), getSize(), getSort()), getTotalElements())
      91. }
      92. }

    2. Some information about how Spring MVC recive and use the Accept Header in these two case

      Your method is matching on any URI pattern that ends in json and in both cases your URL ends in json. If you want to filter on things that have an Accept header of JSON then I think you want to do something like this Please understand I typed the above from memory so you may need to tweak it a tad. details

      Reactions - Positive 2, Negative 0, Others 0

      1. @RequestMapping(value="/someUriPattern", headers = {"Accept=application/json"})

      Positive Reactions
      1. Ok,thank you very muchSo, are you sayng to me that if I would that my controller method manage only JSON object coming from my view I have to put the element "Accept=application/json" inside my RequestMapping annotation?
      2. What I am saying is that, if you want to limit calls to that method to only things that are requesting JSON, its probably a good idea to add the proper header (again, I typed that off of memory...please google to verify I didn't typo).

    3. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/run/")

    4. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/run/*")

    5. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/run/*")

    6. Sending JSON to Spring MVC controller

      However in your Controller class you do not have any method bound to this URL. Because you've annotated the class with and the method is annotated with the method is actually bound to the URL run/save which is neither the URL you are sending data to with nor the URL the form is pointing at. details

      Reactions - Positive 0, Negative 1, Others 0

      1. @RequestMapping("save")

      Negative Reactions
      1. sorry, it should be run/save but still same problem.
      Other Reactions
      1. Did you take my suggestion to turn up logging to examine exactly which methods are bound to exactly which URLs?
      2. matt b...bulls eye..i have also suggested the same answer...
      3. I don't think you need the in the @RequestMapping(/application/*).

    7. Spring MVC AJAX and JSON using Custom View Resolver, and Custom View

      I'm not sure the path of my form submission and there obviously is no JSP view for it I'm expecting JSON to be returned actually but for some reason this isn't working it's just trying to forward me to some JSP so I'm guessing that I need to specify how to handle this in my XML but I've seen about 1000 different ways that people return JSON and all of them are very confusing to me I'm just looking for the simplest way so I can take it from there edit I added an answer which is a good start but it allows you to type json after any URL and it will do some really bad things if as the controller I'm not expecting it so I need to somehow have this view resolver only apply to secured URLs . Ok finally after trying a million combinations and then this I don't really understand how I can return an object from here. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/test/data") public TestFormData dostuff() { TestFormData data = new TestFormData()
      2. data.setName("myname")
      3. return data
      4. }

  6. Configuring Web Service &amp; thin client using Servlet+JSON+MySQL

    None .. details

    1. package com.example.repositories
    2. import org.springframework.roo.addon.layers.repository.jpa.RooJpaRepository
    3. @RooJpaRepository(domainType = Example.class)
    4. public interface ExampleRepository {}

  7. Configuring Web Service &amp; thin client using Servlet+JSON+MySQL

    None .. details

    1. @RooWebJson(jsonObject = Example.class)
    2. @Controller
    3. @RequestMapping("/example/")
    4. public class ExampleController {
    5. @Resource ExampleRepository exampleRepo
    6. @RequestMapping(method = RequestMethod.PUT, value = "/{name}")
    7. public void putExample(@PathVariable("name") String name) {
    8. exampleRepo.save(new Example(name))
    9. }
    10. }

    • See Also (2)
    1. Is it possible to repeat parameter RESTful Spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/test/{tests}", method=RequestMethod.GET)@ResponseBodypublic String test(@PathVariable String tests){ String[] test= tests.split(",")
      2. return "sth"
      3. }

    2. RESTful MySQL / Terminology / Passing Parameters / Returning Ints & Doubles

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/people/gender/{gender}/updated/{lastUpdated}", method = RequestMethod.GET)@ResponseBodypublic Person findByGenderAndUpdated(@PathVariable String gender, @PathVariable String lastUpdated) {}

  8. ModelAttribute for Restful PUT method not populated value ( JSON )

    Add the below filter to your WebApplicationInitializer class or corresponding xml code to web.xml . Im replace for Link help reference/html/mvc.html#mvc-config-enable reference/html/mvc.html#mvc-config-enable and json-request-body Spring-MVC:-Don't-deserialize-JSON-request-body . .. details

    1. @ModelAttribute("positionGPS") PositionGPS positionGPS, @PathVariable Long id, Model model

    Positive Reactions
    1. You specified you're using Postman, but that obviously isn't going to be your final working solution.
    2. I tested on a cell application and backbone and everything works.
    Other Reactions
    1. You'll have to use either Ajax or a form post.
    2. And did that work?
    3. If it did then I assume you already have Jackson on the classpath for marshaling from JSON to an object.
    4. If you're using a form post this still isn't going to work because that doesn't support a PUT operation cross-browser.

  9. ModelAttribute for Restful PUT method not populated value ( JSON )

    If you can't use Ajax the only other option is to tunnel everything through POST for create update and delete operations. Add the below filter to your WebApplicationInitializer class or corresponding xml code to web.xml . .. details

    1. final FilterRegistration.Dynamic httpMethodFilter = servletContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter())
    2. httpMethodFilter.addMappingForUrlPatterns(null, true, "/*")
    3. final FilterRegistration.Dynamic putFormFilter = servletContext.addFilter("httpPutFormContentFilter", new HttpPutFormContentFilter())
    4. putFormFilter.addMappingForUrlPatterns(null, true, "/*")

  10. How to send Json response in spring?

    Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go Just a little summary As you know you will need the Jackson library in the class path so that Objects can be converted to JSON. .. details

    1. @RequestMapping(value = "/getfees", method = RequestMethod.POST)public @ResponseBodyDomainFeesResponse getFees( @RequestHeader(value = "userName") String userName, @RequestHeader(value = "password") String password, @RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) { return domainFeesHelper.executeRetreiveFees(userName, password, syncDate)
    2. }

    • See Also (4)
    1. JSON character encoding

      I dont know if this is relevant anymore but I fixed it with the RequestMapping annotation. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, produces={"application/json
      2. charset=UTF-8"})

    2. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})

    3. Spring JSON request getting 406 (not Acceptable)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)

    4. In Spring MVC, how can I set the mime type header when using @ResponseBody

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public View fooBar(){ return new JsonView(myService.getJson())
      2. }

  11. Spring REST with both JSON and XML

    I'm doing this in a current project without using a ContentNegotiatingViewResolver. For one method in my controller I can receive the following output based on the Accept request header. .. details

    1. @RequestMapping(value = "/test", method = RequestMethod.GET)@ResponseBodypublic HttpEntity<BasicResponse> getBasicResponse() { return new HttpEntity<BasicResponse>(new BasicResponse())
    2. }

    Negative Reactions
    1. Thanks for your answer, but I wasn't clear enough in my question.
    2. I too get valid xml & json, but a pretty xml api becomes an ugly json api and the other way around.
    Other Reactions
    1. I think @chrylis was spot on.

    • See Also (1)
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1 the implementation looks quite neat Comments First the mvc:annotation-driven or the EnableWebMvc must be reference/html/mvc.html#mvc-config-enable added to your application config. details

      Reactions - Positive 3, Negative 0, Others 0

      1. @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar")@ResponseBodypublic Bar fooBar(){ return myService.getBar()
      2. }

      Positive Reactions
      1. Thanks!.
      2. This answer should be number one, let Spring do the work for you!
      3. Worked great.
      Other Reactions
      1. !.

  12. 400 Bad request on Spring ajax call

    script Spring Controller . Your saveInvestmentValue method expects a . .. details

    1. @RequestParam("transactionDate")

    Negative Reactions
    1. sorry, the project wasnt clean, it worked after cleaning the project, thanks again.
    Other Reactions
    1. thanks, edited that, but still having error.

  13. spring generic json response

    None .. details

    1. @Controllerpublic
    2. class MyController {
    3. @RequestMapping(value = "/mypath", produces = "application/json")
    4. public Response<SomeObject> myPathMethod() {
    5. return new Response<SomeObject>("200", "success!", new SomeObject())
    6. }
    7. }

  14. Providing RESTful JSON API in Java

    None .. details

    1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

  15. How to validate request parameter if it is not a bean in spring MVC?

    None .. details

    1. @RequestMapping(value = "/some/path", method = RequestMethod.POST)@ResponseBodypublic Foo bar(@Valid @RequestBody LongList listOfLongs) { // do some useful work}

  16. Spring MVC + JSON = 406 Not Acceptable

    Thank you very much with your antecedent post I've finally managed to get it working. You have to register the annotation binding for Jackson in your spring-mvc config.xml for example Then in your controller you can use . .. details

    1. @RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")@ResponseBody

    • See Also (5)
    1. Spring 3.2 Web MVC @ModelAttribute without label

      It seems that you use jQuery datatables so you should add ResponseBody to the method . . details

      Reactions - Positive 2, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.GET)@ResponseBody public DTResponse agents() { DTResponse resp = new DTResponse()
      2. resp.setsEcho(1)
      3. resp.setiTotalDisplayRecords(10)
      4. resp.setiTotalRecords(50)
      5. return resp
      6. }}

      Positive Reactions
      1. Thanks :).
      2. Works like a charm.

    2. Spring 3.1, JSON response ModelAndView

      Then you would need to tell JQuery to expect HTML or Text but not JSON. If what you want is json to update some parts of the page don't return a ModelAndView return String make sure to have a json serializer . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html") public @ResponseBody String addSubMenu() { //yourvariable return yourvariable.toString()
      2. }

      Positive Reactions
      1. True, it will return a String, if an object is needed, replace String with your object and you can serialize it using jackson library for example.
      Other Reactions
      1. If you want to deliver some browser renderable code, I would delegate the view rendering to the View layer using ModelAndView (without the ReponseBody Annotation) as result.
      2. If you want to return an object, consider returning an Object and let Spring marshal it to JSON.
      3. This would deliver what ever you have in yourvariable.

    3. Redirect at @ResponseBody?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/postLogout.html", method=RequestMethod.GET)@ResponseBody public MyreturnObject getPostLogout(){ return new ReturnObject(true,true,false)
      2. }

    4. In Spring MVC, how can I set the mime type header when using @ResponseBody

      Register org.springframework.http.converter.json.MappingJacksonHttpMessageConverter as the message converter and return the object directly from the method. and the controller . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public @ResponseBody Object fooBar(){ return myService.getActualObject()
      2. }

      Positive Reactions
      1. Yes, probably a best practice, but as I wrote my objects are already JSON strings and I just want to write them out with the correct mime type.
      Other Reactions
      1. org/springframework/spring-webmvc should cover it.
      2. What are the maven dependencies for the beans you are referencing?

    5. Spring 3.0 making JSON response using jackson message converter

      3. Use as the following This works for me. details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })public @ResponseBody Foo method(@Valid Request request, BindingResult result){return new Foo(3,4)}

      Positive Reactions
      1. @ResponseBody is applied to return type - this was my issue, thanks!.
      Other Reactions
      1. Providing that, as you suggest, is important.
      2. The key part here, I think, is that the OP doesn't have a RequestMapping.
      3. For testing your post requests with Curl or upgrading to spring 3.2 checkout [here]( URL_http://stackoverflow.com/questions/16909742/spring-3-2-0-web-mvc-rest - api-and-json2-post-requests-how-to-get-it-right-onc).
      4. @GaryF updated my answer.

  17. Sending list in JSON request

    Define below bean return jsonView from the controller. Controller Change in ajax viewsResolver config in mvc-servlet.xml . .. details

    1. import org.springframework.ui.ModelMap
    2. @RequestMapping(value = "/testURL.do", method = RequestMethod.POST)public String executeTest(ModelMap model, ListData listData) { ModelAndView modelAndView = null
    3. JsonResponse jsonResponse = null
    4. modelAndView = executeTransaction(listData)
    5. model.addAttribute("paramName", modelAndView)
    6. } return "jsonView"
    7. }

    Positive Reactions
    1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
    2. Thanks a lot Boss!.
    3. Thanks but we are not using Gson.
    4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
    Other Reactions
    1. Point Number 2 is not related to gson, it is spring.
    2. I update the answer with all changes required.
    3. Or I need to do additional processing in controller?
    4. We are using Jackson.

  18. Serializing enums with Jackson

    also I found good workaround sedCommentId=306450&page=com.atlassian.jira.plugin.system.issuetabpanels comment-tabpanel#comment-306450. available since just tested it works with version 2.1.2 answer to TheZuck** I tried your example got Json My code and dependencies are . .. details

    1. @RequestMapping(value = "/getEvent") @ResponseBody public EventContainer getEvent() { EventContainer cont = new EventContainer()
    2. cont.setEvents(Event.values())
    3. return cont
    4. }class EventContainer implements Serializable { private Event[] events
    5. public Event[] getEvents() { return events
    6. } public void setEvents(Event[] events) { this.events = events
    7. }

    Positive Reactions
    1. Upgraded to 3.2.1 and all is well now.
    2. Thanks!.
    3. Using on Mule 3.4.1 and it is working like a charm!.
    Negative Reactions
    1. found out what was wrong, I was using Jackson 2.1.2 but my Spring version was still 3.1 hence did not support this version.
    Other Reactions
    1. @JsonFormat(shape= JsonFormat.Shape.OBJECT)@JsonAutoDetect()public enum Event { VISIT_WEBSITE(Type.ADMIN); @JsonProperty public Type type; public Type getType() { return type; } Event(Type type) { this.type type; } public enum Type { ADMIN, CONSUMER, }}I'm using Jackson 2.1.2.
    2. I like this alternative, it's cleaner, however, I tried it with this class and type does not get serialized, any idea what's wrong?
    3. I've added additional details to body of answer.

    • See Also (1)
    1. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

  19. org.springframework.web.bind.MissingServletRequestParameterException

    If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. Providing a defaultValue implicitly sets required to false so I'll leave it out of the example Hope this helps . .. details

    1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
    2. }

    • See Also (1)
    1. org.springframework.web.bind.MissingServletRequestParameterException

      RequestParam has an attribute required which is true by default. If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

  20. Java web framework with RESTful JSON services, HTML5 &amp; jQuery ajax

    If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. .. details

    1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
    2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
    3. } ...}public class Resource{ @JsonProperty("id") private int id
    4. @JsonProperty("resourceName") private String name
    5. ...}

    • See Also (1)
    1. Spring JSON request getting 406 (not Acceptable)

      You're probably fine then sorry I couldn't be more help on this. In the controller shouldn't the response body annotation be on the return type and not the method like so I'd also use the raw jquery.ajax function and make sure contentType and dataType are being set correctly. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){ Weather weather = weatherService.getCurrentWeather(id)
      2. return weather
      3. }

      Other Reactions
      1. The placement of @ResponseBody should not matter...
      2. I will look into GSON...but still would like this JSON to work if possible.

  21. Spring 3.1, JSON response ModelAndView

    Your server would like to serialize the ModelAndView Object as a JSON string and your jQuery code wants to append an HTML element to the DOM. There are a few things which could be wrong here By specifying a Content-type header of application/json you are expecting a response of json back however looking at the way you are handling the response it looks like what you want is an html if it is html that you are looking for as a response then remove the Content Type header from the request remove the ResponseBody annotation from ModelAndView response instead just return a view which points to a normal jsp which can create the html response that you are expecting . .. details

    1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")public ModelAndView addSubMenu(@RequestBody Menu menu) {...}

    Other Reactions
    1. This would be my understanding of a partial.
    2. Then you would need to tell JQuery to expect HTML or Text but not JSON.
    3. This would deliver HTML Code (Model delivered form controller, view delivered from Template) to the client.

    • See Also (1)
    1. Interfaces and @RequestBody

      Sure thing my apologies!. I'm not sure it would work but you can try to make it generic . details

      Reactions - Positive 3, Negative 0, Others 0

      1. public interface BookableResourceController<R extends BookableResource> {
      2. @RequestMapping(value = "/delete.html", method = RequestMethod.POST)
      3. public ModelAndView processDeleteResource(@RequestBody R resource)
      4. }

      Positive Reactions
      1. I'm not too well versed in generics, so I never would have thought of this.
      2. Thank you for the quick response!.
      3. That worked beautifully!

  22. Generate JSON in JAVA

    put each row contents in a map . Essentially you want something like this This might need to be adjusted to meet your needs but it should at least show you how to do it. .. details

    1. ModelMap [] rowMap = new ModelMap()[3]
    2. for (int i=0
    3. i<3
    4. i++){ ModelMap this_row=new ModelMap()
    5. this_row.put("id",i)
    6. this_row.put("name","name"+i)
    7. rowMap(i)=this_row
    8. }modelMap.put("rows",rowMap)

    Other Reactions
    1. I have an error in your first line The type of the expression must be an array type but it resolved to ModelMap.

    • See Also (1)
    1. Spring MVC returning JSONS and exception Handling

      Return a model and a view instead. To add the exception you'd do it the same way with a key and success false. details

      Reactions - Positive 3, Negative 1, Others 0

      1. public ModelMap getUserDetails() { UserDetails userDetails
      2. // get this object from somewhere ModelMap map = new ModelMap()(
      3. map.addAttribute("data", userDetails)
      4. map.addAttribute("success", true)
      5. return map
      6. }

      Positive Reactions
      1. Brain fart from returning views as well.
      2. I don't see what value ModelAndView adds here.
      3. I am unsure of why I would want to use a ModelAndView however you gave me the idea of using a map (HashMap) which worked like a charm and gave me the desired output.
      Negative Reactions
      1. However how do I do the same in a fail scenario?
      Other Reactions
      1. Why not just return the ModelMap?
      2. @milindaD ModelMap doesn't require keys but not much different.
      3. @skaffman You're right.
      4. However any idea of a way to centralize this when for all controllers and all functions in the controllers?
      5. It implements Map.

  23. Binding the nested json to @RequestBody object using Jackson converter

    The issue was fixed by adding below logic. Here your Java class DrugListJsonRequest should extend It doesn't require a any methods and constructors. .. details

    1. public @ResponseBody String saveDrug(@RequestBody DrugListJsonRequest drugListCriterion) {}

    • See Also (2)
    1. Marshaling JSON and Generics in Java with Spring MVC

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String setJobStatus(@RequestBody JobUpdateList jobUpdates) {

    2. Marshaling JSON and Generics in Java with Spring MVC

      Your solution worked for me D tnx. I ended up creating another class So in the controller instead of i did this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String setJobStatus(@RequestBody List<JobUpdate> jobUpdates) {

  24. java spring MappingJacksonJsonView not doing toString on mongodb ObjectId

    None .. details

    1. @Bean(name = "jsonView")public MappingJacksonJsonView jsonView() { final MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView()
    2. mappingJacksonJsonView.setContentType("application/json")
    3. mappingJacksonJsonView.setObjectMapper(new CustomObjectMapper())
    4. return mappingJacksonJsonView
    5. }

  25. JQuery, Spring MVC @RequestBody and JSON - making it work together

    None .. details

    1. @RequestMapping(value = "/ajax/search/sync") public String sync(@RequestBody Foo json) {

    • See Also (2)
    1. Jackson : Converting JSON property to nested Object with Dot Notation

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/saveChild.json")@ResponseBodypublic Child saveChild(@RequestBody Child child) { // do something with child return child
      2. }

    2. Parsing JSON in Spring MVC using Jackson JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("somepath")@ResponseBodypublic Fozzle doSomeThing(@RequestBody Fizzle input){ return new Fozzle(input)
      2. }

  26. Spring 3.0 making JSON response using jackson message converter

    Thx I have tried that before it isnt. In addition to the answers here if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . .. details

    1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody Foo json) {

    • See Also (1)
    1. Parsing json into java objects in spring-mvc

      Thanks!. if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody SearchRequest json) {

  27. Jackson 2.0 with Spring 3.1

    or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . .. details

    1. package foo.bar.JacksonConfig
    2. import com.fasterxml.jackson.databind.ObjectMapper
    3. import com.fasterxml.jackson.databind.SerializationFeature
    4. import org.springframework.beans.BeansException
    5. import org.springframework.beans.factory.config.BeanPostProcessor
    6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
    7. @Componentpublic
    8. class JacksonConfig implements BeanPostProcessor {
    9. public Object postProcessBeforeInitialization(Object bean, String beanName)
    10. throws BeansException {
    11. return bean
    12. }
    13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    14. if (bean instanceof MappingJackson2HttpMessageConverter) {
    15. MappingJackson2HttpMessageConverter jsonConverter =
    16. (MappingJackson2HttpMessageConverter) bean
    17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
    18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
    19. jsonConverter.setObjectMapper(objectMapper)
    20. }
    21. return bean
    22. }
    23. }

    Positive Reactions
    1. @Ryan this works great.
    2. I'm sure that this is not the official way but it's very clever!.
    Negative Reactions
    1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
    Other Reactions
    1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  28. spring mvc passing objects with post method

    None .. details

    1. boolean createModel( @JsonArg SettlementModelGroup modelGroup, @JsonArg Integer periodId, @JsonArg Integer domainId, @JsonArg Integer modelTypeId )

  29. springmvc using json response

    Then just return your item formattedDate. . .. details

    1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
    2. Date date = new Date()
    3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
    4. String formattedDate = dateFormat.format(date)
    5. model.addAttribute("serverTime", formattedDate )
    6. return "main"
    7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
    8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
    9. return dateFormat.format(date)
    10. }

    Positive Reactions
    1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
    2. Did you resolve your issue?
    3. Nope, I think doing that's just fine.
    Negative Reactions
    1. Ah, sorry about that.
    2. Do you think it's a bad idea to have the controller handle the views?
    3. That seems a bit nasty.
    Other Reactions
    1. Load your view at the root.
    2. also - I don't think that code would even compile with duplicate method names.
    3. Are you suggesting I go to one url for the JSON response and another for the html?
    4. Changed in the example just for future reference.
    5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
    6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
    7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
    8. Is it possible to do both?
    9. I see you marked it as an answer.
    10. Or did you still need help with that?
    11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
    12. I've included jackson-core-asl in my pom.xml.
    13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
    14. Then your view should make an ajax request for the data at /serverTime.
    15. Updated with an example.

  30. springmvc using json response

    I see you marked it as an answer. There's a library for converting Java objects to JSON called gson gson/ Incidentally if you're wanting to send an Ajax response rather than refreshing the page add ResponseBody to your method declaration and return your JSON string assuming you're not updating your model if this is the case). .. details

    1. public @ResponseBody String home(Locale locale, Model model) { .. }

    Positive Reactions
    1. Ah, if you notice the bottom of my question, this looks like it will break my view handling as it returns the view "main", is it possible to do this JSON response and keep handling my views within the controller?
    Other Reactions
    1. I think BrandonV has answered this.

  31. automatically choose viewResolver based on request url?

    Thx . Use a PathVariable in your handler method use that to toggle which view to use View type could be vm or jsp or whatever. .. details

    1. @RequestMapping("/myapp/{viewtype}/view.do")public String myHandler( @PathVariable String viewtype, Model model) { // do stuff return "viewname." + viewtype
    2. }

  32. Spring MVC returning JSONS and exception Handling

    None .. details

    1. @ResponseBody public Response getUserDetails) { //... return new Response(userDetails)
    2. }

  33. Using Spring and Jackson to Render JSON without affecting all Views

    None .. details

    1. @RequestMapping(value = "/test/data")@ResponseBodypublic TestFormData dostuff() { TestFormData data = new TestFormData()
    2. data.setName("myname")
    3. return data
    4. }

  34. In Spring MVC, how can I set the mime type header when using @ResponseBody

    According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . .. details

    1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
    2. HttpHeaders responseHeaders = new HttpHeaders()
    3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
    4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
    5. }

    Positive Reactions
    1. See if your import is correct and your libraries are updated.
    2. That's the nicest one so far, thanks (+1).
    3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
    4. If I could vote for this multiple times, I would!.
    5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
    6. This works great.
    7. now it works fine if not using ResponseEntity.
    Negative Reactions
    1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
    2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
    Other Reactions
    1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
    2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
    3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

  35. In Spring MVC, how can I set the mime type header when using @ResponseBody

    org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . .. details

    1. package xxx
    2. import java.io.ByteArrayOutputStream
    3. import java.io.IOException
    4. import javax.servlet.http.HttpServletResponse
    5. import org.springframework.web.bind.annotation.RequestMapping
    6. import org.springframework.web.bind.annotation.RequestMethod
    7. @Controllerpublic
    8. class FooBar {
    9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
    10. public void fooBar(HttpServletResponse response) throws IOException {
    11. ByteArrayOutputStream out = new ByteArrayOutputStream()
    12. out.write(myService.getJson().getBytes())
    13. response.setContentType("application/json")
    14. response.setContentLength(out.size())
    15. response.getOutputStream().write(out.toByteArray())
    16. response.getOutputStream().flush()
    17. }
    18. }

    Other Reactions
    1. would he need to write to the response, or just setting the header would do?

  1. componentpublic
      Chart will be rendered here
    1. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  2. examplerepository
      Chart will be rendered here
    1. Configuring Web Service & thin client using Servlet+JSON+MySQL

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RooWebJson(jsonObject = Example.class)
      2. @Controller
      3. @RequestMapping("/example/")
      4. public class ExampleController {
      5. @Resource ExampleRepository exampleRepo
      6. @RequestMapping(method = RequestMethod.PUT, value = "/{name}")
      7. public void putExample(@PathVariable("name") String name) {
      8. exampleRepo.save(new Example(name))
      9. }
      10. }

    2. Configuring Web Service & thin client using Servlet+JSON+MySQL

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example.repositories
      2. import org.springframework.roo.addon.layers.repository.jpa.RooJpaRepository
      3. @RooJpaRepository(domainType = Example.class)
      4. public interface ExampleRepository {}

  3. pathvariable
      Chart will be rendered here
    1. Spring MVC REST Json Conversion exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, @PathVariable String id) { final ResponseEntity<Property> response = new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK)
      2. return response
      3. }

    2. Is it possible to repeat parameter RESTful Spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/test/{tests}", method=RequestMethod.GET)@ResponseBodypublic String test(@PathVariable String tests){ String[] test= tests.split(",")
      2. return "sth"
      3. }

    3. Configuring Web Service & thin client using Servlet+JSON+MySQL

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RooWebJson(jsonObject = Example.class)
      2. @Controller
      3. @RequestMapping("/example/")
      4. public class ExampleController {
      5. @Resource ExampleRepository exampleRepo
      6. @RequestMapping(method = RequestMethod.PUT, value = "/{name}")
      7. public void putExample(@PathVariable("name") String name) {
      8. exampleRepo.save(new Example(name))
      9. }
      10. }

    4. RESTful MySQL / Terminology / Passing Parameters / Returning Ints & Doubles

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/people/gender/{gender}/updated/{lastUpdated}", method = RequestMethod.GET)@ResponseBodypublic Person findByGenderAndUpdated(@PathVariable String gender, @PathVariable String lastUpdated) {}

    5. Java web framework with RESTful JSON services, HTML5 & jQuery ajax

      If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
      2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
      3. } ...}public class Resource{ @JsonProperty("id") private int id
      4. @JsonProperty("resourceName") private String name
      5. ...}

    6. Spring JSON request getting 406 (not Acceptable)

      You're probably fine then sorry I couldn't be more help on this. In the controller shouldn't the response body annotation be on the return type and not the method like so I'd also use the raw jquery.ajax function and make sure contentType and dataType are being set correctly. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){ Weather weather = weatherService.getCurrentWeather(id)
      2. return weather
      3. }

      Other Reactions
      1. The placement of @ResponseBody should not matter...
      2. I will look into GSON...but still would like this JSON to work if possible.

    7. automatically choose viewResolver based on request url?

      Thx . Use a PathVariable in your handler method use that to toggle which view to use View type could be vm or jsp or whatever. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/myapp/{viewtype}/view.do")public String myHandler( @PathVariable String viewtype, Model model) { // do stuff return "viewname." + viewtype
      2. }

    8. ModelAttribute for Restful PUT method not populated value ( JSON )

      Add the below filter to your WebApplicationInitializer class or corresponding xml code to web.xml . Im replace for Link help reference/html/mvc.html#mvc-config-enable reference/html/mvc.html#mvc-config-enable and json-request-body Spring-MVC:-Don't-deserialize-JSON-request-body . details

      Reactions - Positive 2, Negative 0, Others 0

      1. @ModelAttribute("positionGPS") PositionGPS positionGPS, @PathVariable Long id, Model model

      Positive Reactions
      1. You specified you're using Postman, but that obviously isn't going to be your final working solution.
      2. I tested on a cell application and backbone and everything works.
      Other Reactions
      1. You'll have to use either Ajax or a form post.
      2. And did that work?
      3. If it did then I assume you already have Jackson on the classpath for marshaling from JSON to an object.
      4. If you're using a form post this still isn't going to work because that doesn't support a PUT operation cross-browser.

    9. ModelAttribute for Restful PUT method not populated value ( JSON )

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestBody PositionGPS positionGPS, @PathVariable Long id, Model model)

  4. requestparam
      Chart will be rendered here
    1. org.springframework.web.bind.MissingServletRequestParameterException

      If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. Providing a defaultValue implicitly sets required to false so I'll leave it out of the example Hope this helps . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    2. org.springframework.web.bind.MissingServletRequestParameterException

      RequestParam has an attribute required which is true by default. If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    3. 400 Bad request on Spring ajax call

      script Spring Controller . Your saveInvestmentValue method expects a . details

      Reactions - Positive 0, Negative 1, Others 0

      1. @RequestParam("transactionDate")

      Negative Reactions
      1. sorry, the project wasnt clean, it worked after cleaning the project, thanks again.
      Other Reactions
      1. thanks, edited that, but still having error.

    4. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

    5. Providing RESTful JSON API in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

  5. autowired
      Chart will be rendered here
    1. Java web framework with RESTful JSON services, HTML5 & jQuery ajax

      If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
      2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
      3. } ...}public class Resource{ @JsonProperty("id") private int id
      4. @JsonProperty("resourceName") private String name
      5. ...}

  6. locale
      Chart will be rendered here
    1. springmvc using json response

      Then just return your item formattedDate. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
      2. Date date = new Date()
      3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      4. String formattedDate = dateFormat.format(date)
      5. model.addAttribute("serverTime", formattedDate )
      6. return "main"
      7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
      8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      9. return dateFormat.format(date)
      10. }

      Positive Reactions
      1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
      2. Did you resolve your issue?
      3. Nope, I think doing that's just fine.
      Negative Reactions
      1. Ah, sorry about that.
      2. Do you think it's a bad idea to have the controller handle the views?
      3. That seems a bit nasty.
      Other Reactions
      1. Load your view at the root.
      2. also - I don't think that code would even compile with duplicate method names.
      3. Are you suggesting I go to one url for the JSON response and another for the html?
      4. Changed in the example just for future reference.
      5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
      6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
      7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
      8. Is it possible to do both?
      9. I see you marked it as an answer.
      10. Or did you still need help with that?
      11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
      12. I've included jackson-core-asl in my pom.xml.
      13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
      14. Then your view should make an ajax request for the data at /serverTime.
      15. Updated with an example.

    2. springmvc using json response

      I see you marked it as an answer. There's a library for converting Java objects to JSON called gson gson/ Incidentally if you're wanting to send an Ajax response rather than refreshing the page add ResponseBody to your method declaration and return your JSON string assuming you're not updating your model if this is the case). details

      Reactions - Positive 1, Negative 0, Others 0

      1. public @ResponseBody String home(Locale locale, Model model) { .. }

      Positive Reactions
      1. Ah, if you notice the bottom of my question, this looks like it will break my view handling as it returns the view "main", is it possible to do this JSON response and keep handling my views within the controller?
      Other Reactions
      1. I think BrandonV has answered this.

  7. beansexception
      Chart will be rendered here
    1. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  8. servicepublic
      Chart will be rendered here
    1. Right way to write JSON deserializer in Spring or extend it

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Servicepublic
      2. class AnchorService {}

  9. dynamic
      Chart will be rendered here
    1. ModelAttribute for Restful PUT method not populated value ( JSON )

      If you can't use Ajax the only other option is to tunnel everything through POST for create update and delete operations. Add the below filter to your WebApplicationInitializer class or corresponding xml code to web.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. final FilterRegistration.Dynamic httpMethodFilter = servletContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter())
      2. httpMethodFilter.addMappingForUrlPatterns(null, true, "/*")
      3. final FilterRegistration.Dynamic putFormFilter = servletContext.addFilter("httpPutFormContentFilter", new HttpPutFormContentFilter())
      4. putFormFilter.addMappingForUrlPatterns(null, true, "/*")

  10. requestbody
      Chart will be rendered here
    1. JSON to Java Mapping Parametric / Generic types

      As an example JSON doesn't have an equivalent to polymorphic types and yet Jackson is able to handle those through annotations. A solution would be to declare a parametric type and use this as the target of RequestBody this way Note that the MyCustomTypeContainer has to be a parametric type(generic types fully realized). details

      Reactions - Positive 2, Negative 0, Others 0

      1. public class MyCustomTypeContainer extends Container<SubContainerItem> {..}public void updateContainer(@RequestBody MyCustomTypeContainer container) { realService.updateContainer(container)
      2. }

      Positive Reactions
      1. Yes true Josh, actually your approach does sound good also.
      2. One change that I can think of is not having the class name in xml, that does not look clean, instead you an try put this information in a custom annotation and use that annotation along with a [HandlerMethodArgumentResolver]( URL_http://docs.spring.io/spring/docs/3.2.x /javadoc- api/org/springframework/web/method/support/HandlerMethodArgumentResolver.html) to create the appropriate JavaType and do the unmarshalling there.
      Other Reactions
      1. Hi Biju, this solution would work if I want to only updateContainer with one concrete type of sub container (SubContainerItem) - but what if I also want to be able to update a container full of SubContainerItem2?

    2. Parsing JSON in Spring MVC using Jackson JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("somepath")@ResponseBodypublic Fozzle doSomeThing(@RequestBody Fizzle input){ return new Fozzle(input)
      2. }

    3. How to validate request parameter if it is not a bean in spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/some/path", method = RequestMethod.POST)@ResponseBodypublic Foo bar(@Valid @RequestBody LongList listOfLongs) { // do some useful work}

    4. Spring MVC REST Json Conversion exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, @PathVariable String id) { final ResponseEntity<Property> response = new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK)
      2. return response
      3. }

    5. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

    6. Parsing json into java objects in spring-mvc

      Thanks!. if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody SearchRequest json) {

    7. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller
      2. @RequestMapping("/test")
      3. public class TestController {
      4. @RequestMapping(method = RequestMethod.POST, value = "math")
      5. @ResponseBody
      6. public Result math(@RequestBody final Request request) {
      7. final Result result = new Result()
      8. result.setAddition(request.getLeft() + request.getRight())
      9. result.setSubtraction(request.getLeft() - request.getRight())
      10. result.setMultiplication(request.getLeft() * request.getRight())
      11. return result
      12. }
      13. }

    8. Marshaling JSON and Generics in Java with Spring MVC

      Your solution worked for me D tnx. I ended up creating another class So in the controller instead of i did this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String setJobStatus(@RequestBody List<JobUpdate> jobUpdates) {

    9. Interfaces and @RequestBody

      Sure thing my apologies!. I'm not sure it would work but you can try to make it generic . details

      Reactions - Positive 3, Negative 0, Others 0

      1. public interface BookableResourceController<R extends BookableResource> {
      2. @RequestMapping(value = "/delete.html", method = RequestMethod.POST)
      3. public ModelAndView processDeleteResource(@RequestBody R resource)
      4. }

      Positive Reactions
      1. I'm not too well versed in generics, so I never would have thought of this.
      2. Thank you for the quick response!.
      3. That worked beautifully!

    10. Spring 3.0 making JSON response using jackson message converter

      Thx I have tried that before it isnt. In addition to the answers here if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody Foo json) {

    11. Spring REST multiple @RequestBody parameters, possible?

      I'm pretty sure that won't work. There may be a workaround but the much easier way would be to introduce a wrapper Object and change your signature . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public class PersonContext{ private UserContext userContext
      2. private Person person
      3. // getters and setters}public Person createPerson(@RequestBody PersonContext personContext)

      Positive Reactions
      1. Thanks, I'm considering a wrapper Array as the last resort.
      Other Reactions
      1. What is the work around you were referring to?
      2. @Srirangan I said there may be a workaround.
      3. @Srirangan: the workarround is the PersonContext class - it is some kind of DTO.
      4. I am not aware of one myself.

    12. Spring MVC: Don't deserialize JSON request body

      I'm guessing your body is not simply a String but some full JSON object. If you have a java model of the JSON object you are expecting then you could replace the String parameter with that in your doSomething declaration such as If you don't have a Java object that matches the JSON then you could try to get it working by replacing the String type with a Map<String Object and see if that gets you closer to a working solution. details

      Reactions - Positive 5, Negative 5, Others 0

      1. public void doSomething(@RequestBody MyObject myobj) {

      Positive Reactions
      1. I'd be interested in how Bart's solution would work.
      2. As a workaround you could simply define a simple class that exposes a string value.
      3. Don't use @RequestBody, and send the json value as a regular request param in a form.
      4. It does work!
      5. That looks like it should work perfectly, thanks @digitaljoel.
      Negative Reactions
      1. Never mind, that was my own fault, actually.
      2. Sorry about that.
      3. It throws this exception: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of javax.servlet.http.HttpServletRequest, problem: abstract types can only be instantiated with additional type information.
      4. To make matters more complex, the application only accepts Content-Type values of application/json so even if every client could send this particular request as plaintext it would be rejected by the application (I can't change this).
      5. Sorry to double comment, but I can't edit my above comment.
      Other Reactions
      1. I enabled debug logging in Spring and came up with this exception: org.codehaus.jackson.map.JsonMappingException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_ARRAY token - so how would I skip the deserializing part and just retrieve the JSON data as a string?
      2. I normally would map it to a Java object but I need to modify the raw JSON before I create the object, hence why I need the raw JSON string.
      3. I don't know how Jackson would map it appropriately.
      4. I updated my answer with a new possible solution.
      5. If you want it as a string then you should send it as a String.
      6. I'm unaccepting this answer as it doesn't seem to work, actually.
      7. This is for a REST API interfacing with middleware, the middleware will be directly calling the routes with the JSON as the body of the request.
      8. Just because the String contains JSON content doesn't mean you need to tell Spring MVC that.
      9. e.g.
      10. You're right - the body is a full JSON object.
      11. class JsonValue { getValue(); }.

    13. Binding the nested json to @RequestBody object using Jackson converter

      The issue was fixed by adding below logic. Here your Java class DrugListJsonRequest should extend It doesn't require a any methods and constructors. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String saveDrug(@RequestBody DrugListJsonRequest drugListCriterion) {}

    14. Spring 3.1, JSON response ModelAndView

      Your server would like to serialize the ModelAndView Object as a JSON string and your jQuery code wants to append an HTML element to the DOM. There are a few things which could be wrong here By specifying a Content-type header of application/json you are expecting a response of json back however looking at the way you are handling the response it looks like what you want is an html if it is html that you are looking for as a response then remove the Content Type header from the request remove the ResponseBody annotation from ModelAndView response instead just return a view which points to a normal jsp which can create the html response that you are expecting . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")public ModelAndView addSubMenu(@RequestBody Menu menu) {...}

      Other Reactions
      1. This would be my understanding of a partial.
      2. Then you would need to tell JQuery to expect HTML or Text but not JSON.
      3. This would deliver HTML Code (Model delivered form controller, view delivered from Template) to the client.

    15. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public String sync(@RequestBody Foo json) {

    16. Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

    17. Marshaling JSON and Generics in Java with Spring MVC

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String setJobStatus(@RequestBody JobUpdateList jobUpdates) {

    18. Jackson : Converting JSON property to nested Object with Dot Notation

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/saveChild.json")@ResponseBodypublic Child saveChild(@RequestBody Child child) { // do something with child return child
      2. }

    19. ModelAttribute for Restful PUT method not populated value ( JSON )

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestBody PositionGPS positionGPS, @PathVariable Long id, Model model)

  11. requestmethod
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

    2. Redirect at @ResponseBody?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/postLogout.html", method=RequestMethod.GET)@ResponseBody public MyreturnObject getPostLogout(){ return new ReturnObject(true,true,false)
      2. }

    3. Configuring Web Service & thin client using Servlet+JSON+MySQL

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RooWebJson(jsonObject = Example.class)
      2. @Controller
      3. @RequestMapping("/example/")
      4. public class ExampleController {
      5. @Resource ExampleRepository exampleRepo
      6. @RequestMapping(method = RequestMethod.PUT, value = "/{name}")
      7. public void putExample(@PathVariable("name") String name) {
      8. exampleRepo.save(new Example(name))
      9. }
      10. }

    4. Spring REST with both JSON and XML

      I'm doing this in a current project without using a ContentNegotiatingViewResolver. For one method in my controller I can receive the following output based on the Accept request header. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @RequestMapping(value = "/test", method = RequestMethod.GET)@ResponseBodypublic HttpEntity<BasicResponse> getBasicResponse() { return new HttpEntity<BasicResponse>(new BasicResponse())
      2. }

      Negative Reactions
      1. Thanks for your answer, but I wasn't clear enough in my question.
      2. I too get valid xml & json, but a pretty xml api becomes an ugly json api and the other way around.
      Other Reactions
      1. I think @chrylis was spot on.

    5. Providing RESTful JSON API in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

    6. Spring 3.2 Web MVC @ModelAttribute without label

      It seems that you use jQuery datatables so you should add ResponseBody to the method . . details

      Reactions - Positive 2, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.GET)@ResponseBody public DTResponse agents() { DTResponse resp = new DTResponse()
      2. resp.setsEcho(1)
      3. resp.setiTotalDisplayRecords(10)
      4. resp.setiTotalRecords(50)
      5. return resp
      6. }}

      Positive Reactions
      1. Thanks :).
      2. Works like a charm.

    7. JSON character encoding

      I dont know if this is relevant anymore but I fixed it with the RequestMapping annotation. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, produces={"application/json
      2. charset=UTF-8"})

    8. In Spring MVC, how can I set the mime type header when using @ResponseBody

      According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

      Reactions - Positive 7, Negative 2, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
      2. HttpHeaders responseHeaders = new HttpHeaders()
      3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
      4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
      5. }

      Positive Reactions
      1. See if your import is correct and your libraries are updated.
      2. That's the nicest one so far, thanks (+1).
      3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
      4. If I could vote for this multiple times, I would!.
      5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
      6. This works great.
      7. now it works fine if not using ResponseEntity.
      Negative Reactions
      1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
      2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
      Other Reactions
      1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
      2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
      3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

    9. Spring MVC + JSON = 406 Not Acceptable

      Thank you very much with your antecedent post I've finally managed to get it working. You have to register the annotation binding for Jackson in your spring-mvc config.xml for example Then in your controller you can use . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")@ResponseBody

    10. Spring 3.0 making JSON response using jackson message converter

      3. Use as the following This works for me. details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })public @ResponseBody Foo method(@Valid Request request, BindingResult result){return new Foo(3,4)}

      Positive Reactions
      1. @ResponseBody is applied to return type - this was my issue, thanks!.
      Other Reactions
      1. Providing that, as you suggest, is important.
      2. The key part here, I think, is that the OP doesn't have a RequestMapping.
      3. For testing your post requests with Curl or upgrading to spring 3.2 checkout [here]( URL_http://stackoverflow.com/questions/16909742/spring-3-2-0-web-mvc-rest - api-and-json2-post-requests-how-to-get-it-right-onc).
      4. @GaryF updated my answer.

    11. Sending list in JSON request

      Define below bean return jsonView from the controller. Controller Change in ajax viewsResolver config in mvc-servlet.xml . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import org.springframework.ui.ModelMap
      2. @RequestMapping(value = "/testURL.do", method = RequestMethod.POST)public String executeTest(ModelMap model, ListData listData) { ModelAndView modelAndView = null
      3. JsonResponse jsonResponse = null
      4. modelAndView = executeTransaction(listData)
      5. model.addAttribute("paramName", modelAndView)
      6. } return "jsonView"
      7. }

      Positive Reactions
      1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
      2. Thanks a lot Boss!.
      3. Thanks but we are not using Gson.
      4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
      Other Reactions
      1. Point Number 2 is not related to gson, it is spring.
      2. I update the answer with all changes required.
      3. Or I need to do additional processing in controller?
      4. We are using Jackson.

    12. Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

    13. In Spring MVC, how can I set the mime type header when using @ResponseBody

      Register org.springframework.http.converter.json.MappingJacksonHttpMessageConverter as the message converter and return the object directly from the method. and the controller . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public @ResponseBody Object fooBar(){ return myService.getActualObject()
      2. }

      Positive Reactions
      1. Yes, probably a best practice, but as I wrote my objects are already JSON strings and I just want to write them out with the correct mime type.
      Other Reactions
      1. org/springframework/spring-webmvc should cover it.
      2. What are the maven dependencies for the beans you are referencing?

    14. How to send Json response in spring?

      Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go Just a little summary As you know you will need the Jackson library in the class path so that Objects can be converted to JSON. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/getfees", method = RequestMethod.POST)public @ResponseBodyDomainFeesResponse getFees( @RequestHeader(value = "userName") String userName, @RequestHeader(value = "password") String password, @RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) { return domainFeesHelper.executeRetreiveFees(userName, password, syncDate)
      2. }

    15. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})

    16. Is it possible to repeat parameter RESTful Spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/test/{tests}", method=RequestMethod.GET)@ResponseBodypublic String test(@PathVariable String tests){ String[] test= tests.split(",")
      2. return "sth"
      3. }

    17. springmvc using json response

      Then just return your item formattedDate. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
      2. Date date = new Date()
      3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      4. String formattedDate = dateFormat.format(date)
      5. model.addAttribute("serverTime", formattedDate )
      6. return "main"
      7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
      8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      9. return dateFormat.format(date)
      10. }

      Positive Reactions
      1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
      2. Did you resolve your issue?
      3. Nope, I think doing that's just fine.
      Negative Reactions
      1. Ah, sorry about that.
      2. Do you think it's a bad idea to have the controller handle the views?
      3. That seems a bit nasty.
      Other Reactions
      1. Load your view at the root.
      2. also - I don't think that code would even compile with duplicate method names.
      3. Are you suggesting I go to one url for the JSON response and another for the html?
      4. Changed in the example just for future reference.
      5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
      6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
      7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
      8. Is it possible to do both?
      9. I see you marked it as an answer.
      10. Or did you still need help with that?
      11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
      12. I've included jackson-core-asl in my pom.xml.
      13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
      14. Then your view should make an ajax request for the data at /serverTime.
      15. Updated with an example.

    18. In Spring MVC, how can I set the mime type header when using @ResponseBody

      I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1 the implementation looks quite neat Comments First the mvc:annotation-driven or the EnableWebMvc must be reference/html/mvc.html#mvc-config-enable added to your application config. details

      Reactions - Positive 3, Negative 0, Others 0

      1. @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar")@ResponseBodypublic Bar fooBar(){ return myService.getBar()
      2. }

      Positive Reactions
      1. Thanks!.
      2. This answer should be number one, let Spring do the work for you!
      3. Worked great.
      Other Reactions
      1. !.

    19. Spring 3.1, JSON response ModelAndView

      Then you would need to tell JQuery to expect HTML or Text but not JSON. If what you want is json to update some parts of the page don't return a ModelAndView return String make sure to have a json serializer . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html") public @ResponseBody String addSubMenu() { //yourvariable return yourvariable.toString()
      2. }

      Positive Reactions
      1. True, it will return a String, if an object is needed, replace String with your object and you can serialize it using jackson library for example.
      Other Reactions
      1. If you want to deliver some browser renderable code, I would delegate the view rendering to the View layer using ModelAndView (without the ReponseBody Annotation) as result.
      2. If you want to return an object, consider returning an Object and let Spring marshal it to JSON.
      3. This would deliver what ever you have in yourvariable.

    20. Interfaces and @RequestBody

      Sure thing my apologies!. I'm not sure it would work but you can try to make it generic . details

      Reactions - Positive 3, Negative 0, Others 0

      1. public interface BookableResourceController<R extends BookableResource> {
      2. @RequestMapping(value = "/delete.html", method = RequestMethod.POST)
      3. public ModelAndView processDeleteResource(@RequestBody R resource)
      4. }

      Positive Reactions
      1. I'm not too well versed in generics, so I never would have thought of this.
      2. Thank you for the quick response!.
      3. That worked beautifully!

    21. Java web framework with RESTful JSON services, HTML5 & jQuery ajax

      If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
      2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
      3. } ...}public class Resource{ @JsonProperty("id") private int id
      4. @JsonProperty("resourceName") private String name
      5. ...}

    22. Spring JSON request getting 406 (not Acceptable)

      You're probably fine then sorry I couldn't be more help on this. In the controller shouldn't the response body annotation be on the return type and not the method like so I'd also use the raw jquery.ajax function and make sure contentType and dataType are being set correctly. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){ Weather weather = weatherService.getCurrentWeather(id)
      2. return weather
      3. }

      Other Reactions
      1. The placement of @ResponseBody should not matter...
      2. I will look into GSON...but still would like this JSON to work if possible.

    23. org.springframework.web.bind.MissingServletRequestParameterException

      If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. Providing a defaultValue implicitly sets required to false so I'll leave it out of the example Hope this helps . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    24. org.springframework.web.bind.MissingServletRequestParameterException

      RequestParam has an attribute required which is true by default. If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    25. How to validate request parameter if it is not a bean in spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/some/path", method = RequestMethod.POST)@ResponseBodypublic Foo bar(@Valid @RequestBody LongList listOfLongs) { // do some useful work}

    26. In Spring MVC, how can I set the mime type header when using @ResponseBody

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public View fooBar(){ return new JsonView(myService.getJson())
      2. }

    27. RESTful MySQL / Terminology / Passing Parameters / Returning Ints & Doubles

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/people/gender/{gender}/updated/{lastUpdated}", method = RequestMethod.GET)@ResponseBodypublic Person findByGenderAndUpdated(@PathVariable String gender, @PathVariable String lastUpdated) {}

    28. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller
      2. @RequestMapping("/test")
      3. public class TestController {
      4. @RequestMapping(method = RequestMethod.POST, value = "math")
      5. @ResponseBody
      6. public Result math(@RequestBody final Request request) {
      7. final Result result = new Result()
      8. result.setAddition(request.getLeft() + request.getRight())
      9. result.setSubtraction(request.getLeft() - request.getRight())
      10. result.setMultiplication(request.getLeft() * request.getRight())
      11. return result
      12. }
      13. }

    29. Spring 3.1, JSON response ModelAndView

      Your server would like to serialize the ModelAndView Object as a JSON string and your jQuery code wants to append an HTML element to the DOM. There are a few things which could be wrong here By specifying a Content-type header of application/json you are expecting a response of json back however looking at the way you are handling the response it looks like what you want is an html if it is html that you are looking for as a response then remove the Content Type header from the request remove the ResponseBody annotation from ModelAndView response instead just return a view which points to a normal jsp which can create the html response that you are expecting . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")public ModelAndView addSubMenu(@RequestBody Menu menu) {...}

      Other Reactions
      1. This would be my understanding of a partial.
      2. Then you would need to tell JQuery to expect HTML or Text but not JSON.
      3. This would deliver HTML Code (Model delivered form controller, view delivered from Template) to the client.

    30. Spring JSON request getting 406 (not Acceptable)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)

  12. responsebodypublic
      Chart will be rendered here
    1. org.springframework.web.bind.MissingServletRequestParameterException

      If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. Providing a defaultValue implicitly sets required to false so I'll leave it out of the example Hope this helps . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    2. org.springframework.web.bind.MissingServletRequestParameterException

      RequestParam has an attribute required which is true by default. If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    3. How to validate request parameter if it is not a bean in spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/some/path", method = RequestMethod.POST)@ResponseBodypublic Foo bar(@Valid @RequestBody LongList listOfLongs) { // do some useful work}

    4. Is it possible to repeat parameter RESTful Spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/test/{tests}", method=RequestMethod.GET)@ResponseBodypublic String test(@PathVariable String tests){ String[] test= tests.split(",")
      2. return "sth"
      3. }

    5. In Spring MVC, how can I set the mime type header when using @ResponseBody

      I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1 the implementation looks quite neat Comments First the mvc:annotation-driven or the EnableWebMvc must be reference/html/mvc.html#mvc-config-enable added to your application config. details

      Reactions - Positive 3, Negative 0, Others 0

      1. @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar")@ResponseBodypublic Bar fooBar(){ return myService.getBar()
      2. }

      Positive Reactions
      1. Thanks!.
      2. This answer should be number one, let Spring do the work for you!
      3. Worked great.
      Other Reactions
      1. !.

    6. Using Spring and Jackson to Render JSON without affecting all Views

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/test/data")@ResponseBodypublic TestFormData dostuff() { TestFormData data = new TestFormData()
      2. data.setName("myname")
      3. return data
      4. }

    7. Spring REST with both JSON and XML

      I'm doing this in a current project without using a ContentNegotiatingViewResolver. For one method in my controller I can receive the following output based on the Accept request header. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @RequestMapping(value = "/test", method = RequestMethod.GET)@ResponseBodypublic HttpEntity<BasicResponse> getBasicResponse() { return new HttpEntity<BasicResponse>(new BasicResponse())
      2. }

      Negative Reactions
      1. Thanks for your answer, but I wasn't clear enough in my question.
      2. I too get valid xml & json, but a pretty xml api becomes an ugly json api and the other way around.
      Other Reactions
      1. I think @chrylis was spot on.

    8. Parsing JSON in Spring MVC using Jackson JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("somepath")@ResponseBodypublic Fozzle doSomeThing(@RequestBody Fizzle input){ return new Fozzle(input)
      2. }

    9. RESTful MySQL / Terminology / Passing Parameters / Returning Ints & Doubles

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/people/gender/{gender}/updated/{lastUpdated}", method = RequestMethod.GET)@ResponseBodypublic Person findByGenderAndUpdated(@PathVariable String gender, @PathVariable String lastUpdated) {}

    10. Jackson : Converting JSON property to nested Object with Dot Notation

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/saveChild.json")@ResponseBodypublic Child saveChild(@RequestBody Child child) { // do something with child return child
      2. }

  13. responseentity
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

      Reactions - Positive 7, Negative 2, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
      2. HttpHeaders responseHeaders = new HttpHeaders()
      3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
      4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
      5. }

      Positive Reactions
      1. See if your import is correct and your libraries are updated.
      2. That's the nicest one so far, thanks (+1).
      3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
      4. If I could vote for this multiple times, I would!.
      5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
      6. This works great.
      7. now it works fine if not using ResponseEntity.
      Negative Reactions
      1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
      2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
      Other Reactions
      1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
      2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
      3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

    2. Spring MVC REST Json Conversion exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, @PathVariable String id) { final ResponseEntity<Property> response = new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK)
      2. return response
      3. }

  14. bytearrayoutputstream
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

  15. controllerpublic
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

    2. spring generic json response

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controllerpublic
      2. class MyController {
      3. @RequestMapping(value = "/mypath", produces = "application/json")
      4. public Response<SomeObject> myPathMethod() {
      5. return new Response<SomeObject>("200", "success!", new SomeObject())
      6. }
      7. }

  16. pagerequest
      Chart will be rendered here
    1. JSONMappingException - cannot desierialize Java object

      Your best bet would be to write a custom bean to deserialize the JSON into then instantiate a PageImpl with the values from this custom bean. I ended up using something like this creating a bean as Perception suggested and then modify your code to use the concrete class and get the PageImpl . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.springframework.data.domain.PageImpl
      4. import org.springframework.data.domain.PageRequest
      5. import org.springframework.data.domain.Sort
      6. public class PageImplBean<T> extends PageImpl<T> {
      7. private static final long serialVersionUID = 1L
      8. private int number
      9. private int size
      10. private int totalPages
      11. private int numberOfElements
      12. private long totalElements
      13. private boolean previousPage
      14. private boolean firstPage
      15. private boolean nextPage
      16. private boolean lastPage
      17. private List<T> content
      18. private Sort sort
      19. public PageImplBean() {
      20. super(new ArrayList<T>())
      21. }
      22. public int getNumber() {
      23. return number
      24. }
      25. public void setNumber(int number) {
      26. this.number = number
      27. }
      28. public int getSize() {
      29. return size
      30. }
      31. public void setSize(int size) {
      32. this.size = size
      33. }
      34. public int getTotalPages() {
      35. return totalPages
      36. }
      37. public void setTotalPages(int totalPages) {
      38. this.totalPages = totalPages
      39. }
      40. public int getNumberOfElements() {
      41. return numberOfElements
      42. }
      43. public void setNumberOfElements(int numberOfElements) {
      44. this.numberOfElements = numberOfElements
      45. }
      46. public long getTotalElements() {
      47. return totalElements
      48. }
      49. public void setTotalElements(long totalElements) {
      50. this.totalElements = totalElements
      51. }
      52. public boolean isPreviousPage() {
      53. return previousPage
      54. }
      55. public void setPreviousPage(boolean previousPage) {
      56. this.previousPage = previousPage
      57. }
      58. public boolean isFirstPage() {
      59. return firstPage
      60. }
      61. public void setFirstPage(boolean firstPage) {
      62. this.firstPage = firstPage
      63. }
      64. public boolean isNextPage() {
      65. return nextPage
      66. }
      67. public void setNextPage(boolean nextPage) {
      68. this.nextPage = nextPage
      69. }
      70. public boolean isLastPage() {
      71. return lastPage
      72. }
      73. public void setLastPage(boolean lastPage) {
      74. this.lastPage = lastPage
      75. }
      76. public List<T> getContent() {
      77. return content
      78. }
      79. public void setContent(List<T> content) {
      80. this.content = content
      81. }
      82. public Sort getSort() {
      83. return sort
      84. }
      85. public void setSort(Sort sort) {
      86. this.sort = sort
      87. }
      88. public PageImpl<T> pageImpl() {
      89. return new PageImpl<T>(
      90. getContent(), new PageRequest(getNumber(), getSize(), getSort()), getTotalElements())
      91. }
      92. }

  17. mappingjacksonjsonview
      Chart will be rendered here
    1. java spring MappingJacksonJsonView not doing toString on mongodb ObjectId

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Bean(name = "jsonView")public MappingJacksonJsonView jsonView() { final MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView()
      2. mappingJacksonJsonView.setContentType("application/json")
      3. mappingJacksonJsonView.setObjectMapper(new CustomObjectMapper())
      4. return mappingJacksonJsonView
      5. }

  18. userresponse
      Chart will be rendered here
    1. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

  19. httpservletresponse
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

  20. httpheaders
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

      Reactions - Positive 7, Negative 2, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
      2. HttpHeaders responseHeaders = new HttpHeaders()
      3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
      4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
      5. }

      Positive Reactions
      1. See if your import is correct and your libraries are updated.
      2. That's the nicest one so far, thanks (+1).
      3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
      4. If I could vote for this multiple times, I would!.
      5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
      6. This works great.
      7. now it works fine if not using ResponseEntity.
      Negative Reactions
      1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
      2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
      Other Reactions
      1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
      2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
      3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

  21. modelmap
      Chart will be rendered here
    1. Sending list in JSON request

      Define below bean return jsonView from the controller. Controller Change in ajax viewsResolver config in mvc-servlet.xml . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import org.springframework.ui.ModelMap
      2. @RequestMapping(value = "/testURL.do", method = RequestMethod.POST)public String executeTest(ModelMap model, ListData listData) { ModelAndView modelAndView = null
      3. JsonResponse jsonResponse = null
      4. modelAndView = executeTransaction(listData)
      5. model.addAttribute("paramName", modelAndView)
      6. } return "jsonView"
      7. }

      Positive Reactions
      1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
      2. Thanks a lot Boss!.
      3. Thanks but we are not using Gson.
      4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
      Other Reactions
      1. Point Number 2 is not related to gson, it is spring.
      2. I update the answer with all changes required.
      3. Or I need to do additional processing in controller?
      4. We are using Jackson.

    2. Generate JSON in JAVA

      put each row contents in a map . Essentially you want something like this This might need to be adjusted to meet your needs but it should at least show you how to do it. details

      Reactions - Positive 0, Negative 0, Others 0

      1. ModelMap [] rowMap = new ModelMap()[3]
      2. for (int i=0
      3. i<3
      4. i++){ ModelMap this_row=new ModelMap()
      5. this_row.put("id",i)
      6. this_row.put("name","name"+i)
      7. rowMap(i)=this_row
      8. }modelMap.put("rows",rowMap)

      Other Reactions
      1. I have an error in your first line The type of the expression must be an array type but it resolved to ModelMap.

    3. Spring MVC returning JSONS and exception Handling

      Return a model and a view instead. To add the exception you'd do it the same way with a key and success false. details

      Reactions - Positive 3, Negative 1, Others 0

      1. public ModelMap getUserDetails() { UserDetails userDetails
      2. // get this object from somewhere ModelMap map = new ModelMap()(
      3. map.addAttribute("data", userDetails)
      4. map.addAttribute("success", true)
      5. return map
      6. }

      Positive Reactions
      1. Brain fart from returning views as well.
      2. I don't see what value ModelAndView adds here.
      3. I am unsure of why I would want to use a ModelAndView however you gave me the idea of using a map (HashMap) which worked like a charm and gave me the desired output.
      Negative Reactions
      1. However how do I do the same in a fail scenario?
      Other Reactions
      1. Why not just return the ModelMap?
      2. @milindaD ModelMap doesn't require keys but not much different.
      3. @skaffman You're right.
      4. However any idea of a way to centralize this when for all controllers and all functions in the controllers?
      5. It implements Map.

  22. requestmapping
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      Register org.springframework.http.converter.json.MappingJacksonHttpMessageConverter as the message converter and return the object directly from the method. and the controller . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public @ResponseBody Object fooBar(){ return myService.getActualObject()
      2. }

      Positive Reactions
      1. Yes, probably a best practice, but as I wrote my objects are already JSON strings and I just want to write them out with the correct mime type.
      Other Reactions
      1. org/springframework/spring-webmvc should cover it.
      2. What are the maven dependencies for the beans you are referencing?

    2. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

    3. Redirect at @ResponseBody?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/postLogout.html", method=RequestMethod.GET)@ResponseBody public MyreturnObject getPostLogout(){ return new ReturnObject(true,true,false)
      2. }

    4. Configuring Web Service & thin client using Servlet+JSON+MySQL

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RooWebJson(jsonObject = Example.class)
      2. @Controller
      3. @RequestMapping("/example/")
      4. public class ExampleController {
      5. @Resource ExampleRepository exampleRepo
      6. @RequestMapping(method = RequestMethod.PUT, value = "/{name}")
      7. public void putExample(@PathVariable("name") String name) {
      8. exampleRepo.save(new Example(name))
      9. }
      10. }

    5. Spring REST with both JSON and XML

      I'm doing this in a current project without using a ContentNegotiatingViewResolver. For one method in my controller I can receive the following output based on the Accept request header. details

      Reactions - Positive 0, Negative 2, Others 0

      1. @RequestMapping(value = "/test", method = RequestMethod.GET)@ResponseBodypublic HttpEntity<BasicResponse> getBasicResponse() { return new HttpEntity<BasicResponse>(new BasicResponse())
      2. }

      Negative Reactions
      1. Thanks for your answer, but I wasn't clear enough in my question.
      2. I too get valid xml & json, but a pretty xml api becomes an ugly json api and the other way around.
      Other Reactions
      1. I think @chrylis was spot on.

    6. Providing RESTful JSON API in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

    7. Spring 3.2 Web MVC @ModelAttribute without label

      It seems that you use jQuery datatables so you should add ResponseBody to the method . . details

      Reactions - Positive 2, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.GET)@ResponseBody public DTResponse agents() { DTResponse resp = new DTResponse()
      2. resp.setsEcho(1)
      3. resp.setiTotalDisplayRecords(10)
      4. resp.setiTotalRecords(50)
      5. return resp
      6. }}

      Positive Reactions
      1. Thanks :).
      2. Works like a charm.

    8. JSON character encoding

      I dont know if this is relevant anymore but I fixed it with the RequestMapping annotation. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, produces={"application/json
      2. charset=UTF-8"})

    9. Some information about how Spring MVC recive and use the Accept Header in these two case

      Your method is matching on any URI pattern that ends in json and in both cases your URL ends in json. If you want to filter on things that have an Accept header of JSON then I think you want to do something like this Please understand I typed the above from memory so you may need to tweak it a tad. details

      Reactions - Positive 2, Negative 0, Others 0

      1. @RequestMapping(value="/someUriPattern", headers = {"Accept=application/json"})

      Positive Reactions
      1. Ok,thank you very muchSo, are you sayng to me that if I would that my controller method manage only JSON object coming from my view I have to put the element "Accept=application/json" inside my RequestMapping annotation?
      2. What I am saying is that, if you want to limit calls to that method to only things that are requesting JSON, its probably a good idea to add the proper header (again, I typed that off of memory...please google to verify I didn't typo).

    10. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/run/*")

    11. Sending JSON to Spring MVC controller

      However in your Controller class you do not have any method bound to this URL. Because you've annotated the class with and the method is annotated with the method is actually bound to the URL run/save which is neither the URL you are sending data to with nor the URL the form is pointing at. details

      Reactions - Positive 0, Negative 1, Others 0

      1. @RequestMapping("save")

      Negative Reactions
      1. sorry, it should be run/save but still same problem.
      Other Reactions
      1. Did you take my suggestion to turn up logging to examine exactly which methods are bound to exactly which URLs?
      2. matt b...bulls eye..i have also suggested the same answer...
      3. I don't think you need the in the @RequestMapping(/application/*).

    12. spring generic json response

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controllerpublic
      2. class MyController {
      3. @RequestMapping(value = "/mypath", produces = "application/json")
      4. public Response<SomeObject> myPathMethod() {
      5. return new Response<SomeObject>("200", "success!", new SomeObject())
      6. }
      7. }

    13. Jackson : Converting JSON property to nested Object with Dot Notation

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/saveChild.json")@ResponseBodypublic Child saveChild(@RequestBody Child child) { // do something with child return child
      2. }

    14. Using Spring and Jackson to Render JSON without affecting all Views

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/test/data")@ResponseBodypublic TestFormData dostuff() { TestFormData data = new TestFormData()
      2. data.setName("myname")
      3. return data
      4. }

    15. automatically choose viewResolver based on request url?

      Thx . Use a PathVariable in your handler method use that to toggle which view to use View type could be vm or jsp or whatever. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/myapp/{viewtype}/view.do")public String myHandler( @PathVariable String viewtype, Model model) { // do stuff return "viewname." + viewtype
      2. }

    16. Is it possible to repeat parameter RESTful Spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/test/{tests}", method=RequestMethod.GET)@ResponseBodypublic String test(@PathVariable String tests){ String[] test= tests.split(",")
      2. return "sth"
      3. }

    17. In Spring MVC, how can I set the mime type header when using @ResponseBody

      According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

      Reactions - Positive 7, Negative 2, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
      2. HttpHeaders responseHeaders = new HttpHeaders()
      3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
      4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
      5. }

      Positive Reactions
      1. See if your import is correct and your libraries are updated.
      2. That's the nicest one so far, thanks (+1).
      3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
      4. If I could vote for this multiple times, I would!.
      5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
      6. This works great.
      7. now it works fine if not using ResponseEntity.
      Negative Reactions
      1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
      2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
      Other Reactions
      1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
      2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
      3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

    18. Spring MVC + JSON = 406 Not Acceptable

      Thank you very much with your antecedent post I've finally managed to get it working. You have to register the annotation binding for Jackson in your spring-mvc config.xml for example Then in your controller you can use . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")@ResponseBody

    19. Spring 3.0 making JSON response using jackson message converter

      3. Use as the following This works for me. details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })public @ResponseBody Foo method(@Valid Request request, BindingResult result){return new Foo(3,4)}

      Positive Reactions
      1. @ResponseBody is applied to return type - this was my issue, thanks!.
      Other Reactions
      1. Providing that, as you suggest, is important.
      2. The key part here, I think, is that the OP doesn't have a RequestMapping.
      3. For testing your post requests with Curl or upgrading to spring 3.2 checkout [here]( URL_http://stackoverflow.com/questions/16909742/spring-3-2-0-web-mvc-rest - api-and-json2-post-requests-how-to-get-it-right-onc).
      4. @GaryF updated my answer.

    20. Spring MVC AJAX and JSON using Custom View Resolver, and Custom View

      I'm not sure the path of my form submission and there obviously is no JSP view for it I'm expecting JSON to be returned actually but for some reason this isn't working it's just trying to forward me to some JSP so I'm guessing that I need to specify how to handle this in my XML but I've seen about 1000 different ways that people return JSON and all of them are very confusing to me I'm just looking for the simplest way so I can take it from there edit I added an answer which is a good start but it allows you to type json after any URL and it will do some really bad things if as the controller I'm not expecting it so I need to somehow have this view resolver only apply to secured URLs . Ok finally after trying a million combinations and then this I don't really understand how I can return an object from here. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/test/data") public TestFormData dostuff() { TestFormData data = new TestFormData()
      2. data.setName("myname")
      3. return data
      4. }

    21. Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

    22. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/run/")

    23. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/run/*")

    24. How to send Json response in spring?

      Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go Just a little summary As you know you will need the Jackson library in the class path so that Objects can be converted to JSON. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/getfees", method = RequestMethod.POST)public @ResponseBodyDomainFeesResponse getFees( @RequestHeader(value = "userName") String userName, @RequestHeader(value = "password") String password, @RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) { return domainFeesHelper.executeRetreiveFees(userName, password, syncDate)
      2. }

    25. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})

    26. Parsing json into java objects in spring-mvc

      Thanks!. if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody SearchRequest json) {

    27. springmvc using json response

      Then just return your item formattedDate. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
      2. Date date = new Date()
      3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      4. String formattedDate = dateFormat.format(date)
      5. model.addAttribute("serverTime", formattedDate )
      6. return "main"
      7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
      8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      9. return dateFormat.format(date)
      10. }

      Positive Reactions
      1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
      2. Did you resolve your issue?
      3. Nope, I think doing that's just fine.
      Negative Reactions
      1. Ah, sorry about that.
      2. Do you think it's a bad idea to have the controller handle the views?
      3. That seems a bit nasty.
      Other Reactions
      1. Load your view at the root.
      2. also - I don't think that code would even compile with duplicate method names.
      3. Are you suggesting I go to one url for the JSON response and another for the html?
      4. Changed in the example just for future reference.
      5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
      6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
      7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
      8. Is it possible to do both?
      9. I see you marked it as an answer.
      10. Or did you still need help with that?
      11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
      12. I've included jackson-core-asl in my pom.xml.
      13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
      14. Then your view should make an ajax request for the data at /serverTime.
      15. Updated with an example.

    28. In Spring MVC, how can I set the mime type header when using @ResponseBody

      I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1 the implementation looks quite neat Comments First the mvc:annotation-driven or the EnableWebMvc must be reference/html/mvc.html#mvc-config-enable added to your application config. details

      Reactions - Positive 3, Negative 0, Others 0

      1. @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar")@ResponseBodypublic Bar fooBar(){ return myService.getBar()
      2. }

      Positive Reactions
      1. Thanks!.
      2. This answer should be number one, let Spring do the work for you!
      3. Worked great.
      Other Reactions
      1. !.

    29. Spring 3.1, JSON response ModelAndView

      Then you would need to tell JQuery to expect HTML or Text but not JSON. If what you want is json to update some parts of the page don't return a ModelAndView return String make sure to have a json serializer . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html") public @ResponseBody String addSubMenu() { //yourvariable return yourvariable.toString()
      2. }

      Positive Reactions
      1. True, it will return a String, if an object is needed, replace String with your object and you can serialize it using jackson library for example.
      Other Reactions
      1. If you want to deliver some browser renderable code, I would delegate the view rendering to the View layer using ModelAndView (without the ReponseBody Annotation) as result.
      2. If you want to return an object, consider returning an Object and let Spring marshal it to JSON.
      3. This would deliver what ever you have in yourvariable.

    30. Interfaces and @RequestBody

      Sure thing my apologies!. I'm not sure it would work but you can try to make it generic . details

      Reactions - Positive 3, Negative 0, Others 0

      1. public interface BookableResourceController<R extends BookableResource> {
      2. @RequestMapping(value = "/delete.html", method = RequestMethod.POST)
      3. public ModelAndView processDeleteResource(@RequestBody R resource)
      4. }

      Positive Reactions
      1. I'm not too well versed in generics, so I never would have thought of this.
      2. Thank you for the quick response!.
      3. That worked beautifully!

    31. Parsing JSON in Spring MVC using Jackson JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("somepath")@ResponseBodypublic Fozzle doSomeThing(@RequestBody Fizzle input){ return new Fozzle(input)
      2. }

    32. Java web framework with RESTful JSON services, HTML5 & jQuery ajax

      If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
      2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
      3. } ...}public class Resource{ @JsonProperty("id") private int id
      4. @JsonProperty("resourceName") private String name
      5. ...}

    33. Spring JSON request getting 406 (not Acceptable)

      You're probably fine then sorry I couldn't be more help on this. In the controller shouldn't the response body annotation be on the return type and not the method like so I'd also use the raw jquery.ajax function and make sure contentType and dataType are being set correctly. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){ Weather weather = weatherService.getCurrentWeather(id)
      2. return weather
      3. }

      Other Reactions
      1. The placement of @ResponseBody should not matter...
      2. I will look into GSON...but still would like this JSON to work if possible.

    34. org.springframework.web.bind.MissingServletRequestParameterException

      If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. Providing a defaultValue implicitly sets required to false so I'll leave it out of the example Hope this helps . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    35. org.springframework.web.bind.MissingServletRequestParameterException

      RequestParam has an attribute required which is true by default. If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
      2. }

    36. How to validate request parameter if it is not a bean in spring MVC?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/some/path", method = RequestMethod.POST)@ResponseBodypublic Foo bar(@Valid @RequestBody LongList listOfLongs) { // do some useful work}

    37. In Spring MVC, how can I set the mime type header when using @ResponseBody

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public View fooBar(){ return new JsonView(myService.getJson())
      2. }

    38. RESTful MySQL / Terminology / Passing Parameters / Returning Ints & Doubles

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/people/gender/{gender}/updated/{lastUpdated}", method = RequestMethod.GET)@ResponseBodypublic Person findByGenderAndUpdated(@PathVariable String gender, @PathVariable String lastUpdated) {}

    39. Spring 3.0 making JSON response using jackson message converter

      Thx I have tried that before it isnt. In addition to the answers here if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody Foo json) {

    40. Convert Entity object to JSON

      And i put jackson libraries to classpath. is what you need and DO NOT FORGET to make a POST request in your JS code not GET). details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(produces="application/json")

    41. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller
      2. @RequestMapping("/test")
      3. public class TestController {
      4. @RequestMapping(method = RequestMethod.POST, value = "math")
      5. @ResponseBody
      6. public Result math(@RequestBody final Request request) {
      7. final Result result = new Result()
      8. result.setAddition(request.getLeft() + request.getRight())
      9. result.setSubtraction(request.getLeft() - request.getRight())
      10. result.setMultiplication(request.getLeft() * request.getRight())
      11. return result
      12. }
      13. }

    42. Spring 3.1, JSON response ModelAndView

      Your server would like to serialize the ModelAndView Object as a JSON string and your jQuery code wants to append an HTML element to the DOM. There are a few things which could be wrong here By specifying a Content-type header of application/json you are expecting a response of json back however looking at the way you are handling the response it looks like what you want is an html if it is html that you are looking for as a response then remove the Content Type header from the request remove the ResponseBody annotation from ModelAndView response instead just return a view which points to a normal jsp which can create the html response that you are expecting . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")public ModelAndView addSubMenu(@RequestBody Menu menu) {...}

      Other Reactions
      1. This would be my understanding of a partial.
      2. Then you would need to tell JQuery to expect HTML or Text but not JSON.
      3. This would deliver HTML Code (Model delivered form controller, view delivered from Template) to the client.

    43. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public String sync(@RequestBody Foo json) {

    44. Serializing enums with Jackson

      also I found good workaround sedCommentId=306450&page=com.atlassian.jira.plugin.system.issuetabpanels comment-tabpanel#comment-306450. available since just tested it works with version 2.1.2 answer to TheZuck** I tried your example got Json My code and dependencies are . details

      Reactions - Positive 3, Negative 1, Others 0

      1. @RequestMapping(value = "/getEvent") @ResponseBody public EventContainer getEvent() { EventContainer cont = new EventContainer()
      2. cont.setEvents(Event.values())
      3. return cont
      4. }class EventContainer implements Serializable { private Event[] events
      5. public Event[] getEvents() { return events
      6. } public void setEvents(Event[] events) { this.events = events
      7. }

      Positive Reactions
      1. Upgraded to 3.2.1 and all is well now.
      2. Thanks!.
      3. Using on Mule 3.4.1 and it is working like a charm!.
      Negative Reactions
      1. found out what was wrong, I was using Jackson 2.1.2 but my Spring version was still 3.1 hence did not support this version.
      Other Reactions
      1. @JsonFormat(shape= JsonFormat.Shape.OBJECT)@JsonAutoDetect()public enum Event { VISIT_WEBSITE(Type.ADMIN); @JsonProperty public Type type; public Type getType() { return type; } Event(Type type) { this.type type; } public enum Type { ADMIN, CONSUMER, }}I'm using Jackson 2.1.2.
      2. I like this alternative, it's cleaner, however, I tried it with this class and type does not get serialized, any idea what's wrong?
      3. I've added additional details to body of answer.

    45. Spring JSON request getting 406 (not Acceptable)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)

  23. dateformat
      Chart will be rendered here
    1. springmvc using json response

      Then just return your item formattedDate. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
      2. Date date = new Date()
      3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      4. String formattedDate = dateFormat.format(date)
      5. model.addAttribute("serverTime", formattedDate )
      6. return "main"
      7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
      8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      9. return dateFormat.format(date)
      10. }

      Positive Reactions
      1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
      2. Did you resolve your issue?
      3. Nope, I think doing that's just fine.
      Negative Reactions
      1. Ah, sorry about that.
      2. Do you think it's a bad idea to have the controller handle the views?
      3. That seems a bit nasty.
      Other Reactions
      1. Load your view at the root.
      2. also - I don't think that code would even compile with duplicate method names.
      3. Are you suggesting I go to one url for the JSON response and another for the html?
      4. Changed in the example just for future reference.
      5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
      6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
      7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
      8. Is it possible to do both?
      9. I see you marked it as an answer.
      10. Or did you still need help with that?
      11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
      12. I've included jackson-core-asl in my pom.xml.
      13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
      14. Then your view should make an ajax request for the data at /serverTime.
      15. Updated with an example.

  24. httpstatus
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

      Reactions - Positive 7, Negative 2, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
      2. HttpHeaders responseHeaders = new HttpHeaders()
      3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
      4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
      5. }

      Positive Reactions
      1. See if your import is correct and your libraries are updated.
      2. That's the nicest one so far, thanks (+1).
      3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
      4. If I could vote for this multiple times, I would!.
      5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
      6. This works great.
      7. now it works fine if not using ResponseEntity.
      Negative Reactions
      1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
      2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
      Other Reactions
      1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
      2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
      3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

    2. Spring MVC REST Json Conversion exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, @PathVariable String id) { final ResponseEntity<Property> response = new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK)
      2. return response
      3. }

  25. component
      Chart will be rendered here
    1. Sending a JComponent as an image

      Instead of them receiving it as a series of x,y co-ordinates they've asked me to send an image. To capture an image of a component create an image get a graphics context for the image then ask the component to paint itself using that graphics context import java.awt.image.BufferedImage if not already. details

      Reactions - Positive 1, Negative 0, Others 0

      1. Component comp = ...
      2. BufferedImage image = new BufferedImage(comp.getWidth(), comp.getHeight(), BufferedImage.TYPE_INT_RGB)
      3. Graphics2D g = image.createGraphics()
      4. comp.paint(g)
      5. g.dispose()

      Positive Reactions
      1. Thanks Boann, I will look into this as soon as I can and then tick it if it works.
      Other Reactions
      1. I haven't forgotten you, just had a another large task fall on my lap and haven't had a chance to give this a second look.

    2. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  26. mediatype
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1 the implementation looks quite neat Comments First the mvc:annotation-driven or the EnableWebMvc must be reference/html/mvc.html#mvc-config-enable added to your application config. details

      Reactions - Positive 3, Negative 0, Others 0

      1. @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar")@ResponseBodypublic Bar fooBar(){ return myService.getBar()
      2. }

      Positive Reactions
      1. Thanks!.
      2. This answer should be number one, let Spring do the work for you!
      3. Worked great.
      Other Reactions
      1. !.

    2. In Spring MVC, how can I set the mime type header when using @ResponseBody

      According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

      Reactions - Positive 7, Negative 2, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
      2. HttpHeaders responseHeaders = new HttpHeaders()
      3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
      4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
      5. }

      Positive Reactions
      1. See if your import is correct and your libraries are updated.
      2. That's the nicest one so far, thanks (+1).
      3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
      4. If I could vote for this multiple times, I would!.
      5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
      6. This works great.
      7. now it works fine if not using ResponseEntity.
      Negative Reactions
      1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
      2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
      Other Reactions
      1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
      2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
      3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

  27. jsonarg
      Chart will be rendered here
    1. spring mvc passing objects with post method

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. boolean createModel( @JsonArg SettlementModelGroup modelGroup, @JsonArg Integer periodId, @JsonArg Integer domainId, @JsonArg Integer modelTypeId )

  28. controller
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

    2. Providing RESTful JSON API in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

  29. serializationfeature
      Chart will be rendered here
    1. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  30. response
      Chart will be rendered here
    1. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

  31. objectmapper
      Chart will be rendered here
    1. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  32. httpservletrequest
      Chart will be rendered here
    1. Providing RESTful JSON API in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

  33. beanpostprocessor
      Chart will be rendered here
    1. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  34. exception
      Chart will be rendered here
    1. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

  35. responsebody
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      Register org.springframework.http.converter.json.MappingJacksonHttpMessageConverter as the message converter and return the object directly from the method. and the controller . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public @ResponseBody Object fooBar(){ return myService.getActualObject()
      2. }

      Positive Reactions
      1. Yes, probably a best practice, but as I wrote my objects are already JSON strings and I just want to write them out with the correct mime type.
      Other Reactions
      1. org/springframework/spring-webmvc should cover it.
      2. What are the maven dependencies for the beans you are referencing?

    2. springmvc using json response

      I see you marked it as an answer. There's a library for converting Java objects to JSON called gson gson/ Incidentally if you're wanting to send an Ajax response rather than refreshing the page add ResponseBody to your method declaration and return your JSON string assuming you're not updating your model if this is the case). details

      Reactions - Positive 1, Negative 0, Others 0

      1. public @ResponseBody String home(Locale locale, Model model) { .. }

      Positive Reactions
      1. Ah, if you notice the bottom of my question, this looks like it will break my view handling as it returns the view "main", is it possible to do this JSON response and keep handling my views within the controller?
      Other Reactions
      1. I think BrandonV has answered this.

    3. Sending JSON to Spring MVC controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

    4. Redirect at @ResponseBody?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/postLogout.html", method=RequestMethod.GET)@ResponseBody public MyreturnObject getPostLogout(){ return new ReturnObject(true,true,false)
      2. }

    5. springmvc using json response

      Then just return your item formattedDate. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
      2. Date date = new Date()
      3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      4. String formattedDate = dateFormat.format(date)
      5. model.addAttribute("serverTime", formattedDate )
      6. return "main"
      7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
      8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
      9. return dateFormat.format(date)
      10. }

      Positive Reactions
      1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
      2. Did you resolve your issue?
      3. Nope, I think doing that's just fine.
      Negative Reactions
      1. Ah, sorry about that.
      2. Do you think it's a bad idea to have the controller handle the views?
      3. That seems a bit nasty.
      Other Reactions
      1. Load your view at the root.
      2. also - I don't think that code would even compile with duplicate method names.
      3. Are you suggesting I go to one url for the JSON response and another for the html?
      4. Changed in the example just for future reference.
      5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
      6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
      7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
      8. Is it possible to do both?
      9. I see you marked it as an answer.
      10. Or did you still need help with that?
      11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
      12. I've included jackson-core-asl in my pom.xml.
      13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
      14. Then your view should make an ajax request for the data at /serverTime.
      15. Updated with an example.

    6. Marshaling JSON and Generics in Java with Spring MVC

      Your solution worked for me D tnx. I ended up creating another class So in the controller instead of i did this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String setJobStatus(@RequestBody List<JobUpdate> jobUpdates) {

    7. Spring MVC + JSON = 406 Not Acceptable

      Thank you very much with your antecedent post I've finally managed to get it working. You have to register the annotation binding for Jackson in your spring-mvc config.xml for example Then in your controller you can use . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")@ResponseBody

    8. Providing RESTful JSON API in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

    9. Spring 3.2 Web MVC @ModelAttribute without label

      It seems that you use jQuery datatables so you should add ResponseBody to the method . . details

      Reactions - Positive 2, Negative 0, Others 0

      1. @RequestMapping(method = RequestMethod.GET)@ResponseBody public DTResponse agents() { DTResponse resp = new DTResponse()
      2. resp.setsEcho(1)
      3. resp.setiTotalDisplayRecords(10)
      4. resp.setiTotalRecords(50)
      5. return resp
      6. }}

      Positive Reactions
      1. Thanks :).
      2. Works like a charm.

    10. Spring MVC returning JSONS and exception Handling

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @ResponseBody public Response getUserDetails) { //... return new Response(userDetails)
      2. }

    11. Java web framework with RESTful JSON services, HTML5 & jQuery ajax

      If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
      2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
      3. } ...}public class Resource{ @JsonProperty("id") private int id
      4. @JsonProperty("resourceName") private String name
      5. ...}

    12. Spring 3.1, JSON response ModelAndView

      Then you would need to tell JQuery to expect HTML or Text but not JSON. If what you want is json to update some parts of the page don't return a ModelAndView return String make sure to have a json serializer . details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html") public @ResponseBody String addSubMenu() { //yourvariable return yourvariable.toString()
      2. }

      Positive Reactions
      1. True, it will return a String, if an object is needed, replace String with your object and you can serialize it using jackson library for example.
      Other Reactions
      1. If you want to deliver some browser renderable code, I would delegate the view rendering to the View layer using ModelAndView (without the ReponseBody Annotation) as result.
      2. If you want to return an object, consider returning an Object and let Spring marshal it to JSON.
      3. This would deliver what ever you have in yourvariable.

    13. JQuery, Spring MVC @RequestBody and JSON - making it work together

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Controller
      2. @RequestMapping("/test")
      3. public class TestController {
      4. @RequestMapping(method = RequestMethod.POST, value = "math")
      5. @ResponseBody
      6. public Result math(@RequestBody final Request request) {
      7. final Result result = new Result()
      8. result.setAddition(request.getLeft() + request.getRight())
      9. result.setSubtraction(request.getLeft() - request.getRight())
      10. result.setMultiplication(request.getLeft() * request.getRight())
      11. return result
      12. }
      13. }

    14. Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

    15. Serializing enums with Jackson

      also I found good workaround sedCommentId=306450&page=com.atlassian.jira.plugin.system.issuetabpanels comment-tabpanel#comment-306450. available since just tested it works with version 2.1.2 answer to TheZuck** I tried your example got Json My code and dependencies are . details

      Reactions - Positive 3, Negative 1, Others 0

      1. @RequestMapping(value = "/getEvent") @ResponseBody public EventContainer getEvent() { EventContainer cont = new EventContainer()
      2. cont.setEvents(Event.values())
      3. return cont
      4. }class EventContainer implements Serializable { private Event[] events
      5. public Event[] getEvents() { return events
      6. } public void setEvents(Event[] events) { this.events = events
      7. }

      Positive Reactions
      1. Upgraded to 3.2.1 and all is well now.
      2. Thanks!.
      3. Using on Mule 3.4.1 and it is working like a charm!.
      Negative Reactions
      1. found out what was wrong, I was using Jackson 2.1.2 but my Spring version was still 3.1 hence did not support this version.
      Other Reactions
      1. @JsonFormat(shape= JsonFormat.Shape.OBJECT)@JsonAutoDetect()public enum Event { VISIT_WEBSITE(Type.ADMIN); @JsonProperty public Type type; public Type getType() { return type; } Event(Type type) { this.type type; } public enum Type { ADMIN, CONSUMER, }}I'm using Jackson 2.1.2.
      2. I like this alternative, it's cleaner, however, I tried it with this class and type does not get serialized, any idea what's wrong?
      3. I've added additional details to body of answer.

    16. Marshaling JSON and Generics in Java with Spring MVC

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String setJobStatus(@RequestBody JobUpdateList jobUpdates) {

    17. Spring 3.0 making JSON response using jackson message converter

      3. Use as the following This works for me. details

      Reactions - Positive 1, Negative 0, Others 0

      1. @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })public @ResponseBody Foo method(@Valid Request request, BindingResult result){return new Foo(3,4)}

      Positive Reactions
      1. @ResponseBody is applied to return type - this was my issue, thanks!.
      Other Reactions
      1. Providing that, as you suggest, is important.
      2. The key part here, I think, is that the OP doesn't have a RequestMapping.
      3. For testing your post requests with Curl or upgrading to spring 3.2 checkout [here]( URL_http://stackoverflow.com/questions/16909742/spring-3-2-0-web-mvc-rest - api-and-json2-post-requests-how-to-get-it-right-onc).
      4. @GaryF updated my answer.

    18. Spring JSON request getting 406 (not Acceptable)

      You're probably fine then sorry I couldn't be more help on this. In the controller shouldn't the response body annotation be on the return type and not the method like so I'd also use the raw jquery.ajax function and make sure contentType and dataType are being set correctly. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){ Weather weather = weatherService.getCurrentWeather(id)
      2. return weather
      3. }

      Other Reactions
      1. The placement of @ResponseBody should not matter...
      2. I will look into GSON...but still would like this JSON to work if possible.

    19. Binding the nested json to @RequestBody object using Jackson converter

      The issue was fixed by adding below logic. Here your Java class DrugListJsonRequest should extend It doesn't require a any methods and constructors. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public @ResponseBody String saveDrug(@RequestBody DrugListJsonRequest drugListCriterion) {}

  36. arraylist
      Chart will be rendered here
    1. JSONMappingException - cannot desierialize Java object

      Your best bet would be to write a custom bean to deserialize the JSON into then instantiate a PageImpl with the values from this custom bean. I ended up using something like this creating a bean as Perception suggested and then modify your code to use the concrete class and get the PageImpl . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.ArrayList
      2. import java.util.List
      3. import org.springframework.data.domain.PageImpl
      4. import org.springframework.data.domain.PageRequest
      5. import org.springframework.data.domain.Sort
      6. public class PageImplBean<T> extends PageImpl<T> {
      7. private static final long serialVersionUID = 1L
      8. private int number
      9. private int size
      10. private int totalPages
      11. private int numberOfElements
      12. private long totalElements
      13. private boolean previousPage
      14. private boolean firstPage
      15. private boolean nextPage
      16. private boolean lastPage
      17. private List<T> content
      18. private Sort sort
      19. public PageImplBean() {
      20. super(new ArrayList<T>())
      21. }
      22. public int getNumber() {
      23. return number
      24. }
      25. public void setNumber(int number) {
      26. this.number = number
      27. }
      28. public int getSize() {
      29. return size
      30. }
      31. public void setSize(int size) {
      32. this.size = size
      33. }
      34. public int getTotalPages() {
      35. return totalPages
      36. }
      37. public void setTotalPages(int totalPages) {
      38. this.totalPages = totalPages
      39. }
      40. public int getNumberOfElements() {
      41. return numberOfElements
      42. }
      43. public void setNumberOfElements(int numberOfElements) {
      44. this.numberOfElements = numberOfElements
      45. }
      46. public long getTotalElements() {
      47. return totalElements
      48. }
      49. public void setTotalElements(long totalElements) {
      50. this.totalElements = totalElements
      51. }
      52. public boolean isPreviousPage() {
      53. return previousPage
      54. }
      55. public void setPreviousPage(boolean previousPage) {
      56. this.previousPage = previousPage
      57. }
      58. public boolean isFirstPage() {
      59. return firstPage
      60. }
      61. public void setFirstPage(boolean firstPage) {
      62. this.firstPage = firstPage
      63. }
      64. public boolean isNextPage() {
      65. return nextPage
      66. }
      67. public void setNextPage(boolean nextPage) {
      68. this.nextPage = nextPage
      69. }
      70. public boolean isLastPage() {
      71. return lastPage
      72. }
      73. public void setLastPage(boolean lastPage) {
      74. this.lastPage = lastPage
      75. }
      76. public List<T> getContent() {
      77. return content
      78. }
      79. public void setContent(List<T> content) {
      80. this.content = content
      81. }
      82. public Sort getSort() {
      83. return sort
      84. }
      85. public void setSort(Sort sort) {
      86. this.sort = sort
      87. }
      88. public PageImpl<T> pageImpl() {
      89. return new PageImpl<T>(
      90. getContent(), new PageRequest(getNumber(), getSize(), getSort()), getTotalElements())
      91. }
      92. }

  37. bufferedimage
      Chart will be rendered here
    1. Sending a JComponent as an image

      Instead of them receiving it as a series of x,y co-ordinates they've asked me to send an image. To capture an image of a component create an image get a graphics context for the image then ask the component to paint itself using that graphics context import java.awt.image.BufferedImage if not already. details

      Reactions - Positive 1, Negative 0, Others 0

      1. Component comp = ...
      2. BufferedImage image = new BufferedImage(comp.getWidth(), comp.getHeight(), BufferedImage.TYPE_INT_RGB)
      3. Graphics2D g = image.createGraphics()
      4. comp.paint(g)
      5. g.dispose()

      Positive Reactions
      1. Thanks Boann, I will look into this as soon as I can and then tick it if it works.
      Other Reactions
      1. I haven't forgotten you, just had a another large task fall on my lap and haven't had a chance to give this a second look.

  38. mappingjackson2httpmessageconverter
      Chart will be rendered here
    1. Jackson 2.0 with Spring 3.1

      or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package foo.bar.JacksonConfig
      2. import com.fasterxml.jackson.databind.ObjectMapper
      3. import com.fasterxml.jackson.databind.SerializationFeature
      4. import org.springframework.beans.BeansException
      5. import org.springframework.beans.factory.config.BeanPostProcessor
      6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
      7. @Componentpublic
      8. class JacksonConfig implements BeanPostProcessor {
      9. public Object postProcessBeforeInitialization(Object bean, String beanName)
      10. throws BeansException {
      11. return bean
      12. }
      13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      14. if (bean instanceof MappingJackson2HttpMessageConverter) {
      15. MappingJackson2HttpMessageConverter jsonConverter =
      16. (MappingJackson2HttpMessageConverter) bean
      17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
      18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      19. jsonConverter.setObjectMapper(objectMapper)
      20. }
      21. return bean
      22. }
      23. }

      Positive Reactions
      1. @Ryan this works great.
      2. I'm sure that this is not the official way but it's very clever!.
      Negative Reactions
      1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
      Other Reactions
      1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  39. ioexception
      Chart will be rendered here
    1. In Spring MVC, how can I set the mime type header when using @ResponseBody

      org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xxx
      2. import java.io.ByteArrayOutputStream
      3. import java.io.IOException
      4. import javax.servlet.http.HttpServletResponse
      5. import org.springframework.web.bind.annotation.RequestMapping
      6. import org.springframework.web.bind.annotation.RequestMethod
      7. @Controllerpublic
      8. class FooBar {
      9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
      10. public void fooBar(HttpServletResponse response) throws IOException {
      11. ByteArrayOutputStream out = new ByteArrayOutputStream()
      12. out.write(myService.getJson().getBytes())
      13. response.setContentType("application/json")
      14. response.setContentLength(out.size())
      15. response.getOutputStream().write(out.toByteArray())
      16. response.getOutputStream().flush()
      17. }
      18. }

      Other Reactions
      1. would he need to write to the response, or just setting the header would do?

  40. roojparepository
      Chart will be rendered here
    1. Configuring Web Service & thin client using Servlet+JSON+MySQL

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.example.repositories
      2. import org.springframework.roo.addon.layers.repository.jpa.RooJpaRepository
      3. @RooJpaRepository(domainType = Example.class)
      4. public interface ExampleRepository {}

  41. jsonresponse
      Chart will be rendered here
    1. Sending list in JSON request

      Define below bean return jsonView from the controller. Controller Change in ajax viewsResolver config in mvc-servlet.xml . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import org.springframework.ui.ModelMap
      2. @RequestMapping(value = "/testURL.do", method = RequestMethod.POST)public String executeTest(ModelMap model, ListData listData) { ModelAndView modelAndView = null
      3. JsonResponse jsonResponse = null
      4. modelAndView = executeTransaction(listData)
      5. model.addAttribute("paramName", modelAndView)
      6. } return "jsonView"
      7. }

      Positive Reactions
      1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
      2. Thanks a lot Boss!.
      3. Thanks but we are not using Gson.
      4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
      Other Reactions
      1. Point Number 2 is not related to gson, it is spring.
      2. I update the answer with all changes required.
      3. Or I need to do additional processing in controller?
      4. We are using Jackson.

  42. modelandview
      Chart will be rendered here
    1. Sending list in JSON request

      Define below bean return jsonView from the controller. Controller Change in ajax viewsResolver config in mvc-servlet.xml . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import org.springframework.ui.ModelMap
      2. @RequestMapping(value = "/testURL.do", method = RequestMethod.POST)public String executeTest(ModelMap model, ListData listData) { ModelAndView modelAndView = null
      3. JsonResponse jsonResponse = null
      4. modelAndView = executeTransaction(listData)
      5. model.addAttribute("paramName", modelAndView)
      6. } return "jsonView"
      7. }

      Positive Reactions
      1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
      2. Thanks a lot Boss!.
      3. Thanks but we are not using Gson.
      4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
      Other Reactions
      1. Point Number 2 is not related to gson, it is spring.
      2. I update the answer with all changes required.
      3. Or I need to do additional processing in controller?
      4. We are using Jackson.

    2. Spring 3.0 making JSON response using jackson message converter

      Thx I have tried that before it isnt. In addition to the answers here if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody Foo json) {

    3. Interfaces and @RequestBody

      Sure thing my apologies!. I'm not sure it would work but you can try to make it generic . details

      Reactions - Positive 3, Negative 0, Others 0

      1. public interface BookableResourceController<R extends BookableResource> {
      2. @RequestMapping(value = "/delete.html", method = RequestMethod.POST)
      3. public ModelAndView processDeleteResource(@RequestBody R resource)
      4. }

      Positive Reactions
      1. I'm not too well versed in generics, so I never would have thought of this.
      2. Thank you for the quick response!.
      3. That worked beautifully!

    4. Spring 3.1, JSON response ModelAndView

      Your server would like to serialize the ModelAndView Object as a JSON string and your jQuery code wants to append an HTML element to the DOM. There are a few things which could be wrong here By specifying a Content-type header of application/json you are expecting a response of json back however looking at the way you are handling the response it looks like what you want is an html if it is html that you are looking for as a response then remove the Content Type header from the request remove the ResponseBody annotation from ModelAndView response instead just return a view which points to a normal jsp which can create the html response that you are expecting . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")public ModelAndView addSubMenu(@RequestBody Menu menu) {...}

      Other Reactions
      1. This would be my understanding of a partial.
      2. Then you would need to tell JQuery to expect HTML or Text but not JSON.
      3. This would deliver HTML Code (Model delivered form controller, view delivered from Template) to the client.

    5. Parsing json into java objects in spring-mvc

      Thanks!. if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody SearchRequest json) {

All usage scenarios for API org.springframework
  • Spring MVC REST Json Conversion exception

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. public ResponseEntity<Property> updateProperty(@RequestBody PropertyWrapper property, @PathVariable String id) { final ResponseEntity<Property> response = new ResponseEntity<Property>(property.getProperty(), HttpStatus.OK)
    2. return response
    3. }

  • Right way to write JSON deserializer in Spring or extend it

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Servicepublic
    2. class AnchorService {}

  • Sending a JComponent as an image

    Instead of them receiving it as a series of x,y co-ordinates they've asked me to send an image. To capture an image of a component create an image get a graphics context for the image then ask the component to paint itself using that graphics context import java.awt.image.BufferedImage if not already. details

    Reactions - Positive 1, Negative 0, Others 0

    1. Component comp = ...
    2. BufferedImage image = new BufferedImage(comp.getWidth(), comp.getHeight(), BufferedImage.TYPE_INT_RGB)
    3. Graphics2D g = image.createGraphics()
    4. comp.paint(g)
    5. g.dispose()

    Positive Reactions
    1. Thanks Boann, I will look into this as soon as I can and then tick it if it works.
    Other Reactions
    1. I haven't forgotten you, just had a another large task fall on my lap and haven't had a chance to give this a second look.

  • Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

  • Convert Entity object to JSON

    And i put jackson libraries to classpath. is what you need and DO NOT FORGET to make a POST request in your JS code not GET). details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(produces="application/json")

  • Configuring Web Service & thin client using Servlet+JSON+MySQL

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. package com.example.repositories
    2. import org.springframework.roo.addon.layers.repository.jpa.RooJpaRepository
    3. @RooJpaRepository(domainType = Example.class)
    4. public interface ExampleRepository {}

  • Configuring Web Service & thin client using Servlet+JSON+MySQL

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RooWebJson(jsonObject = Example.class)
    2. @Controller
    3. @RequestMapping("/example/")
    4. public class ExampleController {
    5. @Resource ExampleRepository exampleRepo
    6. @RequestMapping(method = RequestMethod.PUT, value = "/{name}")
    7. public void putExample(@PathVariable("name") String name) {
    8. exampleRepo.save(new Example(name))
    9. }
    10. }

  • ModelAttribute for Restful PUT method not populated value ( JSON )

    Add the below filter to your WebApplicationInitializer class or corresponding xml code to web.xml . Im replace for Link help reference/html/mvc.html#mvc-config-enable reference/html/mvc.html#mvc-config-enable and json-request-body Spring-MVC:-Don't-deserialize-JSON-request-body . details

    Reactions - Positive 2, Negative 0, Others 0

    1. @ModelAttribute("positionGPS") PositionGPS positionGPS, @PathVariable Long id, Model model

    Positive Reactions
    1. You specified you're using Postman, but that obviously isn't going to be your final working solution.
    2. I tested on a cell application and backbone and everything works.
    Other Reactions
    1. You'll have to use either Ajax or a form post.
    2. And did that work?
    3. If it did then I assume you already have Jackson on the classpath for marshaling from JSON to an object.
    4. If you're using a form post this still isn't going to work because that doesn't support a PUT operation cross-browser.

  • ModelAttribute for Restful PUT method not populated value ( JSON )

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestBody PositionGPS positionGPS, @PathVariable Long id, Model model)

  • ModelAttribute for Restful PUT method not populated value ( JSON )

    If you can't use Ajax the only other option is to tunnel everything through POST for create update and delete operations. Add the below filter to your WebApplicationInitializer class or corresponding xml code to web.xml . details

    Reactions - Positive 0, Negative 0, Others 0

    1. final FilterRegistration.Dynamic httpMethodFilter = servletContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter())
    2. httpMethodFilter.addMappingForUrlPatterns(null, true, "/*")
    3. final FilterRegistration.Dynamic putFormFilter = servletContext.addFilter("httpPutFormContentFilter", new HttpPutFormContentFilter())
    4. putFormFilter.addMappingForUrlPatterns(null, true, "/*")

  • JSON to Java Mapping Parametric / Generic types

    As an example JSON doesn't have an equivalent to polymorphic types and yet Jackson is able to handle those through annotations. A solution would be to declare a parametric type and use this as the target of RequestBody this way Note that the MyCustomTypeContainer has to be a parametric type(generic types fully realized). details

    Reactions - Positive 2, Negative 0, Others 0

    1. public class MyCustomTypeContainer extends Container<SubContainerItem> {..}public void updateContainer(@RequestBody MyCustomTypeContainer container) { realService.updateContainer(container)
    2. }

    Positive Reactions
    1. Yes true Josh, actually your approach does sound good also.
    2. One change that I can think of is not having the class name in xml, that does not look clean, instead you an try put this information in a custom annotation and use that annotation along with a [HandlerMethodArgumentResolver]( URL_http://docs.spring.io/spring/docs/3.2.x /javadoc- api/org/springframework/web/method/support/HandlerMethodArgumentResolver.html) to create the appropriate JavaType and do the unmarshalling there.
    Other Reactions
    1. Hi Biju, this solution would work if I want to only updateContainer with one concrete type of sub container (SubContainerItem) - but what if I also want to be able to update a container full of SubContainerItem2?

  • JSONMappingException - cannot desierialize Java object

    Your best bet would be to write a custom bean to deserialize the JSON into then instantiate a PageImpl with the values from this custom bean. I ended up using something like this creating a bean as Perception suggested and then modify your code to use the concrete class and get the PageImpl . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.util.ArrayList
    2. import java.util.List
    3. import org.springframework.data.domain.PageImpl
    4. import org.springframework.data.domain.PageRequest
    5. import org.springframework.data.domain.Sort
    6. public class PageImplBean<T> extends PageImpl<T> {
    7. private static final long serialVersionUID = 1L
    8. private int number
    9. private int size
    10. private int totalPages
    11. private int numberOfElements
    12. private long totalElements
    13. private boolean previousPage
    14. private boolean firstPage
    15. private boolean nextPage
    16. private boolean lastPage
    17. private List<T> content
    18. private Sort sort
    19. public PageImplBean() {
    20. super(new ArrayList<T>())
    21. }
    22. public int getNumber() {
    23. return number
    24. }
    25. public void setNumber(int number) {
    26. this.number = number
    27. }
    28. public int getSize() {
    29. return size
    30. }
    31. public void setSize(int size) {
    32. this.size = size
    33. }
    34. public int getTotalPages() {
    35. return totalPages
    36. }
    37. public void setTotalPages(int totalPages) {
    38. this.totalPages = totalPages
    39. }
    40. public int getNumberOfElements() {
    41. return numberOfElements
    42. }
    43. public void setNumberOfElements(int numberOfElements) {
    44. this.numberOfElements = numberOfElements
    45. }
    46. public long getTotalElements() {
    47. return totalElements
    48. }
    49. public void setTotalElements(long totalElements) {
    50. this.totalElements = totalElements
    51. }
    52. public boolean isPreviousPage() {
    53. return previousPage
    54. }
    55. public void setPreviousPage(boolean previousPage) {
    56. this.previousPage = previousPage
    57. }
    58. public boolean isFirstPage() {
    59. return firstPage
    60. }
    61. public void setFirstPage(boolean firstPage) {
    62. this.firstPage = firstPage
    63. }
    64. public boolean isNextPage() {
    65. return nextPage
    66. }
    67. public void setNextPage(boolean nextPage) {
    68. this.nextPage = nextPage
    69. }
    70. public boolean isLastPage() {
    71. return lastPage
    72. }
    73. public void setLastPage(boolean lastPage) {
    74. this.lastPage = lastPage
    75. }
    76. public List<T> getContent() {
    77. return content
    78. }
    79. public void setContent(List<T> content) {
    80. this.content = content
    81. }
    82. public Sort getSort() {
    83. return sort
    84. }
    85. public void setSort(Sort sort) {
    86. this.sort = sort
    87. }
    88. public PageImpl<T> pageImpl() {
    89. return new PageImpl<T>(
    90. getContent(), new PageRequest(getNumber(), getSize(), getSort()), getTotalElements())
    91. }
    92. }

  • How to send Json response in spring?

    Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go Just a little summary As you know you will need the Jackson library in the class path so that Objects can be converted to JSON. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/getfees", method = RequestMethod.POST)public @ResponseBodyDomainFeesResponse getFees( @RequestHeader(value = "userName") String userName, @RequestHeader(value = "password") String password, @RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) { return domainFeesHelper.executeRetreiveFees(userName, password, syncDate)
    2. }

  • Spring REST with both JSON and XML

    I'm doing this in a current project without using a ContentNegotiatingViewResolver. For one method in my controller I can receive the following output based on the Accept request header. details

    Reactions - Positive 0, Negative 2, Others 0

    1. @RequestMapping(value = "/test", method = RequestMethod.GET)@ResponseBodypublic HttpEntity<BasicResponse> getBasicResponse() { return new HttpEntity<BasicResponse>(new BasicResponse())
    2. }

    Negative Reactions
    1. Thanks for your answer, but I wasn't clear enough in my question.
    2. I too get valid xml & json, but a pretty xml api becomes an ugly json api and the other way around.
    Other Reactions
    1. I think @chrylis was spot on.

  • 400 Bad request on Spring ajax call

    script Spring Controller . Your saveInvestmentValue method expects a . details

    Reactions - Positive 0, Negative 1, Others 0

    1. @RequestParam("transactionDate")

    Negative Reactions
    1. sorry, the project wasnt clean, it worked after cleaning the project, thanks again.
    Other Reactions
    1. thanks, edited that, but still having error.

  • spring generic json response

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Controllerpublic
    2. class MyController {
    3. @RequestMapping(value = "/mypath", produces = "application/json")
    4. public Response<SomeObject> myPathMethod() {
    5. return new Response<SomeObject>("200", "success!", new SomeObject())
    6. }
    7. }

  • Providing RESTful JSON API in Java

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Controller@RequestMapping("/user")public class UserService { @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json") public @ResponseBody Response login( @RequestParam(value = "user", defaultValue = "") String email, @RequestParam(value = "password", defaultValue = "") String password, HttpServletRequest request ) { // Your logic here }}

  • How to validate request parameter if it is not a bean in spring MVC?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/some/path", method = RequestMethod.POST)@ResponseBodypublic Foo bar(@Valid @RequestBody LongList listOfLongs) { // do some useful work}

  • Spring MVC: Don't deserialize JSON request body

    I'm guessing your body is not simply a String but some full JSON object. If you have a java model of the JSON object you are expecting then you could replace the String parameter with that in your doSomething declaration such as If you don't have a Java object that matches the JSON then you could try to get it working by replacing the String type with a Map<String Object and see if that gets you closer to a working solution. details

    Reactions - Positive 5, Negative 5, Others 0

    1. public void doSomething(@RequestBody MyObject myobj) {

    Positive Reactions
    1. I'd be interested in how Bart's solution would work.
    2. As a workaround you could simply define a simple class that exposes a string value.
    3. Don't use @RequestBody, and send the json value as a regular request param in a form.
    4. It does work!
    5. That looks like it should work perfectly, thanks @digitaljoel.
    Negative Reactions
    1. Never mind, that was my own fault, actually.
    2. Sorry about that.
    3. It throws this exception: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of javax.servlet.http.HttpServletRequest, problem: abstract types can only be instantiated with additional type information.
    4. To make matters more complex, the application only accepts Content-Type values of application/json so even if every client could send this particular request as plaintext it would be rejected by the application (I can't change this).
    5. Sorry to double comment, but I can't edit my above comment.
    Other Reactions
    1. I enabled debug logging in Spring and came up with this exception: org.codehaus.jackson.map.JsonMappingException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_ARRAY token - so how would I skip the deserializing part and just retrieve the JSON data as a string?
    2. I normally would map it to a Java object but I need to modify the raw JSON before I create the object, hence why I need the raw JSON string.
    3. I don't know how Jackson would map it appropriately.
    4. I updated my answer with a new possible solution.
    5. If you want it as a string then you should send it as a String.
    6. I'm unaccepting this answer as it doesn't seem to work, actually.
    7. This is for a REST API interfacing with middleware, the middleware will be directly calling the routes with the JSON as the body of the request.
    8. Just because the String contains JSON content doesn't mean you need to tell Spring MVC that.
    9. e.g.
    10. You're right - the body is a full JSON object.
    11. class JsonValue { getValue(); }.

  • Spring MVC + JSON = 406 Not Acceptable

    Thank you very much with your antecedent post I've finally managed to get it working. You have to register the annotation binding for Jackson in your spring-mvc config.xml for example Then in your controller you can use . details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")@ResponseBody

  • Spring 3.2 Web MVC @ModelAttribute without label

    It seems that you use jQuery datatables so you should add ResponseBody to the method . . details

    Reactions - Positive 2, Negative 0, Others 0

    1. @RequestMapping(method = RequestMethod.GET)@ResponseBody public DTResponse agents() { DTResponse resp = new DTResponse()
    2. resp.setsEcho(1)
    3. resp.setiTotalDisplayRecords(10)
    4. resp.setiTotalRecords(50)
    5. return resp
    6. }}

    Positive Reactions
    1. Thanks :).
    2. Works like a charm.

  • JSON character encoding

    I dont know if this is relevant anymore but I fixed it with the RequestMapping annotation. . details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(method=RequestMethod.GET, produces={"application/json
    2. charset=UTF-8"})

  • Sending list in JSON request

    Define below bean return jsonView from the controller. Controller Change in ajax viewsResolver config in mvc-servlet.xml . details

    Reactions - Positive 4, Negative 0, Others 0

    1. import org.springframework.ui.ModelMap
    2. @RequestMapping(value = "/testURL.do", method = RequestMethod.POST)public String executeTest(ModelMap model, ListData listData) { ModelAndView modelAndView = null
    3. JsonResponse jsonResponse = null
    4. modelAndView = executeTransaction(listData)
    5. model.addAttribute("paramName", modelAndView)
    6. } return "jsonView"
    7. }

    Positive Reactions
    1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
    2. Thanks a lot Boss!.
    3. Thanks but we are not using Gson.
    4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
    Other Reactions
    1. Point Number 2 is not related to gson, it is spring.
    2. I update the answer with all changes required.
    3. Or I need to do additional processing in controller?
    4. We are using Jackson.

  • Some information about how Spring MVC recive and use the Accept Header in these two case

    Your method is matching on any URI pattern that ends in json and in both cases your URL ends in json. If you want to filter on things that have an Accept header of JSON then I think you want to do something like this Please understand I typed the above from memory so you may need to tweak it a tad. details

    Reactions - Positive 2, Negative 0, Others 0

    1. @RequestMapping(value="/someUriPattern", headers = {"Accept=application/json"})

    Positive Reactions
    1. Ok,thank you very muchSo, are you sayng to me that if I would that my controller method manage only JSON object coming from my view I have to put the element "Accept=application/json" inside my RequestMapping annotation?
    2. What I am saying is that, if you want to limit calls to that method to only things that are requesting JSON, its probably a good idea to add the proper header (again, I typed that off of memory...please google to verify I didn't typo).

  • Serializing enums with Jackson

    also I found good workaround sedCommentId=306450&page=com.atlassian.jira.plugin.system.issuetabpanels comment-tabpanel#comment-306450. available since just tested it works with version 2.1.2 answer to TheZuck** I tried your example got Json My code and dependencies are . details

    Reactions - Positive 3, Negative 1, Others 0

    1. @RequestMapping(value = "/getEvent") @ResponseBody public EventContainer getEvent() { EventContainer cont = new EventContainer()
    2. cont.setEvents(Event.values())
    3. return cont
    4. }class EventContainer implements Serializable { private Event[] events
    5. public Event[] getEvents() { return events
    6. } public void setEvents(Event[] events) { this.events = events
    7. }

    Positive Reactions
    1. Upgraded to 3.2.1 and all is well now.
    2. Thanks!.
    3. Using on Mule 3.4.1 and it is working like a charm!.
    Negative Reactions
    1. found out what was wrong, I was using Jackson 2.1.2 but my Spring version was still 3.1 hence did not support this version.
    Other Reactions
    1. @JsonFormat(shape= JsonFormat.Shape.OBJECT)@JsonAutoDetect()public enum Event { VISIT_WEBSITE(Type.ADMIN); @JsonProperty public Type type; public Type getType() { return type; } Event(Type type) { this.type type; } public enum Type { ADMIN, CONSUMER, }}I'm using Jackson 2.1.2.
    2. I like this alternative, it's cleaner, however, I tried it with this class and type does not get serialized, any idea what's wrong?
    3. I've added additional details to body of answer.

  • org.springframework.web.bind.MissingServletRequestParameterException

    RequestParam has an attribute required which is true by default. If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(required = false) Integer answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
    2. }

  • org.springframework.web.bind.MissingServletRequestParameterException

    If answerId is not required change the annotation and parameter type as follows Edit Since answerId is a primitive value in your example you would also need to provide a defaultValue in the annotation. Providing a defaultValue implicitly sets required to false so I'll leave it out of the example Hope this helps . details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")@ResponseBodypublic void addCorrectAnswer(@RequestParam(defaultValue = 0) int answerId, @RequestParam String correct) { getAnswerDAC().addCorrectAnswer(answerId, correct)
    2. }

  • Java web framework with RESTful JSON services, HTML5 & jQuery ajax

    If your adamant about Java then look at Spring MVC as an alternative to Jax RS. With Spring and Jackson for JSON marshall/unmarshall you can do something like Hope that helps. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Controller@RequestMapping("/resource")public class ResourceController{ @Autowired private ResourceService resourceService
    2. @RequestMapping(value="/{id}", method=RequestMethod.GET) public @ResponseBody Resource getResource(@PathVariable Integer id) { return resourceService.lookup(id)
    3. } ...}public class Resource{ @JsonProperty("id") private int id
    4. @JsonProperty("resourceName") private String name
    5. ...}

  • Spring 3.1, JSON response ModelAndView

    Then you would need to tell JQuery to expect HTML or Text but not JSON. If what you want is json to update some parts of the page don't return a ModelAndView return String make sure to have a json serializer . details

    Reactions - Positive 1, Negative 0, Others 0

    1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html") public @ResponseBody String addSubMenu() { //yourvariable return yourvariable.toString()
    2. }

    Positive Reactions
    1. True, it will return a String, if an object is needed, replace String with your object and you can serialize it using jackson library for example.
    Other Reactions
    1. If you want to deliver some browser renderable code, I would delegate the view rendering to the View layer using ModelAndView (without the ReponseBody Annotation) as result.
    2. If you want to return an object, consider returning an Object and let Spring marshal it to JSON.
    3. This would deliver what ever you have in yourvariable.

  • Spring 3.1, JSON response ModelAndView

    Your server would like to serialize the ModelAndView Object as a JSON string and your jQuery code wants to append an HTML element to the DOM. There are a few things which could be wrong here By specifying a Content-type header of application/json you are expecting a response of json back however looking at the way you are handling the response it looks like what you want is an html if it is html that you are looking for as a response then remove the Content Type header from the request remove the ResponseBody annotation from ModelAndView response instead just return a view which points to a normal jsp which can create the html response that you are expecting . details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")public ModelAndView addSubMenu(@RequestBody Menu menu) {...}

    Other Reactions
    1. This would be my understanding of a partial.
    2. Then you would need to tell JQuery to expect HTML or Text but not JSON.
    3. This would deliver HTML Code (Model delivered form controller, view delivered from Template) to the client.

  • In Spring MVC, how can I set the mime type header when using @ResponseBody

    I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1 the implementation looks quite neat Comments First the mvc:annotation-driven or the EnableWebMvc must be reference/html/mvc.html#mvc-config-enable added to your application config. details

    Reactions - Positive 3, Negative 0, Others 0

    1. @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar")@ResponseBodypublic Bar fooBar(){ return myService.getBar()
    2. }

    Positive Reactions
    1. Thanks!.
    2. This answer should be number one, let Spring do the work for you!
    3. Worked great.
    Other Reactions
    1. !.

  • Generate JSON in JAVA

    put each row contents in a map . Essentially you want something like this This might need to be adjusted to meet your needs but it should at least show you how to do it. details

    Reactions - Positive 0, Negative 0, Others 0

    1. ModelMap [] rowMap = new ModelMap()[3]
    2. for (int i=0
    3. i<3
    4. i++){ ModelMap this_row=new ModelMap()
    5. this_row.put("id",i)
    6. this_row.put("name","name"+i)
    7. rowMap(i)=this_row
    8. }modelMap.put("rows",rowMap)

    Other Reactions
    1. I have an error in your first line The type of the expression must be an array type but it resolved to ModelMap.

  • Binding the nested json to @RequestBody object using Jackson converter

    The issue was fixed by adding below logic. Here your Java class DrugListJsonRequest should extend It doesn't require a any methods and constructors. details

    Reactions - Positive 0, Negative 0, Others 0

    1. public @ResponseBody String saveDrug(@RequestBody DrugListJsonRequest drugListCriterion) {}

  • java spring MappingJacksonJsonView not doing toString on mongodb ObjectId

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Bean(name = "jsonView")public MappingJacksonJsonView jsonView() { final MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView()
    2. mappingJacksonJsonView.setContentType("application/json")
    3. mappingJacksonJsonView.setObjectMapper(new CustomObjectMapper())
    4. return mappingJacksonJsonView
    5. }

  • Sending JSON to Spring MVC controller

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})

  • Sending JSON to Spring MVC controller

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

  • Sending JSON to Spring MVC controller

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping("/run/*")

  • Sending JSON to Spring MVC controller

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping("/run/")

  • Sending JSON to Spring MVC controller

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping("/run/*")

  • Sending JSON to Spring MVC controller

    However in your Controller class you do not have any method bound to this URL. Because you've annotated the class with and the method is annotated with the method is actually bound to the URL run/save which is neither the URL you are sending data to with nor the URL the form is pointing at. details

    Reactions - Positive 0, Negative 1, Others 0

    1. @RequestMapping("save")

    Negative Reactions
    1. sorry, it should be run/save but still same problem.
    Other Reactions
    1. Did you take my suggestion to turn up logging to examine exactly which methods are bound to exactly which URLs?
    2. matt b...bulls eye..i have also suggested the same answer...
    3. I don't think you need the in the @RequestMapping(/application/*).

  • JQuery, Spring MVC @RequestBody and JSON - making it work together

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/ajax/search/sync") public String sync(@RequestBody Foo json) {

  • Spring 3.0 making JSON response using jackson message converter

    Thx I have tried that before it isnt. In addition to the answers here if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody Foo json) {

  • Marshaling JSON and Generics in Java with Spring MVC

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. public @ResponseBody String setJobStatus(@RequestBody JobUpdateList jobUpdates) {

  • Marshaling JSON and Generics in Java with Spring MVC

    Your solution worked for me D tnx. I ended up creating another class So in the controller instead of i did this . details

    Reactions - Positive 0, Negative 0, Others 0

    1. public @ResponseBody String setJobStatus(@RequestBody List<JobUpdate> jobUpdates) {

  • Parsing json into java objects in spring-mvc

    Thanks!. if you are using jquery on the client side this worked for me Java Jquery you need to include Douglas Crockford's json2.js to have the JSON.stringify function) . details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestBody SearchRequest json) {

  • Jackson 2.0 with Spring 3.1

    or is this the official way to configure the Jackson converter. In this particular case I am configuring the converter to return dates in the ISO-8601 format . details

    Reactions - Positive 2, Negative 1, Others 0

    1. package foo.bar.JacksonConfig
    2. import com.fasterxml.jackson.databind.ObjectMapper
    3. import com.fasterxml.jackson.databind.SerializationFeature
    4. import org.springframework.beans.BeansException
    5. import org.springframework.beans.factory.config.BeanPostProcessor
    6. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
    7. @Componentpublic
    8. class JacksonConfig implements BeanPostProcessor {
    9. public Object postProcessBeforeInitialization(Object bean, String beanName)
    10. throws BeansException {
    11. return bean
    12. }
    13. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    14. if (bean instanceof MappingJackson2HttpMessageConverter) {
    15. MappingJackson2HttpMessageConverter jsonConverter =
    16. (MappingJackson2HttpMessageConverter) bean
    17. ObjectMapper objectMapper = jsonConverter.getObjectMapper()
    18. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
    19. jsonConverter.setObjectMapper(objectMapper)
    20. }
    21. return bean
    22. }
    23. }

    Positive Reactions
    1. @Ryan this works great.
    2. I'm sure that this is not the official way but it's very clever!.
    Negative Reactions
    1. The "official" method of configuring this is described here: URL_http://wallsofchange.wordpress.com/2013/02/02/spring-mvc-rest-services-force - jackson-to-serialize-dates-as-iso-8601-dates/.
    Other Reactions
    1. The only difference for Jackson 2 is that you have to use MappingJackson2HttpMessageConverter instead of MappingJacksonHttpMessageConverter and SerializationFeature.WRITE_DATES_AS_TIMESTAMPS instead of SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS.

  • spring mvc passing objects with post method

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. boolean createModel( @JsonArg SettlementModelGroup modelGroup, @JsonArg Integer periodId, @JsonArg Integer domainId, @JsonArg Integer modelTypeId )

  • Is it possible to repeat parameter RESTful Spring MVC?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value="/test/{tests}", method=RequestMethod.GET)@ResponseBodypublic String test(@PathVariable String tests){ String[] test= tests.split(",")
    2. return "sth"
    3. }

  • Jackson : Converting JSON property to nested Object with Dot Notation

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping("/saveChild.json")@ResponseBodypublic Child saveChild(@RequestBody Child child) { // do something with child return child
    2. }

  • springmvc using json response

    Then just return your item formattedDate. . details

    Reactions - Positive 3, Negative 3, Others 0

    1. @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString())
    2. Date date = new Date()
    3. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
    4. String formattedDate = dateFormat.format(date)
    5. model.addAttribute("serverTime", formattedDate )
    6. return "main"
    7. } @RequestMapping(value = "/serverTime", method = RequestMethod.GET) @ResponseBody public String serverTime(Locale locale, Model model) { Date date = new Date()
    8. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale)
    9. return dateFormat.format(date)
    10. }

    Positive Reactions
    1. You may be able to clean up some of the handling with something like [backbone.js]( URL_http://documentcloud.github.com/backbone/) , but it doesn't sound necessary in this case.And yes, it would not :)Bad copy-paste.
    2. Did you resolve your issue?
    3. Nope, I think doing that's just fine.
    Negative Reactions
    1. Ah, sorry about that.
    2. Do you think it's a bad idea to have the controller handle the views?
    3. That seems a bit nasty.
    Other Reactions
    1. Load your view at the root.
    2. also - I don't think that code would even compile with duplicate method names.
    3. Are you suggesting I go to one url for the JSON response and another for the html?
    4. Changed in the example just for future reference.
    5. Are you able to use AJAX?Load your view, main, then make the request for the JSON data.
    6. Yeah my AJAX request basically makes the request to the controller for the page it should go to, which it does, but it should also return a payload of JSON.
    7. Is there any XML I need to annotate so that the response comes back as JSON rather than just a String?
    8. Is it possible to do both?
    9. I see you marked it as an answer.
    10. Or did you still need help with that?
    11. Ah, I did this, but you will notice on the bottom line of my question, this breaks the way my views are returned.
    12. I've included jackson-core-asl in my pom.xml.
    13. Ah I see, so I have to use two endpoints, can you think of anyway I could improve my design?
    14. Then your view should make an ajax request for the data at /serverTime.
    15. Updated with an example.

  • springmvc using json response

    I see you marked it as an answer. There's a library for converting Java objects to JSON called gson gson/ Incidentally if you're wanting to send an Ajax response rather than refreshing the page add ResponseBody to your method declaration and return your JSON string assuming you're not updating your model if this is the case). details

    Reactions - Positive 1, Negative 0, Others 0

    1. public @ResponseBody String home(Locale locale, Model model) { .. }

    Positive Reactions
    1. Ah, if you notice the bottom of my question, this looks like it will break my view handling as it returns the view "main", is it possible to do this JSON response and keep handling my views within the controller?
    Other Reactions
    1. I think BrandonV has answered this.

  • Spring JSON request getting 406 (not Acceptable)

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)

  • Spring JSON request getting 406 (not Acceptable)

    You're probably fine then sorry I couldn't be more help on this. In the controller shouldn't the response body annotation be on the return type and not the method like so I'd also use the raw jquery.ajax function and make sure contentType and dataType are being set correctly. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){ Weather weather = weatherService.getCurrentWeather(id)
    2. return weather
    3. }

    Other Reactions
    1. The placement of @ResponseBody should not matter...
    2. I will look into GSON...but still would like this JSON to work if possible.

  • automatically choose viewResolver based on request url?

    Thx . Use a PathVariable in your handler method use that to toggle which view to use View type could be vm or jsp or whatever. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping("/myapp/{viewtype}/view.do")public String myHandler( @PathVariable String viewtype, Model model) { // do stuff return "viewname." + viewtype
    2. }

  • Redirect at @ResponseBody?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value="/postLogout.html", method=RequestMethod.GET)@ResponseBody public MyreturnObject getPostLogout(){ return new ReturnObject(true,true,false)
    2. }

  • Parsing JSON in Spring MVC using Jackson JSON

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping("somepath")@ResponseBodypublic Fozzle doSomeThing(@RequestBody Fizzle input){ return new Fozzle(input)
    2. }

  • JQuery, Spring MVC @RequestBody and JSON - making it work together

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @Controller
    2. @RequestMapping("/test")
    3. public class TestController {
    4. @RequestMapping(method = RequestMethod.POST, value = "math")
    5. @ResponseBody
    6. public Result math(@RequestBody final Request request) {
    7. final Result result = new Result()
    8. result.setAddition(request.getLeft() + request.getRight())
    9. result.setSubtraction(request.getLeft() - request.getRight())
    10. result.setMultiplication(request.getLeft() * request.getRight())
    11. return result
    12. }
    13. }

  • Spring REST multiple @RequestBody parameters, possible?

    I'm pretty sure that won't work. There may be a workaround but the much easier way would be to introduce a wrapper Object and change your signature . details

    Reactions - Positive 1, Negative 0, Others 0

    1. public class PersonContext{ private UserContext userContext
    2. private Person person
    3. // getters and setters}public Person createPerson(@RequestBody PersonContext personContext)

    Positive Reactions
    1. Thanks, I'm considering a wrapper Array as the last resort.
    Other Reactions
    1. What is the work around you were referring to?
    2. @Srirangan I said there may be a workaround.
    3. @Srirangan: the workarround is the PersonContext class - it is some kind of DTO.
    4. I am not aware of one myself.

  • Spring MVC returning JSONS and exception Handling

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @ResponseBody public Response getUserDetails) { //... return new Response(userDetails)
    2. }

  • Spring MVC returning JSONS and exception Handling

    Return a model and a view instead. To add the exception you'd do it the same way with a key and success false. details

    Reactions - Positive 3, Negative 1, Others 0

    1. public ModelMap getUserDetails() { UserDetails userDetails
    2. // get this object from somewhere ModelMap map = new ModelMap()(
    3. map.addAttribute("data", userDetails)
    4. map.addAttribute("success", true)
    5. return map
    6. }

    Positive Reactions
    1. Brain fart from returning views as well.
    2. I don't see what value ModelAndView adds here.
    3. I am unsure of why I would want to use a ModelAndView however you gave me the idea of using a map (HashMap) which worked like a charm and gave me the desired output.
    Negative Reactions
    1. However how do I do the same in a fail scenario?
    Other Reactions
    1. Why not just return the ModelMap?
    2. @milindaD ModelMap doesn't require keys but not much different.
    3. @skaffman You're right.
    4. However any idea of a way to centralize this when for all controllers and all functions in the controllers?
    5. It implements Map.

  • RESTful MySQL / Terminology / Passing Parameters / Returning Ints & Doubles

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/people/gender/{gender}/updated/{lastUpdated}", method = RequestMethod.GET)@ResponseBodypublic Person findByGenderAndUpdated(@PathVariable String gender, @PathVariable String lastUpdated) {}

  • Using Spring and Jackson to Render JSON without affecting all Views

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/test/data")@ResponseBodypublic TestFormData dostuff() { TestFormData data = new TestFormData()
    2. data.setName("myname")
    3. return data
    4. }

  • Interfaces and @RequestBody

    Sure thing my apologies!. I'm not sure it would work but you can try to make it generic . details

    Reactions - Positive 3, Negative 0, Others 0

    1. public interface BookableResourceController<R extends BookableResource> {
    2. @RequestMapping(value = "/delete.html", method = RequestMethod.POST)
    3. public ModelAndView processDeleteResource(@RequestBody R resource)
    4. }

    Positive Reactions
    1. I'm not too well versed in generics, so I never would have thought of this.
    2. Thank you for the quick response!.
    3. That worked beautifully!

  • In Spring MVC, how can I set the mime type header when using @ResponseBody

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public View fooBar(){ return new JsonView(myService.getJson())
    2. }

  • In Spring MVC, how can I set the mime type header when using @ResponseBody

    According to the spring doc framework-reference/html/mvc.html#mvc-ann-httpentity reference/html/mvc.html#mvc-ann-httpentity The HttpEntity is similar to RequestBody and ResponseBody. Besides getting access to the request and response body HttpEntity and the response-specific subclass ResponseEntity also allows access to the request and response headers The code will look like . details

    Reactions - Positive 7, Negative 2, Others 0

    1. @RequestMapping(method=RequestMethod.GET, value="/fooBar") public ResponseEntity<String> fooBar2() { String json = "jsonResponse"
    2. HttpHeaders responseHeaders = new HttpHeaders()
    3. responseHeaders.setContentType(MediaType.APPLICATION_JSON)
    4. return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED)
    5. }

    Positive Reactions
    1. See if your import is correct and your libraries are updated.
    2. That's the nicest one so far, thanks (+1).
    3. Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping.
    4. If I could vote for this multiple times, I would!.
    5. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").
    6. This works great.
    7. now it works fine if not using ResponseEntity.
    Negative Reactions
    1. I needed a way to return a string that was already in JSON format and tell spring not to mess with it.
    2. hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object?
    Other Reactions
    1. @Lince81 org.springframework.http.HttpHeaders is not an abstract class ( URL_http://static.springsource.org/spring/docs/3.0.x/javadoc - api/org/springframework/http/HttpHeaders.html).
    2. If you want Spring to serialize an Object (as XML, JSON, etc) use @ResponseBody and configure the appropiate MessageConverters (see link in the answer).
    3. @Lince81 the point of the example is returning an already serialized object as a String while setting a different Content-Type.

  • In Spring MVC, how can I set the mime type header when using @ResponseBody

    Register org.springframework.http.converter.json.MappingJacksonHttpMessageConverter as the message converter and return the object directly from the method. and the controller . details

    Reactions - Positive 1, Negative 0, Others 0

    1. @RequestMapping(method=RequestMethod.GET, value="foo/bar")public @ResponseBody Object fooBar(){ return myService.getActualObject()
    2. }

    Positive Reactions
    1. Yes, probably a best practice, but as I wrote my objects are already JSON strings and I just want to write them out with the correct mime type.
    Other Reactions
    1. org/springframework/spring-webmvc should cover it.
    2. What are the maven dependencies for the beans you are referencing?

  • In Spring MVC, how can I set the mime type header when using @ResponseBody

    org/springframework/spring-webmvc should cover it. You may not be able to do it with ResponseBody but something like this should work . details

    Reactions - Positive 0, Negative 0, Others 0

    1. package xxx
    2. import java.io.ByteArrayOutputStream
    3. import java.io.IOException
    4. import javax.servlet.http.HttpServletResponse
    5. import org.springframework.web.bind.annotation.RequestMapping
    6. import org.springframework.web.bind.annotation.RequestMethod
    7. @Controllerpublic
    8. class FooBar {
    9. @RequestMapping(value = "foo/bar", method = RequestMethod.GET)
    10. public void fooBar(HttpServletResponse response) throws IOException {
    11. ByteArrayOutputStream out = new ByteArrayOutputStream()
    12. out.write(myService.getJson().getBytes())
    13. response.setContentType("application/json")
    14. response.setContentLength(out.size())
    15. response.getOutputStream().write(out.toByteArray())
    16. response.getOutputStream().flush()
    17. }
    18. }

    Other Reactions
    1. would he need to write to the response, or just setting the header would do?

  • Spring 3.0 making JSON response using jackson message converter

    3. Use as the following This works for me. details

    Reactions - Positive 1, Negative 0, Others 0

    1. @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })public @ResponseBody Foo method(@Valid Request request, BindingResult result){return new Foo(3,4)}

    Positive Reactions
    1. @ResponseBody is applied to return type - this was my issue, thanks!.
    Other Reactions
    1. Providing that, as you suggest, is important.
    2. The key part here, I think, is that the OP doesn't have a RequestMapping.
    3. For testing your post requests with Curl or upgrading to spring 3.2 checkout [here]( URL_http://stackoverflow.com/questions/16909742/spring-3-2-0-web-mvc-rest - api-and-json2-post-requests-how-to-get-it-right-onc).
    4. @GaryF updated my answer.

  • Spring MVC AJAX and JSON using Custom View Resolver, and Custom View

    I'm not sure the path of my form submission and there obviously is no JSP view for it I'm expecting JSON to be returned actually but for some reason this isn't working it's just trying to forward me to some JSP so I'm guessing that I need to specify how to handle this in my XML but I've seen about 1000 different ways that people return JSON and all of them are very confusing to me I'm just looking for the simplest way so I can take it from there edit I added an answer which is a good start but it allows you to type json after any URL and it will do some really bad things if as the controller I'm not expecting it so I need to somehow have this view resolver only apply to secured URLs . Ok finally after trying a million combinations and then this I don't really understand how I can return an object from here. details

    Reactions - Positive 0, Negative 0, Others 0

    1. @RequestMapping(value = "/test/data") public TestFormData dostuff() { TestFormData data = new TestFormData()
    2. data.setName("myname")
    3. return data
    4. }