JavaEE HttpServletRequest

描述

使用 HttpServletRequest 对象,可以获取请求行中相关信息。

题目

通过 HttpServletRequest 对象,获取请求行中相关信息。

题目解决思路

  1. 使用 @WebServlet 注解的方式创建 Servlet。
  2. 使用 getMethod 方法获取请求行中的请求方式。
  3. 使用 getRequestURI 方法获取请求行中的的 URI。
  4. 使用 getProtocol 方法获取协议和版本。
  5. 使用 getQueryString 方法获取查询字符串。

代码具体实现

Servlet 代码:

@WebServlet("/demo01") public class Servlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应的内容类型和编码 response.setContentType("text/html;charset=utf-8"); // 通过响应对象获取打印流 PrintWriter pw = response.getWriter(); pw.print("嗨客网(www.haicoder.net)<br/>"); pw.print("<br/>"); // 获取请求行的信息 pw.print("获取请求的方式:" + request.getMethod() + "<hr/>"); pw.print("获取请求的URI:" + request.getRequestURI() + "<hr/>"); pw.print("获取协议和版本:" + request.getProtocol() + "<hr/>"); pw.print("获取查询字符串:" + request.getQueryString() + "<hr/>"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }

运行结果如下图:

01_Java HttpServletRequest.png

以上案例通过 HttpServletRequest 对象,获取请求行中相关信息。