我在Spring MVC中有一個場景,我必須在handleRequest方法中顯式拋出Exception。拋出異常作爲來自Spring handleRequest方法的響應
例如,
public class AdminController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// for some request parameter this is run. For Eg. reqParam=xyz
undeployTables();
}
public void undeployTables() throws Exception {
throw new Exception("Undeploy Exception");
}
現在假設春天servlet和URL映射配置在web.xml中,當我試圖通過URL http://localhost:8080/server/admin?reqParam=xyz
訪問servlet中,我得到網頁上的正確的錯誤。 java.lang.Exception: Undeploy failed....
但是,當我試着通過了HTTPClient訪問碼,即通過Java代碼在客戶端的響應是不是能趕上這個例外,只有我得到的是HTTP 401內部錯誤的響應object.But什麼我想在客戶端有一個Exception對象。
代碼是:
HttpPost httppost = new HttpPost(url.toURI());
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
logger.info("executing request " + httppost.getURI()); //$NON-NLS-1$
// Create a response handler
HttpResponse response = httpclient.execute(httppost);// expect exception to be thrown here
statusCode = response.getStatusLine().getStatusCode();
能否請您讓我知道的變化應該做到讓客戶端上的異常可能會被卡住。
我可以谷歌,但無法找到合適的答案。
什麼如果servlet直接拋出異常? HTTPClient是否可以捕獲異常作爲響應?這不正確嗎? – chaosguru 2012-07-20 08:18:40
不,它不是Java調用Java,它是Java調用Web服務 - Web服務恰好也是在Java中實現的......如果您想要返回錯誤,則需要使用HTTP來執行此操作。 – MattR 2012-07-20 10:30:22