Servlet中Request对象请求转发详解

需求应用场景:

浏览器发起请求,请求至AServlet,AServlet增加相关逻辑后将Request请求对象转发给BServlet,BServlet做相关的逻辑处理。

示意图如下:

 代码 AServlet

package com.lagou;

/**
 * 实现request的内容转发和共享需求
 */

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AServlet 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.setContentType("text/html;charset=utf-8");

        System.out.println("AServlet处理功能--上:");
        req.setAttribute("name","香辣鸡腿堡");                    //向request中存放数据
        req.getRequestDispatcher("/bServlet").forward(req,resp);      //链式编程:获取转发器对象并调用forward()方法实现请求转发,其中Dispatcher对象中的参数为要转发Servlet的虚拟路径


    }
}

  BServlet

package com.lagou;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BServlet 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.setContentType("text/html;charset=utf-8");

        System.out.println("BServlet处理功能--下:");

        String name = (String) req.getAttribute("name");
        System.out.println("name : " + name);
    }
}

  

原文地址:https://www.cnblogs.com/aloneme/p/14285577.html