在JSP页面中不需要定义,直接可以拿来就用的对象。:
例子:在JSP代码里面,我们直接写
<%
request.setParameter('foo','bar');
%>
不需要声明,就可以直接拿来用的对象。
不需要声明就可以直接用的对象有九种(SUN):
1.request对象,其实就是HttpServletRequest对象,存在于JSP中。常见的方法:getParameter(),getParameterValues(),getParameterNames().
例子:get client Parameters, Enumeration getParameterNames(),String[] getParameterValues(String name),String getParameter(String name),Map getParameterMap()
get client stream or reader,ServletInputStream getInputStream(),Reader getReader(),
parse request url,String getServletPath(),String getContextPath(),
2.response对象:其实就是HttpServletResponse对象,在服务器端将数据传送到客户端。常用功能,设置HTTP头信息,重定向,设置cookie信息。号称是技巧,response.setHeader("refresh","2;url=页面名称");
3.session对象:就是HttpSession对象,在Jsp当中有默认的request.getSession()的在JSP里面总是有session对象的。<%@page sesson="false"%>
4.application对象:就是Servlet中的上下文中的ServletContext。
5.exception对象:其实就是java.lang.Throwable的实现类,当前页面指定<%page errorPage="error.jsp"%>,然后在错误页面中指定<%@page iosErrorPage="true"%>
6.out对象:就是getWrite()对象,类型是JspWrite
7.config对象。
8.page对象:写this和写page应该是一样的,两个指代的对象应该是一个。
9.pageContext对象:一个页面对应一个pageContext页面上下文,通过pageContext可以获取request,session,application等对象,pageContext的存取只是限制其中一个页面上。
JSP的数据的共享范围:范围从小到大排序,pageContext,request,session,application.在几个范围之内读取一条String,
例子:
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What is Jsp</title>
</head>
<body>
<%
request.setAttribute("str","helloWorld_request");
session.setAttribute("str","helloWorld_session");
application.setAttribute("str","helloWorld_application");
String str = (String)pageContext.getAttribute("str",pageContext.SESSION_SCOPE);
out.println(str+"<hr/>");
str = (String)pageContext.findAttribute("str");
out.println(str);
%>
</body>
</html>
两个页面使用dispatcher.forward进行转发
例子:
index.jsp页面中的代码:
<%@page import="java.util.List,java.util.ArrayList" %>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What is Jsp</title>
</head>
<body>
<%
pageContext.setAttribute("str","helloWorld_pageContext");
request.setAttribute("str","helloWorld_request");
session.setAttribute("str","helloWorld_session");
application.setAttribute("str","helloWorld_application");
request.getRequestDispatcher("target.jsp").forward(request,response);
//pageContext.forward("target.jsp");
%>
</body>
</html>
target.jsp页面中的代码:
<%@page import="java.util.List,java.util.ArrayList" %>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What is Jsp</title>
</head>
<body>
<%
String str=(String)pageContext.findAttribute("str");
out.println(str);
%>
</body>
</html>
前台页面访问的时候显示的内容:
helloWorld_request