Request共享数据

这里我们说了Request请求转发,下面说说请求转发的共享数据

  • void setAttribute(String var1, Object var2):设置属性
  • Object getAttribute(String var1):获取属性
  • void removeAttribute(String var1):一处属性

直接来例子,RequestDemo7设置属性“love”,然后请求转发给RequestDemo8,RequestDemo8获取输出

RequestDemo7代码

package com.lingaolu.request;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 林高禄
 * @create 2020-07-07-16:46
 */
@WebServlet("/requestDemo7")
public class RequestDemo7 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("love","game");
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/requestDemo8");
        requestDispatcher.forward(request,response);
    }
}

RequestDemo8代码

package com.lingaolu.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 林高禄
 * @create 2020-07-07-16:46
 */
@WebServlet("/requestDemo8")
public class RequestDemo8 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Object love = request.getAttribute("love");
        System.out.println(love);
    }
}

浏览器访问

Request共享数据_第1张图片

后台输出

 

你可能感兴趣的:(Web核心)