HttpServletRequest获取URL的相关方法主要有以下几个:
String url = request.getRequestURL().toString();
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String localAddr = request.getLocalAddr();
int localPort = request.getLocalPort();
String servletPath = request.getServletPath();
为了更直观,直接拿示例url:http:localhost:8080/project/example演示
各方法获取到的内容:
request.getRequestURL()
: http:localhost:8080/project/example
request.getRequestURI()
: /project/example
request.getContextPath()
: /project
request.getLocalAddr()
: localhost
request.getLocalPort()
: 8080
request.getServletPath()
: /example
综上,如果想要获取服务器地址http:localhost:8080/project,以下代码即可:
String url = request.getLocalAddr()+":" + request.getLocalPort() + request.getContextPath();