Servlet请求信息示例

时间:2020-02-23 14:34:40  来源:igfitidea点击:

在本教程中,将介绍如何从Servlet请求对象检索各种数据,如头、参数、路径和会话数据

当客户机(浏览器)向Servlet发出GET、POST、PUT等请求时

HttpServletRequest

对象保存有关客户端和请求本身的有价值的信息。在下面的示例中,我将列出请求对象的一些最有趣的方法以及如何提取信息。

package net.theitroad.tutorials;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletInfo extends HttpServlet {

	private static final long serialVersionUID = -2383814320847175129L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		PrintWriter pr = response.getWriter();

		pr.println("=== Paths ===\n");
		pr.println("Request URL : " + request.getRequestURL());
		pr.println("Request URI : " + request.getRequestURI());
		pr.println("Servlet path : " + request.getServletPath());

		pr.println("\n=== Headers ===\n");
		Enumeration<String> e = request.getHeaderNames();
		while(e.hasMoreElements()){
			String param = (String) e.nextElement();
			pr.println(param + " : " + request.getHeader(param));
		}

		pr.println("\n=== Parameters ===\n");
		Map<String, String[]> paramsMap = request.getParameterMap();
		for (String key : paramsMap.keySet()) {
			pr.println(key + " : " + request.getParameter(key));
		}

		pr.println("\n=== Session ===\n");
		//returns 0:0:0:0:0:0:0:1 if executed from localhost
		pr.println("Client IP address : " + request.getRemoteAddr());
		pr.println("Session ID : " + request.getRequestedSessionId());
		//Cookie objects the client sent with this request
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				pr.print(cookie.getName() + ";");
			}
		}
	}

}

正在请求上的servlet

localhost

Tomcat服务器位于http://localhost:8080/ServletInfo/info?mygooglechrome版本51.0.2704.103中的section=tutorials&lang=java显示以下输出:

请求信息输出

HttpServletRequest方法

getRequestURL()–返回客户端用于发出请求的整个URL,包括协议(http或者https)、服务器名称、端口号和服务器路径,但不包括查询参数

getRequestURI())–只返回URL的服务器路径部分

getServletPath())–返回在Tomcat中部署的应用程序路径(在上面的示例中是/info)

getHeaderNames())–返回与请求一起传递的所有头的名称的枚举

getHeader(headerName)–返回具有给定名称的头的值

getParameterMap())–返回包含所有参数及其值的哈希映射

getParameter(key)–返回给定key(name)的参数值

getRemoteAddr())–返回客户端的IP地址。如果请求在本地主机上执行,则返回值为0:0:0:0:0:0:1或者IPv6等效值127.0.0.1

getRequestedSessionId())–返回远程会话id(如果提供)

getCookies())–返回客户端随此请求发送的Cookie对象数组