request获取请求参数(通用方法)

//解决post中文乱码
req.setCharacterEncoding(“utf-8”);
//根据参数名称获值
String username = req.getParameter(“username”);
//根据参数名称获多值数组
String[] selects = req.getParameterValues(“select”);
//获取所有请求参数的名称
Enumeration parameterNames = req.getParameterNames();
//获取所有参数map集合
Map parameterMap = req.getParameterMap();

html表单代码

<form action="/day010/demo4" method="post">
        <input type="text" placeholder="请输入用户名" name="username"><br>
        <input type="text" placeholder="请输入密码" name="password"><br>
        <input type="checkbox" name="select" value="study">学习
        <input type="checkbox" name="select" value="play"><br>
        <input type="submit" value="提交">
    </form>
package Demo01;

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.util.Enumeration;
import java.util.Map;

@WebServlet("/demo4")
public class demo4 extends HttpServlet {
     
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        //根据参数名称获值
        String username = req.getParameter("username");
        System.out.println(username);
        System.out.println("============");
        //根据参数名称获多值数组
        String[] selects = req.getParameterValues("select");
        for (String select : selects) {
     
            System.out.println(select);
        }
        System.out.println("===========");
        //获取所有请求参数的名称
        Enumeration<String> parameterNames = req.getParameterNames();
        //遍历
        while (parameterNames.hasMoreElements()){
     
            String s = parameterNames.nextElement();
            System.out.println(s);
            String parameter = req.getParameter(s);
            System.out.println(parameter);
            System.out.println("-----");
        }
        System.out.println("==========");
        //获取所有参数map集合
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (String s : parameterMap.keySet()) {
     
            System.out.println(s);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        this.doPost(req,resp);
    }
}

结果输出

小明
============
study
play
===========
username
小明
password
sdegt
select
study
==========
username
password
select

你可能感兴趣的:(学习心得)