javaweb 获取请求文件绝对路径问题-getServletPath();

yzmm
887 阅读
在之前获取绝对路径用了WEB路径+RequestURI:jsp获取真实或虚拟文件绝对路径,发现这种做法麻烦而又不准确。当请求http://xxx.com/test/假设test下有index.jsp那么request.getRequestURI()是取不到index.jsp的请求的。这时候最好使用:request.getServletPath(),此方法可以获取请求的servlet路径。

getServletPath

java.lang.String getServletPath()

Returns the part of this request's URL that calls the servlet. This path starts with a "/" character and includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME.

This method will return an empty string ("") if the servlet used to process this request was matched using the "/*" pattern.

Returns:

a String containing the name or path of the servlet being called, as specified in the request URL, decoded, or an empty string if the servlet used to process the request is matched using the "/*" pattern.

简单封装了下获取当前请求文件绝对路径方法:

    /**
     * 获取web目录,Weblogic 默认以war包部署的时候不能用getRealPath
     * getResource("/")获取的是当前应用所在的类路径,截取到WEB-INF
     * 之后的路径就是当前应用的web根目录了
     * @param request
     * @return
     */
    public String getDocumentRoot(HttpServletRequest request){
    	String webRoot = request.getSession().getServletContext().getRealPath("/");
    	if(webRoot == null){
    		webRoot = this.getClass().getClassLoader().getResource("/").getPath();
    		webRoot = webRoot.substring(0,webRoot.lastIndexOf("WEB-INF"));
    	}
	    return webRoot;
    }
    /**
     * 获取请求文件的绝对路径,getServletPath()更加准确。访问目录可以获取到具体的索引文件
     * 如访问/test,test目录下存在index.jsp getServletPath()可获取到只有的请求文件URL
     * @param request
     * @return
     */
    public String getHttpRequestFileRealPath(HttpServletRequest request) {
    	String documentRoot = getDocumentRoot(request)+"/"+request.getServletPath();
        return documentRoot.replaceAll("\\\\", "/").replaceAll("/+", "/");
    }

评论 (1)

botak
在jspy这个shell里面写的很详细 <p>SHELL_NAME = request.getServletPath().substring(request.getServletPath().lastIndexOf("/")+1);</p> <p> String myAbsolutePath = application.getRealPath(request.getServletPath());</p> <p> if (Util.isEmpty(myAbsolutePath)) {//for weblogic</p> <p> SHELL_NAME = request.getServletPath();</p> <p> myAbsolutePath = new File(application.getResource("/").getPath()+SHELL_NAME).toString();</p> <p> SHELL_NAME=request.getContextPath()+SHELL_NAME;</p> <p> WEB_ROOT = new File(application.getResource("/").getPath()).toString();</p> <p> } else {</p> <p> WEB_ROOT = application.getRealPath("/");</p> <p> }</p>

发表评论