request获取前端传递的数据

两个方法:

String username = req.getParameter("username");
String[] hobbys = req.getParameterValues("hobbys");

前端代码:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align:center" >
<%--   提交到Login --%>
    <form action="${pageContext.request.contextPath}/Login" 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="submit">
    </form>
</div>
</body>
</html>
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbys));
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

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

注册为Login

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.gao.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/Login</url-pattern>
    </servlet-mapping>
</web-app>

最后转义或重定向为success.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功,重定义</title>

</head>
<body>
<h1>登录成功</h1>
</body>
</html>

测试:

别忘了部署Tomcat

request获取前端传递的数据

request获取前端传递的数据

上一篇:php 的精品文章


下一篇:FreeCodeCamp初级算法部分学习