Получить корневой / базовый Url в Spring MVC
каков наилучший способ получить корневой / базовый url веб-приложения в Spring MVC?
Базовый Url = http://www.example.com или http://www.example.com/VirtualDirectory
9 ответов
Если базовый url-адрес"http://www.example.com", затем используйте следующее, Чтобы получить"www.example.com "часть, без" http://":
от контроллера:
@RequestMapping(value = "/someURL", method = RequestMethod.GET)
public ModelAndView doSomething(HttpServletRequest request) throws IOException{
//Try this:
request.getLocalName();
// or this
request.getLocalAddr();
}
из JSP:
объявите это поверх вашего документа:
<c:set var="baseURL" value="${pageContext.request.localName}"/> //or ".localAddr"
затем, чтобы использовать его, ссылаться на переменную:
<a href="http://${baseURL}">Go Home</a>
вы также можете создать свой собственный метод, чтобы получить его:
public String getURLBase(HttpServletRequest request) throws MalformedURLException {
URL requestURL = new URL(request.getRequestURL().toString());
String port = requestURL.getPort() == -1 ? "" : ":" + requestURL.getPort();
return requestURL.getProtocol() + "://" + requestURL.getHost() + port;
}
в контроллере используйте HttpServletRequest.getContextPath()
.
в JSP используйте библиотеку тегов Spring: или jstl
либо впрыснуть UriCompoenentsBuilder
:
@RequestMapping(yaddie yadda)
public void doit(UriComponentBuilder b) {
//b is pre-populated with context URI here
}
. Или сделать это самостоятельно (аналогично Салиму ответа):
// Get full URL (http://user:pwd@www.example.com/root/some?k=v#hey)
URI requestUri = new URI(req.getRequestURL().toString());
// and strip last parts (http://user:pwd@www.example.com/root)
URI contextUri = new URI(requestUri.getScheme(),
requestUri.getAuthority(),
req.getContextPath(),
null,
null);
затем вы можете использовать UriComponentsBuilder из этого URI:
// http://user:pwd@www.example.com/root/some/other/14
URI complete = UriComponentsBuilder.fromUri(contextUri)
.path("/some/other/{id}")
.buildAndExpand(14)
.toUri();
просто :
String getBaseUrl(HttpServletRequest req) {
return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
}
@RequestMapping(value="/myMapping",method = RequestMethod.POST)
public ModelandView myAction(HttpServletRequest request){
//then follow this answer to get your Root url
}
Если вам это нужно в jsp, то войдите в контроллер и добавьте его как объект в ModelAndView.
кроме того, если вам это нужно на стороне клиента, используйте javascript для его извлечения: http://www.gotknowhow.com/articles/how-to-get-the-base-url-with-javascript
думаю ответ на этот вопрос:Поиск URL вашего приложения только с ServletContext показывает, почему вы должны использовать относительный url вместо этого, если у вас нет очень конкретной причины для получения корневого url.
в JSP
<c:set var="scheme" value="${pageContext.request.scheme}"/>
<c:set var="serverPort" value="${pageContext.request.serverPort}"/>
<c:set var="port" value=":${serverPort}"/>
<a href="${scheme}://${pageContext.request.serverName}${port}">base url</a>