2016-10-10 54 views
1

Jersey文檔給出how to inject HttpSession on resources的示例。我應該如何注入(或以其他方式獲得)在「Content-Type:application/x-www-form-urlencoded」請求上發送的表單參數?我看到這些通過爲parameters on methods, and do not seem to be annotated,讓我相信這裏有一些怪癖?注入多值注入提供者(application/x-www-form-urlencoded)

的(幼稚)工廠我目前正在執行如下工作,JerseyHttpServletRequestWrapper是我自己的一類:

import org.glassfish.hk2.api.Factory; 

import javax.inject.Inject; 
import javax.servlet.http.HttpServletRequest; 
import javax.ws.rs.core.MultivaluedMap; 

public class JerseyHttpServletRequestWrapperFactory implements Factory<JerseyHttpServletRequestWrapper> { 
    private final HttpServletRequest request; 
    private final MultivaluedMap<String, String> formParams; 

    @Inject 
    public JerseyHttpServletRequestWrapperFactory(HttpServletRequest request, MultivaluedMap<String, String> formParams) { 
     this.request = request; 
     this.formParams = formParams; 
    } 

    @Override 
    public JerseyHttpServletRequestWrapper provide() { 
     return new JerseyHttpServletRequestWrapper(request, formParams); 
    } 

    @Override 
    public void dispose(JerseyHttpServletRequestWrapper jerseyHttpServletRequestWrapper) { 
    } 
} 

我想在這裏,實體提供商應注入實例以便我可以檢查實際上是否有與請求一起發送的實體。嘗試直接注入MultivaluedMap錯誤出具有:

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=MultivaluedMap<String,String>,parent=JerseyHttpServletRequestWrapperFactory,qualifiers={},position=1,optional=false,self=false,unqualified=null,2067821943) 
+0

這不是你應該問的那種問題。您需要向我們展示您迄今爲止所做的工作 - 給我們一些代碼。 –

回答

2

當你

@POST 
public Response post(MultivaluedMap<String, String> params) {} 

這種方法參數注入比定期現場/構造器注入不同的處理。所以你不能試圖將MultivaluedMap注入一個領域。

你可以做什麼雖然是注入ContainerRequest,然後閱讀正文。你需要檢查它是一個POST請求,而Content-Type是application/x-www-form-urlencoded。如果你不這樣做,當你嘗試閱讀實體時,你有可能會遇到異常。

@Inject 
ContainerRequest request; 

if (request.getMethod().toUpperCase().equals("POST") 
    && request.getMediaType().equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) { 
    request.bufferEntity(); 
    Form form = request.readEntity(Form.class); 
    MultivaluedMap<String, String> params = form.asMap(); 
}