getRequestDispatcher()和forward()方法如何工作? [英] How do the getRequestDispatcher() and forward() methods work?

查看:141
本文介绍了getRequestDispatcher()和forward()方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSP,JSTL和Java servlet创建登录/注册页面,并且正在servlet的doPost()方法中使用它:

I'm making a login/registration page using JSP, JSTL, and a Java servlet, and I'm using, in the doPost() method of the servlet:

request.setAttribute("message", "invalid login");
request.getRequestDispatcher("index.jsp").forward(request, response);

在用户从index.jsp输入无效的登录凭据时提醒用户.

to alert the user when he enters invalid login credentials from index.jsp.

这有效,但我不知道为什么有效;这是我的问题:

This works, but I don't know why it works; here are my questions:

  1. 为什么在请求对象而不是响应对象上调用setAttribute()?

  1. Why is setAttribute() called on the request object and not the response object?

据我了解,我正在将请求和响应对象转发到index.jsp,但是jsp页面如何处理这些对象?它是一堆html,因此响应对象是否已更改,因此它包括index.jsp的所有html代码?

As I understand it, I'm forwarding the request and response objects to index.jsp, but how does a jsp page handle these objects? It's a bunch of html, so is the response object altered so that it includes all the html code of index.jsp?

为什么getRequestDispatcher()是实例方法?也就是说,为什么不能使用构造函数创建RequestDispatcher对象?

Why is getRequestDispatcher() an instance method? That is, why can't RequestDispatcher objects be created using a constructor?

谢谢.

推荐答案

  1. HttpServletRequest一直传递到最终处理响应为止.也就是说,在呈现JSP时,请求对象仍然可用.这是您在整个请求处理过程中传递任意数据的方式.

  1. The HttpServletRequest is passed along until the response is finally handled. That is, when the JSP is being rendered, the request object is still available. This is how you pass arbitrary data throughout the whole request handling process.

JSP文件被编译为将HTML写入响应的自定义servlet.

JSP files are compiled to custom servlets that write the HTML to the response.

RequestDispatcher是根据请求创建的,因为它需要了解servlet环境.否则它将不知道如何调度任何东西.

The RequestDispatcher is created from the request because it needs to know about the servlet environment. Otherwise it wouldn't know how to dispatch anything.

这篇关于getRequestDispatcher()和forward()方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