HttpServletRequest类的常用方法
- getRequestURI() 获取请求的资源路径
- getRequestURL() 获取请求的统一资源定位符(资源路径)
- getRemoteHost() 获取客户端的IP地址
- getHeader() 获取请求头
- getParameter() 获取请求参数
- getParameterValues() 获取请求的参数(多个值时候使用)
- getMethod() 获取请求的方式GET或POST
- setAttribute(key,value); 设置域数据
- getAttribute(key); 获取域数据
- getRequestDispatcher() 请求转发函数
获取参数(重点使用)
首先需要编辑HTML表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8888/7_servlet_war_exploded/ppp" method="post">
用户名:<input type="text" name="username"> <br/>
密码:<input type="password" name="password"> <br/>
兴趣爱好:<input type="checkbox" name="hobby" value="java">JAVA
兴趣爱好:<input type="checkbox" name="hobby" value="js">JavaScript
兴趣爱好:<input type="checkbox" name="hobby" value="CPP">C+
<input TYPE="submit" >
</form>
</body>
</html>
其在Servlet类中写入方法体
protected void doGet(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:"+username);
System.out.println("密码"+password);
System.out.println("兴趣爱好"+ Arrays.asList(hobby));
}
解决post请求中文乱码
在doPost方法头部中写入
//设置请求体字符集为UTF-8
req.setCharacterEncoding("UTF-8");
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求体字符集为UTF-8
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobby = req.getParameterValues("hobby");
System.out.println("username:"+username);
System.out.println("密码"+password);
System.out.println("兴趣爱好"+ Arrays.asList(hobby));
System.out.println("POST");
}