JSP指令及九大内置对象

一.三个编译指令

常见的编译指令:
        (1)page                  针对当前页面的指令
        (2)include               制定包含另一个页面
        (3)taglib                  定义和访问自定义标签

1. page指令

<%@ page
[language="java"]
[extends="package.class"]
[import="true|false"]
[session="treu|false"]
[buffer="nonde|8kb|size kb"]
[autoFlush="true|false"]
[isThreadSafe="true|false"]
[info="text"] //在页面取这个值用getServletInfo()
[errorPage="relativeURL"]
[contentType="mimeType[;charset=characterSet]"|"text/html;charset=utf-8"]
[pageEncoding="utf-8"]
[isErroePage="true|false"]
%>
 

2. include指令

    使用这个指令,将一个外部文件嵌入到当前JSP页面中,同时解析这个页面的JSP语法这是个静态的include语句,他会把目标页面的其他便以指令也包含进来,但动态include则不会
<%@include file="relativeURLSpec" %>
注意:两个页面的编译指令不能相同,会报错
 

3. taglib指令

    目前常用的有两个,一个是c标签库,一个是s标签库
<%@taglib prefix="s" uri="/struts-tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
 
 

一.七个动作指令

 
动作指令与编译指令不同,编译指令是通知servlet引擎的处理消息,而动作指令仅仅是运行时的动作,编译指令在将JSP编译成servlet时起作用,而处理指令通常可替换成JSP脚本,他只是JSP脚本的标准化写法。
JSP动作指令如下:
      
 jsp:forward       执行页面转向,将请求的处理转发到下一个页面
  jsp:param       用于传递参数,必须与其他支持参数的标签一起使用
  jsp:include      用于动态引入一个jsp页面
  jsp:plugin         用于下载javaBean或Applet到客户端
  jsp:userBean         创建javaBean实例
  jsp:setProperty      设置javaBean实例的属性
  jsp:getProperty      输出javaBean的实例属性值
 
 

1. forword指令

         将页面响应转发到另外一个页面,既可以是静态页面又可以是动态页面,甚至是servlet。
<jsp:forward page="{relativeUrl|<%=EXPRESSION%>}">
{<jsp:param... />}
</jsp:forward>
执行此操作不会导致请求参数丢失,使用request.getParameter("###")接收。页面地址并未改变,只是采用了新页面来响应它。
 

2. include指令

         他也用户导入其他页面,只不过不会导入编译指令,只会导入页面body部分插入到当前页面。
<jsp:include page="{relativeUrl|<%=EXPRESSION%>}" flush="true">
{<jsp:param=""value=""/>}
</jsp:include>
##动态导入和静态导入的区别:
         静态导入是一种全部导入,合成一个servlet,而动态导入是Servlet中使用include方法来引入被导入页面的内容,动态导入后编译指令失效,只是插入了body部分。动态包含可以增加额外的参数

3. userBean  setProperty  getProperty  

    其实就是创建一个页面版本的javaBean,最好是直接去创建类,这样好一些,这里给出这个标签用法:
<jsp:userBeanid="name"class="classname"scope="page|request|session|application"/>
<jsp:setPropertyname="BeanName"property="propertyName"value="value"/>
<jsp:getPropertyname="BeanName"property="propertyName"/>
 

4. plugin指令

         

5. param指令

 结合之前学的使用:
jsp:include
jsp:forward
jsp:plugin
 
       

