Request应用

HttpServletRequest

代表客户端的请求,用户通过http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得用户端的所有信息。
屏幕截图 2025-09-04 170204

应用场景

  1. 获取前端传递的参数
    屏幕截图 2025-09-04 170357

  2. 请求转发

package com.xin.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 doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//解决后台接收中文乱码问题
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] loves = req.getParameterValues("love");
        System.out.println(Arrays.toString(loves));
        //resp.sendRedirect("/r/success.jsp");
        //请求转发,这里的斜杠/代表当前的web应用 tomcat
        //重定向需要写好绝对路径/request/success,请求转发只是内部资源的跳转不用写
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }
<%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2025/9/4
  Time: 17:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
    <%--以post方式提交表单,提交到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="love" value="XIXI">熙熙
        <input type="checkbox" name="love" value="G.E.M.">棋棋
        <input type="checkbox" name="love" value="ZAIZAI">崽崽
        <br>
        <%--checkbox 多选框--%>
        <input type="submit">
    </form>
</div>
</body>
</html>

面试:重定向和转发的区别

(写过但是加深印象)
相同:

  1. 页面都会跳转
    不同:
  2. 请求转发的时候url不会变化,转发编码307
  3. 重定向的时候url会发生变化,重定向编码302
posted @ 2025-09-04 17:55  xixixixin  阅读(7)  评论(0)    收藏  举报