jsp:和属性相关的方法,请求的转发,重定向

jsp中与属性相关的方法:

方法:

void setAttribute(String name, Object o): 设置属性 

Object getAttribute(String name):获取指定的属性Enumeration

getAttributeNames(): 获取所有的属性的名字组成的 Enumeration 对象

removeAttribute(String name): 移除指定的属性

2). pageContext,request, session, application 对象都有这些方法!这四个对象也称之为域对象.

pageContext: 属性的作用范围仅限于当前 JSP 页面

request: 属性的作用范围仅限于同一个请求.

 session: 属性的作用范围限于一次会话: 浏览器打开直到关闭称之为一次会话(在此期间会话不失效)

application: 属性的作用范围限于当前 WEB 应用. 是范围最大的属性作用范围, 只要在一处设置属性, 在其他各处的 JSP 或 Servlet 中都可以获取到.

-------------------------------------------------------------------------------------------------------------------------------

请求的转发和重定向:

 本质区别: 请求的转发只发出了一次请求, 而重定向则发出了两次请求.

具体:

1. 请求的转发: 地址栏是初次发出请求的地址.
请求的重定向: 地址栏不再是初次发出的请求地址. 地址栏为最后响应的那个地址

2. 请求转发: 在最终的 Servlet 中, request 对象和中转的那个 request 是同一个对象.
请求的重定向: 在最终的 Servlet 中, request 对象和中转的那个 request 不是同一个对象.

3. 请求的转发: 只能转发给当前 WEB 应用的的资源
请求的重定向: 可以重定向到任何资源.

4. 请求的转发: / 代表的是当前 WEB 应用的根目录
请求的重定向: / 代表的是当前 WEB 站点的根目录.

--------------------------------------------------------------------------------------------------------------------------

具体例子如下:

请求的转发例子使用:它是Servlet类

public class ForwardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("只是forwardServlet方法!!!");

//请求的转发
//1.调用HttpServletRequest的getRequestDispatcher()方法获取RequestDispatcher对象
//调用getRequestDispatcher()方法需要传入要转发的地址
String path="testServlet";
RequestDispatcher requestDispatcher=request.getRequestDispatcher(path);

//2.调用HttpServletRequest的forward(request,response)进行请求的转发
requestDispatcher.forward(request, response);

}

}

---------------------------------------------------------------------------------------------

重定向的例子:它是Servlet类,

public class RedirectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("只是RedirectServlet的doget方法");

//执行请求和重定向,直接调用response.sendRedirect(path)方法
//其中path为重定向的地址
String path="testServlet";
response.sendRedirect(path);
}

}

原文地址:https://www.cnblogs.com/lxnlxn/p/5813159.html