HttpServletRequest获取URL、URI

从Request对象中可以获取各种路径信息,以下例子:

假设请求的页面是index.jsp,项目是WebDemo,则在index.jsp中获取有关request对象的各种路径信息如下

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class test extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter(); String getContextPath = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+getContextPath+"/";
String getRemoteAddress=request.getRemoteAddr();
String getServletPath =request.getServletPath();
String getServletContext_getRealPath =request.getServletContext.getRealPath("/");
String getRequestURL =request.getRequestURL().toString();
String getRequestURI =request.getRequestURI();
String getQueryString =request.getQueryString();
String getRemoteUser =request.getRemoteUser();
out.println("getContextPath:"+ getContextPath +"<br>");
out.println("basePath:"+basePath+"<br>");
out.println("getRemoteAddress:"+ getRemoteAddress +"<br>");
out.println("getServletPath:"+ getServletPath +"<br>");
out.println("getServletContext_getRealPath:"+ getServletContext_getRealPath +"<br>");
out.println("getRequestURL:"+ getRequestURL +"<br>");
out.println("getRequestURI:"+ getRequestURI +"<br>");
out.println("getQueryString:"+ getQueryString +"<br>");
out.println("getRemoteUser:"+ getRemoteUser +"<br>");
}
}

结果:

getContextPath:/WebDemo

basePath:http://localhost:8683/WebDemo/

getRemoteAddress:127.0.0.1

getServletPath:/ welcome.jsp

getServletContext_getRealPath:D:\apache-tomcat-6.0.13\webapps\WebDemo\

getRequestURL: http://localhost:8683/WebDemo/welcome.jsp

getRequestURI:/WebDemo/welcome.jsp

getRequestQueryString: userName=Jhon

getRemoteUser:null

注意:
request.getServletContext().getRealPath("/")等价于request.getRealPath("/"),但是request.getRealPath("/")方法现在已经被移除。

上一篇:Spring整合MongoDB(转)


下一篇:你应该知道的jQuery技巧