package cn.edu; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //通过ServletContext实现请求转发 public class ServletDemo8 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="ABCDEFG"; //把数据带给1.JSP(不能通过Context域,要通过request域) this.getServletContext().setAttribute("data", data); //获取请求分派器 RequestDispatcher rd=this.getServletContext().getRequestDispatcher("/1.jsp"); //将请求转发到指定资源 rd.forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
前台显示页面:1.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP '1.jsp' starting page</title> </head> <body> <h1> <font color="red"> <% String value=(String)application.getAttribute("data"); out.write(value); %> </font> </h1> </body> </html>
时间: 2024-09-21 17:36:21