Access HttpServletRequest object from Jackson custom deserializer

hibernate, jackson, json, servlets, spring

Solution

You may try following approach

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder

                .getRequestAttributes()).getRequest();

Problem

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

Original source

Related problems