文章目录

  • 一、getRequestDispatcher理解
  • 二、RequestDispatcher.forward()方法与HttpServletResponse.sendRedirect()方法的区别
  • 三、实现步骤
    • 1.编写index.jsp登录页面
    • 2.编写跳转页面success.jsp页面
    • 3.编写LoginServlet.java类
  • 四、运行示例

一、getRequestDispatcher理解

request.getRequestDispatcher()是请求转发,前后页面共享一个request ; 这个是在服务端运行的,对浏览器来说是透明的。
response.sendRedirect()是重新定向,前后页面不是一个request。而这个是在浏览器端运行的。

二、RequestDispatcher.forward()方法与HttpServletResponse.sendRedirect()方法的区别

RequestDispatcher.forward()方法仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址。
HttpServletResponse.sendRedirect()方法则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。

三、实现步骤

1.编写index.jsp登录页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
    <form action="${pageContext.request.contextPath}/login" method="get">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        爱好:
        <input type="checkbox" name="hobby" value="女孩"> 女孩
        <input type="checkbox" name="hobby" value="代码"> 代码
        <input type="checkbox" name="hobby" value="唱歌"> 唱歌
        <input type="checkbox" name="hobby" value="电影"> 电影
        <br>
        <input type="submit">
    </form>
</div>
</body>
</html>

2.编写跳转页面success.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>

3.编写LoginServlet.java类

package com.xxx.request;
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 {
           req.setCharacterEncoding("utf-8");
           resp.setCharacterEncoding("utf-8");
           String username=req.getParameter("username");
           String password=req.getParameter("password");
           String[] hobby=req.getParameterValues("hobby");
           System.out.println("======================================");
           System.out.println(username);
           System.out.println(password);
           System.out.println(Arrays.toString(hobby));
           req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}

四、运行示例

Request请求转发getRequestDispatcher

Request请求转发getRequestDispatcher
Request请求转发getRequestDispatcher

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。