3

I am trying to send an object via an ajax POST using JSON payload; this object has references to other objects stored in a database, handled by Hibernate; I need to access this database to resolve other objects references and store them in the new object obtained deserializing JSON payload of request.

Now, I have to access HttpServletRequest attribute in order to get a saved hibernate session to use to access to database. Is it possible?

The controller that handle the request is the following:

@RequestMapping(value = "/newproduct", method = RequestMethod.POST)
public @ResponseBody
Integer newProduct(HttpServletRequest request, @RequestBody Product product)
{
    //Controller code here
}

The deserializer where I have to be able to get request attribute "hibernate_session" is a custom deserializer, registered to Jackson and is the following:

public class ProductDeserializer extends JsonDeserializer<Product>
{

    @Override
    public Product deserialize(JsonParser jpar, DeserializationContext arg1)
        throws IOException, JsonProcessingException
    {

            Product newProduct = new Product();
            // I want to get request attribute or open a new hibernate session here 
            return newProduct;
    }

}

If necessary I'll post more code if needed.

Thanks

gc5
  • 9,468
  • 24
  • 90
  • 151
  • Sending ajax post to which server component? Is it servlet or something else? – kosa Jul 06 '12 at 19:20
  • Yes it is a servlet. Ajax post is directed to a method mapped by Spring and a param is annotated with the `@RequestBody` annotation. This param is where the json sent will be deserialized into. I am posting an example in the question right now. – gc5 Jul 06 '12 at 19:26
  • Some things work, I'll check all I have to do and I'll let you know.. If you want you can fill an answer with solution 1 of http://stackoverflow.com/a/1795931/41977 Now I'll check if everything works. Thanks – gc5 Jul 06 '12 at 19:48

1 Answers1

6

You may try following approach

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder

                .getRequestAttributes()).getRequest();
kosa
  • 65,990
  • 13
  • 130
  • 167