一.九个内置对象

 
对象名称 实例所属 含义 作用范围 常用方法
application javax.servlet.ServletContext 代表jsp所属应用,可用于JSP页面或servlet之间交换信息 Application get/setAttribute(String attName)
getInitParameter(String paramName)
config javax.servlet.ServletConfig 代表jsp的配置信息,基本在servlet中发挥作用 Page getInitParameter(String paramName)
getInitParameternames()
exception javax.lang.Throwable 只有当前页面为编译指令page中isError=true时才有用 Page getMessage(),printStackTrace()
out javax.servlet.jsp.JspWriter jsp页面输出流用于输出内容形成html页面 Page  
page   页面本身,也是servlet中的this,能用page的地方就可以用this Page  
pageContext javax.servlet.jsp.PageContext jsp上下文,可以访问页面中的共享数据 Page getServletContext();getServletConfig()
request javax.servlet.http.HttpServletRequest 该对象封装一次客户端请求参数发送到服务器端 Request getParaqameter(String name);
getParameterValues(String name);
setAttribute("key","value");getAttribute(key);
setCharacterEncoding(String env);
response javax.servlet.http.HttpServletResponse 代表服务器端对客户端的响应 Page getOutputStream();
sendRedirect(java.lang.String Location);
session javax.servlet.http.HttpSession 代表一次通话(从建立连接到浏览器关闭) Session setAttribute("key","value");
getAttribute(key);
 
注意,所有jsp页面编译后都有如下信息可以查询:
pageContext = _jspxFactory.getPageContext(this,request,response,null,true,8192,true)
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
 

1. application对象

     application对象实现了用户间数据的共享,可存放全局变量。 与session对象不同的是,所有客户的application对象都是同一个,即所有客户共享application对象,这样 application对象就可以起到一个全局变量的作用
application开始于服务器的启动,终止于服务器的关闭。 在用户的前后链接或不同用户之间的连接中,可以对application对象的同一属性进行操作。
在任何地方对application对象属性的操作,都将影响到其他用户对此的访问 服务器的启动和关闭决定了application对象的生命。 application对象是ServletContext类的实例。
application对象的常用方法如下:
    ( 1)public void setAttribute(String name,Object value)使用指定名称将对象绑定到此会话。
    ( 2)public Object getAttribute(String name)返回与此会话中的指定名称绑定在一起的对象,如果没有对象绑定在该 名称下,则返回null
    ( 3)Enumeration getAttributeNames()返回所有可用属性名的枚举。
    ( 4)String getServerInfo():返回JSP(Servlet)引擎名及版本号。
主要两个地方有用到:
(1)在多个jsp、servlet共享数据,比如:
   
jsp中
<%
application.setAttribute("counter",100);
application.getAttribute("name");
%>
java
ServletContext sc = getServletConfig().getServletContext();
sc.getAttribute("counter");
 
(2)获得web应用配置参数     
比如在web.xml中这样写:
<context-param>
<param-name>name</param-name>
<param-value>sun</param-value>
</ context -param>  
在jsp中获得:
<%=application.getAttribute("name")%>
 
 

2. config对象

     config对象是在一个Servlet初始化时,JSP引擎向它传递信息用的,此信息包括Servlet初始化时所要用到的参数(通过 属性名和属性值构成)以及服务器的有关信息(通过传递一个ServletContext对象),简单点就是你在web.xml中写的init-params都可以用它接收
