获取HttpServletRequest请求信息,HTTP协议信息
经常用到,简单记录下…
/** * HttpServletRequest请求参数获取测试 * @author Niu on 2017年7月17日 下午2:45:01 */ @WebServlet("/dispense") public class DispenseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求方式:GET System.out.println("req.getMethod():" + req.getMethod()); // 获取项目名称:/dispense System.out.println("req.getContextPath():" + req.getContextPath()); // 获取完整请求路径:http://localhost:8888/dispense/dispense System.out.println("req.getRequestURL():" + req.getRequestURL()); // 获取除了域名外的请求数据:/dispense/dispense System.out.println("req.getRequestURI():" + req.getRequestURI()); // 获取请求参数:name=codingme.net System.out.println("req.getQueryString():" + req.getQueryString()); // 获取请求头: System.out.println("req.getHeader(\"user-Agent\"):" + req.getHeader("user-Agent")); System.out.println("--------------------------------------------------------"); // 获取所有的消息头名称 Enumeration<String> headerNames = req.getHeaderNames(); // 获取获取的消息头名称,获取对应的值,并输出 while (headerNames.hasMoreElements()) { String nextElement = headerNames.nextElement(); System.out.println(nextElement + ":" + req.getHeader(nextElement)); } System.out.println("----------------------------------------------------------"); // 根据名称获取此重名的所有数据 System.out.println("req.getHeader(\"accept\"):" + req.getHeader("accept")); // 获取请求主机名 System.out.println("req.getHeader(\"host\"):" + req.getHeader("host")); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
请求URL:
输出:
req.getMethod():GET req.getContextPath():/dispense req.getRequestURL():http://localhost:8888/dispense/dispense req.getRequestURI():/dispense/dispense req.getQueryString():name=codingme.net req.getHeader("user-Agent"):Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3080.5 Safari/537.36 -------------------------------------------------------- host:localhost:8888 connection:keep-alive cache-control:max-age=0 upgrade-insecure-requests:1 user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3080.5 Safari/537.36 accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 accept-encoding:gzip, deflate, br accept-language:zh-CN,zh;q=0.8 cookie:_ga=GA1.1.1003706294.1499565784; Hm_lvt_57ccbd5c600ed4e6bdb9458e666b6409=1499849256,1499853602,1499950574; Hm_lvt_1b51c3ea9a3e7b1a2bc55df97ab4efd3=1499952403 ---------------------------------------------------------- req.getHeader("accept"):text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 req.getHeader("host"):localhost:8888
原文地址:http://blog.codingme.net/post/servlet-HttpServletRequest-http-info
时间: 2024-10-07 05:31:20