这篇介绍和演示一下HttpServlet常用的几个API。
常用的API有:
- getRequestURI() 获取请求的资源路径
- getRequestURL() 获取请求的统一资源定位符(绝对路径)
- getRemoteHost() 获取客户端的ip地址
- getHeader() 获取请求头
- getParameter() 获取请求的参数
- getParameterValues() 获取请求的参数(多个值的时候使用)
- getMethod() 获取请求的方式GET或POST
package com.example.javaservlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HttpServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("URI: " + req.getRequestURI());
System.out.println("URL: " + req.getRequestURL());
System.out.println("Client IP: " + req.getRemoteHost());
System.out.println("Req Headers: " + req.getHeader("User-Agent"));
System.out.println("Req Method: " + req.getMethod());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("This is post request");
}
}