2012-04-30 29 views
2

我正在我的本地主機的應用程序信息,端口8080的基本網址爲:http://localhost:8080/EMSApplication/otherparts ...提取上下文路徑和等人從URL HttpServletRequest的

現在從HttpServletRequest我怎麼能提取部分http://localhost:8080/EMSApplication

目前,我這樣做:

String schema = request.getScheme(); 
String serverName = request.getServerName(); 
int serverPort = request.getServerPort(); 
String contextPath = request.getContextPath(); 
String path = schema + "://" + serverName + ":" + serverPort + contextPath; 
System.out.println(path); 

這裏的要求是HttpServletRequest實例。

這個程序是否正確?

是否有任何其他方式獲取信息?

如果我託管我的應用程序,並說網址是http://my.domain.com/EMSApplication/otherparts ...那麼上述程序代碼將工作?


另一種方式,我發現:

String requestUrl = request.getRequestURL().toString(); 
String contextPath = request.getContextPath(); 
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length()); 

,我需要這樣的:

HttpServletRequest request = (HttpServletRequest) getRequest().getContainerRequest(); 
String requestUrl = request.getRequestURL().toString(); 
String contextPath = request.getContextPath(); 
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());   
submitLink.add(new WebMarkupContainer("submitImage").add(new AttributeModifier("src", path + "/ASSETS/css/images/login-btn.png"))); 

我開發一個Wicket的應用程序,我需要指定一個<img/>的SRC。

回答

2

無論哪種方式都很好,但我更喜歡第一種。沒有什麼更直接的想法,但如果你解釋了爲什麼你想要這個價值,可能會有。

+0

謝謝。我已經更新了我的答案以解釋這種情況。你能告訴我爲什麼你會喜歡第一個嗎? –

+0

我更喜歡第一個,因爲上下文路徑是一個零長度的字符串,因此第二個會破壞根環境。考慮到你在做什麼,可能會進行一些優化以節省多次執行相同的操作,但是在Servlet API中沒有什麼可以幫助的。 –