目录

​一、Request通用方式获取请求参数​

​二、Servlet模板创建​


一、Request通用方式获取请求参数

Map<String,String> getParameteMap():获取所有参数Mapcans参数

String[] getParameter(String name):根据名称获取参数值(数组)

String getParameter(String name):根据名称获取参数值(单个值)

代码示例:

req.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>


<form action="/Tomcate-demo2/req2" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="1">游泳
<input type="checkbox" name="hobby" value="2">爬山<br>
<input type="submit">
</form>
</body>
</html>

 RequestDemo2 :

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.Map;

@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//获取所有参数的map集合
Map<String, String[]> map = req.getParameterMap();
for (String key : map.keySet()) {
// username:zhangsan
System.out.print(key + ":");

//获取值
String[] values = map.get(key);
for (String value : values) {
System.out.print(value + " ");
}

System.out.println();
}

System.out.println("------------");

//2、根据key获取对应的参数组,数组
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}

//3、根据key,获取单个的参数值
String username = req.getParameter("username");
String password = req.getParameter("password");

System.out.println(username);
System.out.println(password);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

this.doGet(req,resp);
}
}

 访问req.html,输入数据并且提交:

Request通用方式获取请求参数及Servlet模板创建_java

控制台输出:

Request通用方式获取请求参数及Servlet模板创建_开发语言_02

二、Servlet模板创建

使用通用方式获取请求参数后,屏蔽了GET和POST的请求方式代码的不同,则代码可以定义为如下格式:

@WebServlet("/req6")
public class RequestDemo6 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

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

 可以使用Servlet模板创建Servlet更高效:

第一步选择File中的Setting

Request通用方式获取请求参数及Servlet模板创建_java-ee_03

 第二步根据对应的红框修改模板

Request通用方式获取请求参数及Servlet模板创建_开发语言_04

 第三步点击右键创建新的Sevlet

Request通用方式获取请求参数及Servlet模板创建_前端_05

新的Sevlet

Request通用方式获取请求参数及Servlet模板创建_java-ee_06