JavaWeb13(Request应用)

HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过Http协议访问客户端时,客户端中的所有信息会被封装保存在HttpServletRequest中,再通过HttpServletRequest中的方法,可以获得客户端的所有信息

编写代码

LoginServlet

package com.hao.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 LoginServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbies));
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
//        resp.sendRedirect("/Request_war/success.jsp");
    }
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 15983
  Date: 2021/7/23
  Time: 10:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<h1>登录</h1>
<body>
<form action="${pageContext.request.contextPath}/login" method="post" style="text-align: center">
    用户名称: <input type="username" name="username"> <br>
    用户密码: <input type="password" name="password"> <br>
    用户爱好: <input type="checkbox" name="hobbies" value="fit">健身
            <input type="checkbox" name="hobbies" value="read">看书
            <input type="checkbox" name="hobbies" value="game">游戏
            <input type="checkbox" name="hobbies" value="eat">吃饭 <br>
    <input type="submit" name="submit">
</form>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 15983
  Date: 2021/7/23
  Time: 10:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>

编写映射

<servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.hao.Servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

测试访问

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_51224492/article/details/119024830