HTTP 请求中的所有信息会被封装到HttpServletRequest 通过这个HttpServletRequest 可以获得所有信息
获取前端传递的参数
req.getParameter(string s) string
req.getParameterValues(string s) string[]
//第二行是获取多选框的数据 或者是一些其他多选的的数据
测试类代码
package com.hui.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.Arrays;
public class RequesetTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");// 这里是处理输出时的乱码
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
//获取前端的数据
System.out.println("=============");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
//这里是打印出前端输入的数据 以便于检查 还有后续学习 的 判断等等 还有一些处理
System.out.println("==============");
//这是通过请求转发
req.getRequestDispatcher("/success.jsp").forward(req,resp);
req.setCharacterEncoding("utf-8");// 这里是 处理输出时的乱码问题
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
JSP代码
<%--这是写的那个登录页面--%>
<html>
<body>
<h2>登录</h2>
<%--这里提交的路径, 需要找到项目的路径--%>
<%--${pageContext.request.contextPath}当前项目路径--%>
<%--这里表单表示的意思: 以post方式提交表单提交到login2请求--%>
<form action="${pageContext.request.contextPath}/login2" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<!-- 多选框 -->
<input type="checkbox" name="hobbys"value=" 女孩" >女孩
<input type="checkbox" name="hobbys" value=" 代码"> 代码
<input type="checkbox" name="hobbys" value=" 唱歌"> 唱歌
<input type="checkbox" name="hobbys" value=" 电影"> 电影
<input type="checkbox" name="hobbys" value=" 骑行">骑行
<br>
<input type="submit">
</form>
</body>
</html>
登录成功显示的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>