【问题标题】:Access HttpServletRequest object from Jackson custom deserializer从 Jackson 自定义反序列化器访问 HttpServletRequest 对象
【发布时间】:2012-07-07 06:38:35
【问题描述】:

我正在尝试使用 JSON 有效负载通过 ajax POST 发送对象;这个对象引用了存储在数据库中的其他对象,由 Hibernate 处理;我需要访问这个数据库来解析其他对象引用并将它们存储在获得反序列化请求的 JSON 有效负载的新对象中。

现在,我必须访问 HttpServletRequest 属性以获取保存的休眠会话以用于访问数据库。有可能吗?

处理请求的控制器如下:

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

我必须能够获取请求属性“hibernate_session”的反序列化器是一个自定义反序列化器,已注册到 Jackson,如下所示:

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;
    }

}

如果需要,我会发布更多代码。

谢谢

【问题讨论】:

  • 发送 ajax 帖子到哪个服务器组件?是servlet还是别的什么?
  • 是的,它是一个 servlet。 Ajax post 指向由 Spring 映射的方法,并且使用 @RequestBody 注释对参数进行注释。这个参数是发送的 json 将被反序列化到的地方。我现在在问题中发布一个示例。
  • 有些事情有效,我会检查所有我必须做的,我会告诉你。如果你愿意,你可以用stackoverflow.com/a/1795931/41977的解决方案1填写答案现在我会检查如果一切正常。谢谢

标签: json spring hibernate servlets jackson


【解决方案1】:

您可以尝试以下方法

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder

                .getRequestAttributes()).getRequest();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    相关资源
    最近更新 更多