jsp跳转getRequestDispatcher()和sendRedirect()的区别

1.request.getRequestDispatcher()是请求转发,前后页面共享一个request ;
response.sendRedirect()是重新定向,前后页面不是一个request。

2.RequestDispatcher.forward()是在服务器端运行;
HttpServletResponse.sendRedirect()是通过向客户浏览器发送命令来完成.
所以RequestDispatcher.forward()对于浏览器来说是“透明的”;
而HttpServletResponse.sendRedirect()则不是。

3.ServletContext.getRequestDispatcher(String url)中的url只能使用绝对路径; 而ServletRequest.getRequestDispatcher(String url)中的url可以使用相对路径。因为ServletRequest具有相对路径的概念;而ServletContext对象无次概念。

RequestDispatcher对象从客户端获取请求request,并把它们传递给服务器上的servlet,html或jsp。它有两个方法:

1.void forward(ServletRequest request,ServletResponse response)

用来传递request的,可以一个Servlet接收request请求,另一个Servlet用这个request请 求来产生response。request传递的请求,response是客户端返回的信息。forward要在response到达客户端之前调用,也 就是 before response body output has been flushed。如果不是的话,它会报出异常。

2.void include(ServletRequest request,ServletResponse response)

用来记录保留request和response,以后不能再修改response里表示状态的信息。

如果需要把请求转移到另外一个Web App中的某个地址,可以按下面的做法:
1. 获得另外一个Web App的ServletConext对象(currentServletContext.getContext(uripath)).

2. 调用ServletContext.getRequestDispatcher(String url)方法。

eg:ServletContext.getRequestDispatcher(“smserror.jsp”).forward(request,response);

代码实例:
index.jsp:


代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

My JSP 'index.jsp' starting page
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />
<meta http-equiv="description" content="This is my page" />
    <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<form action="servlet/session" method="post">
  用户名:<input type="text" name="username" />

密码:<input type="password" name="password" />

<input type="submit" />
  </form>

session.java:


代码如下:

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;
import javax.servlet.http.HttpSession;

public class session extends HttpServlet {

/**
     * Constructor of the object.
     */
    public session() {
        super();
    }

/**
     * Destruction of the servlet.

*/
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

/**
     * The doGet method of the servlet.

*
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

/**
     * The doPost method of the servlet.

*
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = "";
        String password = "";
        username = request.getParameter("username");
        password = request.getParameter("password");
        HttpSession session = request.getSession();
        session.setAttribute("username", username);
        session.setAttribute("password", password);
        request.setAttribute("name", username);
        request.setAttribute("pwd", password);

RequestDispatcher dis = request.getRequestDispatcher("/getsession.jsp");
        dis.forward(request, response);

/*
        response.sendRedirect("http://localhost:8080/sessiontest/getsession.jsp");
        */
                //这个路径必须是这样写,而不能像上面的request.getRequestDispatcher那样使用相对路径
                //  而且要是使用response.sendRedirect的话在下面的session.jsp中不能通过request.getAttribute来获取request对象
                //因为前后使用的不是同一个request,但是session可以,因为session会一直存在直到用户关闭浏览器
    }

/**
     * Initialization of the servlet.

*
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

getsession.jsp:

代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

My JSP 'getsession.jsp' starting page

<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />
<meta http-equiv="description" content="This is my page" />
    <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
    -->

<%   out.print("");   String username = (String)session.getAttribute("username");  
String password = (String)session.getAttribute("password");  
String name = (String)request.getAttribute("name");  
String pwd = (String)request.getAttribute("pwd"); 
 out.println("username " + username + " password " +password);
 //如果上面是使用response.sendRedirect的话就不能获取到name和pwd  
 out.println("name " + name + "pwd "+ pwd);   
  %>

(0)

相关推荐

  • JSP的request对象实例详解

    JSP的request对象实例详解 一 request对象定义 客户端的请求信息被封装在request对象中,通过它才能了解客户的需求,然后做出响应.它是HttpServletRequest类的实例.request对象具有请求域,即完成客户端的请求之前,该对象一直有效. 二 request对象方法 三 实例 <%@ page language="java" import="java.util.*" contentType="text/html; ch

  • JSP用过滤器解决request getParameter中文乱码问题

    (1)客户端的数据一般是通过HTTP GET/POST方式提交给服务器,在服务器端用request.getParameter()读取参数时,很容易出现中文乱码现象. (2)用过滤器解决request中文乱码问题. (3)代码如下: package my; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ChineseFilter implements Filter { //定义

  • jsp 对request.getSession(false)的理解(附程序员常疏忽的一个漏洞)

    [前面的话] 在网上经常看到有人对request.getSession(false)提出疑问,我第一次也很迷惑,看了一下J2EE1.3 API,看一下官网是怎么解释的. [官方解释] getSession public HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if if there is no current session an

  • JSP XMLHttpRequest动态无刷新及其中文乱码处理

    1.在页面的<script type="text/JavaScript" >内加入 //无刷新请求的xmlhttp请求 var http_request=false; function createRequest(url) { http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_reque

  • java和jsp中的request使用示例

    复制代码 代码如下: //== JAVA request 详细说明== System.out.println("rotocol: " + request.getProtocol());  System.out.println("Scheme: " + request.getScheme());  System.out.println("Server Name: " + request.getServerName() );  System.out.

  • JSP利用过滤器解决request中文乱码问题

    本文为大家分享了JSP用过滤器解决request中文乱码问题,具体内容如下 (1)客户端的数据一般是通过HTTP  GET/POST方式提交给服务器,在服务器端用request.getParameter() 读取参数时,很容易出现中文乱码现象. (2)用过滤器解决request中文乱码问题. (3)代码如下: package my; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public clas

  • JSP request(return String)用法详例

    1.JSP代码 : 复制代码 代码如下: <%-- Document : index Created on : 2009-10-4, 12:45:43 Author : lucifer --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN&

  • JSP request.setAttribute()详解及实例

     javascript request.setAttribute()详解 request.setAttribute()怎么用的? JSP1代码 String [] test=new String[2]; test[0]="1"; test[1]="2"; request.setAttribute("test",test) ; response.sendRedirect("jsp2.jsp"); JSP2代码 String te

  • JSP内置对象:Request和Response的简单介绍及使用

    JSP内置对象之request对象客户端的请求信息被封装在request对象中,通过它才能了解到客户的需求,然后做出响应.它是HttpServletRequest类的实例.序号 方 法 说 明 1 object getAttribute(String name) 返回指定属性的属性值 2 Enumeration getAttributeNames() 返回所有可用属性名的枚举 3 String getCharacterEncoding() 返回字符编码方式 4 int getContentLen

  • 通过过滤器(Filter)解决JSP的Post和Request中文乱码问题

    jsp代码: import javax.servlet.*; import javax.servlet.http.*; public class CharsetFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { try { HttpServletRequest

随机推荐