package top.qaqaq.P146;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
/**
* @author RichieZhang
* @create 2022-12-05 下午 4:52
*/
public class ParameterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
// v. getParameter() 获取请求的参数
// vi. getParameterValues() 获取请求的参数(多个值的时候使用)
System.out.println("-----------doGet-----------");
// 获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
// String hobby = req.getParameter("hobby");
String[] hobby = req.getParameterValues("hobby");
System.out.println("用户名" + username);
System.out.println("密码" + password);
System.out.println("兴趣爱好" + Arrays.asList(hobby));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 设置请求体的字符集为UTF-8,从而解决post请求的中文乱码问题
// 也要在获取请求参数之前调用才有效
req.setCharacterEncoding("UTF-8");
System.out.println("-----------doPost-----------");
// 获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobby = req.getParameterValues("hobby");
System.out.println("用户名" + username);
System.out.println("密码" + password);
System.out.println("兴趣爱好" + Arrays.asList(hobby));
}
}
<servlet>
<servlet-name>ParameterServlet</servlet-name>
<servlet-class>top.qaqaq.P146.ParameterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ParameterServlet</servlet-name>
<url-pattern>/parameterServlet</url-pattern>
</servlet-mapping>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/JavaWeb_Code_Servlet/parameterServlet" 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">JavaScript<br/>
<input type="submit">
</form>
</body>
</html>