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

      

  • 相关阅读:
    虹软人脸识别在 linux中so文件加载不到的问题
    tomcat 控制台乱码问题
    sourceTree git 空目录从远程仓库克隆代码出现warning: templates not found
    springboot项目更改代码后实时刷新问题
    spring 3.0 整合redis
    随笔
    Centos 7 安装 FFmpeg
    Postgresql 查看当前数据库所有的触发器
    oracle只导出触发器
    oracle 批量删除触发器
  • 原文地址:https://www.cnblogs.com/aloneme/p/14285577.html
Copyright © 2011-2022 走看看