request内部转发Demo
// 转发的Demo1
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/sendData")
public class Demo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//资源跳转 把一个服务当中的数据带到另外一个服务当中页面中
String name="小孙";
//http资源对象的内部转发方式
RequestDispatcher dispatcher = req.getRequestDispatcher("receiveData");
//域 缓存
// request域 存储的时机就是这个一次请求中,当请求结束的时候request域对象信息就释放掉了
req.setAttribute("username",name);//key - value
//转发
dispatcher.forward(req,resp);
}
}
// 接收的Demo2
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/receiveData")
public class Demo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从request中获取value值
String name = (String) req.getAttribute("username");
//如果携带有中文信息 设定编码字符集
//System.out.println(name);
resp.setContentType("text/html;charset=utf-8");
//显示在页面中
resp.getWriter().write(name);
}
}