您的位置:首页 > 其它

在Servlet中获取Web路径和文件真实路径

2017-05-24 18:47 232 查看

在Servlet中获取Web路径和文件真实路径

在servlet中,使用HttpServletRequest对象中的一系列方法可以获取相关路径的信息,然后可以根据

这些信息组合成一个Web站点的虚拟路径。HttpServletRequest接口中提供的用于获取路径有关的信息的方法如下:

getScheme():返回请求协议(http).

getServerName():返回服务器的名称。如果访问本机,则返回的是localhost。

getServerPort():返回服务器的端口号。Tomcat服务器的默认端口为8080.

getContextPath():返回客户端所请求的Web应该的URL入口。例如,在浏览器中访问http://localhost:8080/helloapp/getpath,该方法返回的是“/helloapp”;

getRequestURL():返回请求Web服务器的完全路径。例如,在浏览器中访问http://localhost:8080/149/getpath,该方法直接返回的是:http://localhost:8080/149/getpath这个路径。

获取文件的真实路径,可以使用ServletContext接口的getRealPath(String path)方法,该方法根据参数指定的虚拟路径,返回文件在系统中的真实路径,这个路径主要是指发布在Tomcat服务中的文件路径。例如,找到index.jsp文件的真实路径,这个路径主要是指发布在Tomcat服务中的文件路径。例如,找出index.jsp 文件的真实路径的写法为getRealPath(“index.jsp”),那么反悔的真实路径为“D:\Program File\apche-tomcat-7.0.41\webapps\149\index.jsp”。

一、新建名为GetPathServlet的servlet类,在该类的doPost()方法中获取Web服务器的路径以及文件的真实路径。

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 GetPathServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
String scheme = request.getScheme();    // 获取请求协议(http)
String serverName = request.getServerName();    //获取服务器名称(localhost)
int serverPort = request.getServerPort();   // 获取服务器端口号
String contextPath = request.getContextPath();  // 返回Web应用的URL入口
// 访问路径
String path = scheme + "://" + serverName + ":" + serverPort + contextPath + "/";
// getRealPath()方法返回一个给定虚拟路径的真实路径
// 这里的真实路径只能是WebRoot下直接的文件,不能包含子文件夹。因为此处的真实路径即为:server真实路径+文件名。
String realPath = this.getServletContext().getRealPath("index.jsp");
// 设置HTTP响应的正文的MIME类型以及字符编码格式
request.setAttribute("path",path);  // 将Web路径添加到request对象中
request.setAttribute("realPath", realPath); // 将真实路径添加到request对象中
request.getRequestDispatcher("path.jsp").forward(request, response);
}

}


二、新建path.jsp页,在该页中获得请求中保存的路径信息并显示。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="GetPathServlet" method="post">
<input type="submit" value="提 交"/>
</form>
<table align="center">
<tr>
<td>Web路径:</td>
<td><%=(String)request.getAttribute("path") %></td>
</tr>
<tr>
<td>真实路径:</td>
<td><%=(String)request.getAttribute("realPath") %></td>
</tr>
</table>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: