Servlet之处理请求(四)

it2024-11-03  5

4.检索客户端有关信息: String getMethod():返回请求使用的HTTP方法名,如GET、POST或PUT等; String getRemoteHost() :返回客户端的主机名; String getRemoteAddr() :返回客户端的IP地址; int getRemotePort():返回客户端IP地址的端口号; String getProtocol():返回客户使用的请求协议名和版本; String getRequestURI():返回请求行中URL的查询串的前面部分; String getQueryString():返回请求行中URL的查询串的内容;

package com.demo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ClientInfoServlet */ @WebServlet("/client-information") public class ClientInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); out.print("<html><head><title>客户端信息</title></head><body>"); out.print("<p>客户端信息:</p>"); out.print(request.getMethod()+""+request.getRequestURI()+""+request.getProtocol()+"<br>"); out.print("<p>客户主机名:"+request.getRemoteHost()+"</p>"); out.print("<p>客户IP地址:"+request.getRemoteAddr()+"</p>"); out.print("<p>端口号:"+request.getRemotePort()+"</p>"); out.print("</body></html>"); } }

5.检索请求头信息 HTTP请求头是随请求一起发送到服务器的信息,它是以"名/值"对的形式发送。例如,关于浏览器的信息就是通过User-Agent请求头发送的。

package com.demo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ClientInfoServlet */ @WebServlet("/client-information") public class ClientInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); out.print("<html><head><title>客户端信息</title></head><body>"); out.print("<p>客户端信息:</p>"); out.print(request.getMethod()+""+request.getRequestURI()+""+request.getProtocol()+"<br>"); out.print("<p>客户主机名:"+request.getRemoteHost()+"</p>"); out.print("<p>客户IP地址:"+request.getRemoteAddr()+"</p>"); out.print("<p>端口号:"+request.getRemotePort()+"</p>"); out.print("</body></html>"); } }
最新回复(0)