HttpServletRequest获取URL,URI方法详解

HttpServletRequest可以分别获取完整的URL,URL路径以及URL后面的参数等。

方法

1、request.getRequestURL()    //返回的是完整的url,包括Http协议,端口号,servlet名字和映射路径,但它不包含请求参数。

2、request.getRequestURI()    //得到的是URL的前部分值

3、request.getContextPath()    //返回url主体

4、request.getServletPath()    //返回调用servlet的部分url.

5、request.getQueryString()    //返回url路径后面的查询字符串

例子

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  

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。