您的位置:首页 > Web前端 > JavaScript

【JSP开发】通过ServletContext实现请求转发

2015-01-25 18:03 302 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: