Java如何获取servlet请求URL信息?
在下面的示例中,我们提取有关请求对象路径信息的信息。我们提取协议用户,服务器及其分配的端口号。我们提取应用程序上下文路径,servlet路径,路径信息和查询字符串信息。如果我们结合以下所有信息,将获得与相等的信息request.getRequestURL()。
package org.nhooo.example.servlet;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ServletUrlInformation extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// 获取servlet请求URL
String url = request.getRequestURL().toString();
// 获取servlet请求查询字符串。
String queryString = request.getQueryString();
// 在没有主机名的情况下获取请求信息。
String uri = request.getRequestURI();
// 下面我们提取有关请求对象路径的信息
// 信息。
String scheme = request.getScheme();
String serverName = request.getServerName();
int portNumber = request.getServerPort();
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
String query = request.getQueryString();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("Url: " + url + "<br/>");
pw.print("Uri: " + uri + "<br/>");
pw.print("Scheme: " + scheme + "<br/>");
pw.print("Server Name: " + serverName + "<br/>");
pw.print("Port: " + portNumber + "<br/>");
pw.print("Context Path: " + contextPath + "<br/>");
pw.print("Servlet Path: " + servletPath + "<br/>");
pw.print("Path Info: " + pathInfo + "<br/>");
pw.print("Query: " + query);
}
}
注册在servletweb.xml文件和定义url-pattern来urlinfo的servlet-mapping。使用以下url访问此servlet时http://localhost:8080/urlinfo?x=1&y=1,将在浏览器上获得以下输出:
Url: http://localhost:8080/urlinfoUri: /urlinfo
Scheme: http
Server Name: localhost
Port: 8080
Context Path:
Servlet Path: /urlinfo
Path Info: null
Query: x=1&y=1
以上是 Java如何获取servlet请求URL信息? 的全部内容, 来源链接: utcz.com/z/330742.html