常用的方法如下:
     1) ServletContext getServletContext():返回含有服务器相关信息的ServletContext对象。
     (2 String getInitParameter(String name()):返回初始化参数的值。
     (3 Enumeration getInitParameterNames():返回Servlet初始化所需所有参数的枚举。
比如在web.xml中这样写:
<servlet>
<init-param>
<param-name>name</param-name>
<param-value>sun</param-value>
</init-param>
</servlet>
 
通常在jsp中这样写:
<%=config.getServletName %> //输出jsp
<%=config.getInitParameter("name")%>
 
与application区别
          这里实在每个servlet里面的初始化配置,二application使用的是在全局web.xml的配置
 

3. exception对象

    仅在当前页是错误页才起作用
jsp中
<%=exception.getClass()%>
<%=exception.getMessage()%>

4. out对象

    页面输出流
 

5. pageContext对象

         pageContext是页面上下文的意思,也就是说和页面相关的都可以在这里面找到,我们知道数据存放有四大域,范围分别叫做page、reuqest、session、application,这个对象可以取到这些里面的任意属性或者添加任意属性,主要如下:
取值:
getAttribute(String name);//page范围
getAttribute(String name,intScope);//指定范围,此处可用PageContext.PAGE_SCOPE等方法获得范围整数值
赋值同理
试验一下看看详情:
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
 
<body>
<%
//默认范围:page
pageContext.setAttribute("page","hello");
//范围 request,首先是直接给request加属性,然后通过pageContext加属性
request.setAttribute("request","hello");
pageContext.setAttribute("request2","hello",PageContext.REQUEST_SCOPE);
//范围 session,首先是直接给session加属性,然后通过pageContext加属性
session.setAttribute("session","hello");
pageContext.setAttribute("session2","hello",PageContext.SESSION_SCOPE);
//范围 application,首先是直接给 application加属性,然后通过pageContext加属性
application.setAttribute("application","hello");
pageContext.setAttribute("application2","hello",PageContext.APPLICATION_SCOPE);
 
//获取上面的值:
out.println("page变量所在范围:"+pageContext.getAttributesScope("page")+"<br>");
out.println("request变量所在范围:"+pageContext.getAttributesScope("request")+"<br>");
out.println("request2变量所在范围:"+pageContext.getAttributesScope("request2")+"<br>");
out.println("session变量所在范围:"+pageContext.getAttributesScope("session")+"<br>");
out.println("session2变量所在范围:"+pageContext.getAttributesScope("session2")+"<br>");
out.println("application变量所在范围:"+pageContext.getAttributesScope("application")+"<br>");
out.println("application2变量所在范围:"+pageContext.getAttributesScope("application2")+"<br>");
 
%>
</body>
</html>
 
得出的结果是:
page变量所在范围:1
request变量所在范围:2
request2变量所在范围:2
session变量所在范围:2
session2变量所在范围:3
application变量所在范围:2
application2变量所在范围:4
 
除此之外pageContext对象还可以获得其他内置对象:
ServletRequest getRequest();
ServletResponse getResponse();
ServletConfig getServletConfig();
ServletContext getServletContext();
HttpSession getSession();
 

6.request对象

先粘贴一些方法吧,因为这个太常用了,所以最好都掌握了
Object getAttribute(String name)
Returns the value of the named attribute as an Object, or nullif no attribute of the given name exists.
Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this request.
String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1if the length is not known.
String getContentType()
Returns the MIME type of the body of the request, or nullif the type is not known.
ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.
String getLocalAddr()
Returns the InternetProtocol(IP) address of the interface on which the request was received.
Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
Enumeration getLocales()
Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header.
String getLocalName()
Returns the host name of the InternetProtocol(IP)interface on which the request was received.
int getLocalPort()
Returns the InternetProtocol(IP) port number of the interface on which the request was received.
String getParameter(String name)
Returns the value of a request parameter as a String, or nullif the parameter does not exist.
Map getParameterMap()
Returns a java.util.Map of the parameters of this request.
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request.
String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given request parameter has, or nullif the parameter does not exist.
String getProtocol()
Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion,for example, HTTP/1.1.
BufferedReader getReader()
Retrieves the body of the request as character data using a BufferedReader.
String getRealPath(String path)
Deprecated.As of Version2.1 of the JavaServlet API, use ServletContext.getRealPath(java.lang.String) instead.
String getRemoteAddr()
Returns the InternetProtocol(IP) address of the client or last proxy that sent the request.
String getRemoteHost()
Returns the fully qualified name of the client or the last proxy that sent the request.
int getRemotePort()
Returns the InternetProtocol(IP) source port of the client or last proxy that sent the request.
RequestDispatcher getRequestDispatcher(String path)
Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
String getScheme()
Returns the name of the scheme used to make this request,for example, http, https, or ftp.
String getServerName()
Returns the host name of the server to which the request was sent.
int getServerPort()
Returns the port number to which the request was sent.
boolean isSecure()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
void removeAttribute(String name)
Removes an attribute from this request.
void setAttribute(String name,Object o)
Stores an attribute in this request.
void setCharacterEncoding(String env)
Overrides the name of the character encoding used in the body of this request.
 
 
GET和POST方式的区别:
         get方式显式的将参数放在了url的后面并且对数据量大小有限制,而post方式会放入到HTML HEADER中,传输数据可以无限大,安全性相对较高。
 
通常解决乱码诀窍:
byte[] rawByte = rawName.getBytes("ISO-8859-1");
String name =newString(rawByte,"utf-8");
当我们用其进行页面跳转时:forward会传递请求参数。还有,下面这个path必须以"/"开头
RequestDispatcher getRequestDispatcher(String path)

7. response对象

     记得要在response中加入cookie,才能在request中去提取出来显示!
    cookie存取中文比较麻烦,需要借助一些东西,比如:
存的时候:
Cookie c =newCookie("name", java.net.URLEncoder.encode("孙悟空","gbk"));
取的时候:
out.println(java.net.URLEncoder.encode(cookie.getValue()));
主要方法:
void addCookie(Cookie cookie)
Adds the specified cookie to the response.
void addDateHeader(String name,long date)
Adds a response header with the given name and date-value.
void addHeader(String name,String value)
Adds a response header with the given name and value.
void addIntHeader(String name,int value)
Adds a response header with the given name and integer value.
boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
String encodeRedirectUrl(String url)
Deprecated.As of version 2.1, use encodeRedirectURL(String url) instead
String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or,if encoding is not needed, returns the URL unchanged.
String encodeUrl(String url)
Deprecated.As of version 2.1, use encodeURL(String url) instead
String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or,if encoding is not needed, returns the URL unchanged.
void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
void sendError(int sc,String msg)
Sends an error response to the client using the specified status.
void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.
void setDateHeader(String name,long date)
Sets a response header with the given name and date-value.
void setHeader(String name,String value)
Sets a response header with the given name and value.
void setIntHeader(String name,int value)
Sets a response header with the given name and integer value.
void setStatus(int sc)
Sets the status code forthis response.
void setStatus(int sc,String sm)
Deprecated.As of version 2.1, due to ambiguous meaning of the message parameter.To set a status code use setStatus(int), to send an error with a description use sendError(int,String).Sets the status code and message forthis response.
 
 

8. session对象

    session里面存放的数据可以保留到浏览器关闭为止。
Object getAttribute(String name)
Returns the object bound with the specified name in this session, or nullif no object is bound under the name.
Enumeration getAttributeNames()
Returns an Enumeration of String objects containing the names of all the objects bound to this session.
long getCreationTime()
Returns the time when this session was created, measured in milliseconds since midnight January1,1970 GMT.
String getId()
Returns a string containing the unique identifier assigned to this session.
long getLastAccessedTime()
Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January1,1970 GMT, and marked by the time the container received the request.
int getMaxInactiveInterval()
Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
ServletContext getServletContext()
Returns the ServletContext to which this session belongs.
HttpSessionContext getSessionContext()
Deprecated.As of Version2.1,this method is deprecated and has no replacement.It will be removed in a future version of the JavaServlet API.
Object getValue(String name)
Deprecated.As of Version2.2,this method is replaced by getAttribute(java.lang.String).
String[] getValueNames()
Deprecated.As of Version2.2,this method is replaced by getAttributeNames()
void invalidate()
Invalidatesthis session then unbinds any objects bound to it.
boolean isNew()
Returnstrueif the client does not yet know about the session or if the client chooses not to join the session.
void putValue(String name,Object value)
Deprecated.As of Version2.2,this method is replaced by setAttribute(java.lang.String, java.lang.Object)
void removeAttribute(String name)
Removes the object bound with the specified name from this session.
void removeValue(String name)
Deprecated.As of Version2.2,this method is replaced by removeAttribute(java.lang.String)
void setAttribute(String name,Object value)
Binds an object to this session, using the name specified.
void setMaxInactiveInterval(int interval)
Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

猜你喜欢

转载自kissuyoyo.iteye.com/blog/2342902
今日推荐