index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/3/18
  Time: 8:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>表单案例</title>
  </head>
  <body>
  <form action="/Servlet2" method="post">
    用户名:<input type="text" name="username"/><br>
    密码:<input type="password" name="password"/><br>
    性别:<input type="radio" name="sex" value="m"/>男
          <input type="radio" name="sex" value="w"/>女<br>
    爱好:<input type="checkbox" name="hobby" value="study"/>学习
          <input type="checkbox" name="hobby" value="game"/>游戏
          <input type="checkbox" name="hobby" value="reading"/>看书<br>
    <input type="submit" value="登录">
  </form>
  </body>
</html>

Slave2

package Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");//设置编码格式,否则输出为乱码或"???"
        PrintWriter out=response.getWriter();

        //获取参数值
        String name=request.getParameter("username");
        String pwd=request.getParameter("password");
        String sex=request.getParameter("sex");

        //复选框定义类型
        String hobby[]=request.getParameterValues("hobby");


        //输出获取到的参数值
        out.println("用户名:"+name+"<br>");
        out.println("密码:"+pwd+"<br>");
        out.println("性别:"+sex+"<br>");
        out.println("爱好:");

        //复选框输出方式
        for (int i=0;i<hobby.length;i++)
            out.println(hobby[i]+" ");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request, response);
    }
}