• ServletContext中的转发


    客户端向服务器发送请求,服务器将请求进行转发,获得响应信息,客户端只发送一次请求,地址栏信息不变。

    服务器接收类,进行转发

    package com.itheima.zhuanfa;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ServletContextDemo3 extends HttpServlet{
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    //		转发
    		//获得ServletContext对象
    		ServletContext sc=getServletContext();
    		System.out.println("转发前");
    		resp.getOutputStream().write("before".getBytes());
    		//获得转发器
    		RequestDispatcher rd=sc.getRequestDispatcher("/Demo4");//得到请求转发器
    		rd.forward(req,resp);
    		/*
    		 * 转发的特点:请求的地址栏不变,两者共享request和response对象
    		 * 转发前和转发后的页面输出都不会发送到客户端
    		 * 转发前不要刷新response中的内容,会吧response中的内容清空
    		 */
    		System.out.println("转发后");
    		resp.getOutputStream().write("after".getBytes());
    		
    
    	}
    
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		
    	}
    
    }
    

     转发到的类把这个类的信息传到客户端

    package com.itheima.zhuanfa;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ServletContextDemo4 extends HttpServlet {
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		resp.getOutputStream().write("转发成功,我来自Demo4".getBytes());
    	}
    
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		
    	}
    	
    }
    
  • 相关阅读:
    13.困难重重
    02.Django的第一个网页
    03.Django模板
    01.Web开发之简介
    14.效率利器之多线程和线程池
    Silverlight实用窍门系列:37.Silverlight和ASP.NET相互传参的两种常用方式(QueryString,Cookie)
    Web编码规范中文乱码解决方案
    H*ber*ate Lazy属性
    Bat如何判断txt文本中第8行是否只有"符号,有则删除整行
    #每日一练 获取字典值
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4699720.html
Copyright © 2020-2023  润新知