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);
        }
    }
    

      

  • 相关阅读:
    转:SQL Case when 的使用方法
    转:性能测试知多少
    转:如何让LoadRunner实现多个场景运行?
    转:Loadrunner学习知多少--脚本录制下载操作
    1.3 本章小结
    1.2.5 内部元数据
    1.2.4 创建图像查看应用程序
    1.2.3 使用MediaStore检索图像
    1.2.2 更新CameraActivity以使用MediaStore存储图像和关联元数据
    1.2.1 获得图像的Uri
  • 原文地址:https://www.cnblogs.com/aloneme/p/14285577.html
Copyright © 2011-2022 走看看