zoukankan      html  css  js  c++  java
  • 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.13webappsWebDemo 

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

    getRequestURI:/WebDemo/welcome.jsp 

    getRequestQueryString: userName=Jhon

    getRemoteUser:null  

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

  • 相关阅读:
    Windows 7 Phone 文档数据库Rapid Repository正式发布
    Adobe展示HTML5动画制作IDE
    详解Android实现全屏正确方法
    qtform.com计划
    Adobe加速布局移动开发:Flash Builder+Flex+AIR+Catalyst
    预览:Visual Basic与C#中的异步语法
    Windows 7主题中的壁纸从哪里来?
    F#的编译器及标准库使用Apache 2.0协议开源(暂时还没有看到未来)
    开发者谈Symbian、iPhone、Android、MeeGo平台
    MeeGo 1.1发布
  • 原文地址:https://www.cnblogs.com/SaraMoring/p/5708058.html
Copyright © 2011-2022 走看看