Servlet-獲取request與header信息

request能夠得到的信息: html

package com.pas.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 GetInfoRequest extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("gb2312");
		PrintWriter out = response.getWriter();
		
		out.println("完整URL:"+request.getRequestURL().toString());
		out.println("</br>");
		out.println("部分URI:"+request.getRequestURI().toString());
		out.println("</br>");
		out.println("QueryString:"+request.getQueryString());
		out.println("</br>");
		out.println("客戶端地址:"+request.getRemoteAddr());
		out.println("</br>");
		//請求方沒有在dns上註冊,則返回ip,不然返回機器名
		out.println("主機名:"+request.getRemoteHost());
		out.println("</br>");
		out.println("遠程端口:"+request.getRemotePort());
		out.println("</br>");
		out.println("服務器端口:"+request.getLocalPort());
		out.println("</br>");
		out.println("服務器IP:"+request.getLocalAddr());
		out.println("</br>");
		out.println("服務器名:"+request.getLocalName());
	}

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

		this.doGet(request, response);
	}

}

Header信息: java

package com.pas.request;

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

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

public class GetRequestHeader extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("gb2312");
		PrintWriter out = response.getWriter();
		
		//獲取請求的header信息
		out.println(request.getHeader("Host"));
		
		out.println("</br>");
		out.println("************Head信息************");
		out.println("</br>");
		//getHeaderNames(打印整個http請求消息)
		Enumeration<?> headers= request.getHeaderNames();
		String head="";
		
		while(headers.hasMoreElements())
		{
			head=headers.nextElement().toString();
			out.println(head+":"+request.getHeader(head));
			out.println("</br>");
		}

	}

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

		this.doGet(request, response);
	}

}
相關文章
相關標籤/搜索