HttpServletRequest类
HttpServletRequest类的常用方法
- getRequestURI 获取请求的资源路径
- getRequestURL 获取请求的统一资源定位符(绝对路径)
- getRemoteHost 获取客户端的ip地址
- getMethod 获取请求的方式
代码演示
- 注意给RequestAPIServlet类配置web.xml
public class RequestAPIServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("URI-->"+req.getRequestURI());//URI-->/tian/req
System.out.println("URL-->"+req.getRequestURL());//URL-->http://localhost:8080/tian/req
System.out.println("客户端ip地址--->"+req.getRemoteHost());//客户端ip地址--->0:0:0:0:0:0:0:1 相当于127.0.0.1
System.out.println("请求的方式"+req.getMethod());//请求的方式GET
}
}
如何获取请求参数
-
req.getParameter("username"); //获取一个值的时候使用
-
req.getParameterValues("hobby") //获取多个值的时候使用
代码演示
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/tian/param" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
兴趣爱好:<input type="checkbox" name="hobby" value="cpp">C++
<input type="checkbox" name="hobby" value="java">java
<input type="checkbox" name="hobby" value="js">js<br>
<input type="submit">
</form>
</body>
</html>
xml配置
<servlet>
<servlet-name>ParamterServlet</servlet-name>
<servlet-class>com.tian.servlet.ParamterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ParamterServlet</servlet-name>
<url-pattern>/param</url-pattern>
</servlet-mapping>
servlet
package com.tian.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class ParamterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username=req.getParameter("username");
String password=req.getParameter("password");
String[] hobby=req.getParameterValues("hobby");
System.out.println("用户名:"+username);//用户名:root
System.out.println("密码:"+password); //密码:root
System.out.println("兴趣爱好:"+ Arrays.asList(hobby));
//兴趣爱好:[cpp, java, js]
//Arrays.asList() 该方法是将数组转化为list
}
}