zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    

      

  • 相关阅读:
    [Leetcode] Regular Expression Matching
    [Leetcode] Edit Distance
    计算机科学论文写作3-表、图、例子和其他类似的元素的使用
    计算机科学论文写作2-搜寻、阅读和引用文献
    灰度图与彩图的双边滤波
    opencv6.1-imgproc图像处理模块之平滑与形态学操作
    opencv5-objdetect之级联分类器
    opencv4-highgui之视频的输入和输出以及滚动条
    计算机科学论文写作1-引言
    lecture11-hopfiled网络与玻尔兹曼机
  • 原文地址:https://www.cnblogs.com/aloneme/p/14285577.html
Copyright © 2011-2022 走看看