2012-07-06 65 views
1

我想通過使用JSON負載的ajax POST發送對象;該對象引用了存儲在數據庫中的其他對象,由Hibernate處理;我需要訪問這個數據庫來解析其他對象引用,並將它們存儲到獲取的請求的JSON有效負載的反序列化的新對象中。從Jackson定製解串器訪問HttpServletRequest對象

現在,我必須訪問HttpServletRequest屬性才能獲得保存的hibernate會話以用於訪問數據庫。可能嗎?

是處理請求的控制器如下:

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

,我必須能夠獲得請求屬性「hibernate_session」是一個自定義解串器,註冊到傑克遜和解串如下:

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

} 

如有需要,我會發布更多的代碼,如果需要的話。

感謝

+0

發送Ajax後,其服務器組件?它是servlet還是其他的東西? – kosa 2012-07-06 19:20:20

+0

是的,它是一個servlet。 Ajax post被引導到一個由Spring映射的方法,並且一個參數被註釋爲「@ RequestBody」註解。這個參數是json發送的序列化的地方。我現在在問題中發佈一個示例。 – gc5 2012-07-06 19:26:19

+0

一些工作,我會檢查所有我必須做的,我會讓你知道..如果你想你可以填寫一個解決方案1 ​​http://stackoverflow.com/a/1795931/41977 現在我會檢查一切是否正常。謝謝 – gc5 2012-07-06 19:48:03

回答

3

你可以試試下面的辦法

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder 

       .getRequestAttributes()).getRequest();