#学习笔记#Servlet如何获取请求的参数值?

Servlet如何获取请求的参数

使用Request常用API来获取参数
这里演示的表单的提交
用到的是getParameter()getParameterValues()

相关代码:

//ParamrterServlet.java
package 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.ArrayList;
import java.util.Arrays;

public class ParameterServlet extends HttpServlet {
     

    @Override
    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);
        System.out.println("密码:" + password);
        System.out.println("兴趣爱好:" + Arrays.asList(hobby));
    }

    @Override
    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);
        System.out.println("密码:" + password);
        System.out.println("兴趣爱好:" + Arrays.asList(hobby));
    }
}



<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <form action="http://localhost:8080/Java_Web01_war_exploded/parameterServlet" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        兴趣爱好:
        <input type="checkbox" name="hobby" value="java">java
        <input type="checkbox" name="hobby" value="cpp">c++
        <input type="checkbox" name="hobby" value="PHP">PHP
        <input type="checkbox" name="hobby" value="HTML">HTML<br>
        <input type="submit" value="提交(POST请求)">

    form>

    <form action="http://localhost:8080/Java_Web01_war_exploded/parameterServlet" method="get">
        用户名:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        兴趣爱好:
        <input type="checkbox" name="hobby" value="java">java
        <input type="checkbox" name="hobby" value="cpp">c++
        <input type="checkbox" name="hobby" value="PHP">PHP
        <input type="checkbox" name="hobby" value="HTML">HTML<br>
        <input type="submit" value="提交(GET请求)">

    form>

body>
html>

如果POST请求传递出现乱码(传递中文时)如何解决?

在doPost方法中加入:
req.setCharacterEncoding("UTF-8");
注意:这个API得加在第一行,只对后面的获取请求参数传递生效,对于前面的请求参数不会生效

你可能感兴趣的:(servlet,post,html,ajax)