`
kissuyoyo
  • 浏览: 15148 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

JSP指令及九大内置对象

    博客分类:
  • web
 
阅读更多

一.三个编译指令

常见的编译指令:
       (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对象。
    (2String getInitParameter(String name()):返回初始化参数的值。
    (3Enumeration 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.
分享到:
评论

相关推荐

    jsp九大内置对象讲解

    JSP九大内置对象详解 JSP(Java Server Pages)是一种基于Java技术的服务器端编程语言,用于创建动态网页。JSP九大内置对象是JSP技术中非常重要的一部分,它们是JSP引擎提供的一些预定义的对象,用于帮助开发者快速...

    jsp九个内置对象 六个基本动作 三个指令元素

    ### JSP九个内置对象 六个基本动作 三个指令元素 #### 四种属性范围 ...以上就是JSP中四个作用域、九个内置对象、六个基本动作及三个指令元素的基本介绍,希望能帮助您更好地理解和使用JSP技术。

    JSP的九个内置对象及四个作用域

    JSP 九个内置对象及四个作用域 JSP(Java Server Pages)是一种基于Java的服务器端脚本语言,用于生成动态网页。在JSP中,九个内置对象是指不需要预先声明就可以在脚本代码和表达式中使用的对象,这些对象都是javax...

    JSP内置对象之域对象和JSP指令

    ### JSP内置对象之域对象和JSP指令详解 #### JSP内置对象之域对象 在JSP技术中,有几种内置对象被称为“域对象”,它们用于存储数据,并且具有不同的作用范围。这些域对象包括`pageContext`、`request`、`session`...

    jsp主要九大内置对象、四大web域、两种包含、两种注释、几个jsp标准动作

    以下是JSP的九大内置对象: 1. **request**:HttpServletRequest对象,用于获取HTTP请求中的数据,如参数、头信息和请求属性。 2. **response**:HttpServletResponse对象,负责向客户端发送响应,包括设置状态码...

    JSP 9 大内置对象介绍

    ### JSP 九大内置对象详解 #### 一、Request对象 `request`对象在Java Server Pages(JSP)中主要用于获取客户端发送来的请求信息。它实现了`HttpServletRequest`接口,提供了丰富的API来处理HTTP请求。 - **`...

    JSP语法与内置对象课件

    1. **指令(Directives)**: JSP指令是用于配置整个JSP页面的信息,如页面编码、导入Java包等。例如,`; charset=UTF-8" %&gt;` 设置了页面的编程语言和内容类型。 2. **脚本元素(Scripting Elements)**: 包括声明、...

    jsp内置对象及jsp复用

    **JSP内置对象及JSP复用** 在JavaServer Pages(JSP)技术中,内置对象是预定义的、可以直接在页面中使用的对象,无需通过`&lt;jsp:useBean&gt;`标签或者`new`关键字来创建。这些内置对象极大地简化了JSP页面的编程,提供...

    JSP中的内置对象-详细解析-------

    在JavaServer Pages (JSP) 技术中,内置对象是开发者无需显式创建即可使用的预定义对象。这些对象提供了一系列便利的功能,帮助开发者轻松地处理网页动态内容的生成。本篇文章将对JSP的5个常用内置对象进行详细解析...

    jsp第一阶段试卷,涉及JSP语法,内置对象及HTML编程

    9. **JSP指令**:`include`指令用于将文件嵌入JSP页面。 10. **JSP表达式输出**:`&lt;%="2"+"4"%&gt;`会输出结果`6`。 **三、编程题** 1. **显示日期时间**:使用`(); out.println(date); %&gt;`。 2. **login.jsp与treat....

    JSP内置对象(9个常用的内置对象)

    JSP2.0规范 博文链接:https://jimi68.iteye.com/blog/155582

    jsp内置对象编程

    本文详细介绍了 JSP 内置对象编程的基本概念和技术要点,包括 `out` 对象的使用、变量与函数的定义、JSP 指令的使用以及 `response` 对象的高级应用。通过学习这些知识点,开发人员可以更高效地使用 JSP 技术来构建...

    JSP的3个编译指令7个动作指令9个内置对象.rar_java

    **JSP(Java Server Pages)** 是一种动态网页技术,由Sun Microsystems开发,现在已被Oracle公司维护。...JSP的核心在于将内容的生成...在实际开发中,结合使用这些指令、动作和内置对象,可以构建出复杂的动态Web应用。

    JSP上课课件-JSP语法与内置对象

    JSP(JavaServer Pages)是一种动态网页技术,它允许开发者将Java代码嵌入到HTML页面中,以实现...在实际工作中,了解和熟练运用JSP内置对象可以极大地提高开发效率,同时理解JSP语法能确保代码的正确性和可维护性。

    Web技术及应用实验3JSP内置对象.pdf

    JSP内置对象的使用和应用实验 本实验旨在熟悉JSP内置对象的使用和应用,包括request、response、session等对象的使用。通过实验,学生可以熟悉JSP内置对象的使用,掌握如何在JSP页面中使用这些对象来实现不同功能。...

    JSP脚本元素、指令、内建对象

    主要介绍JSP的两种注释、三脚本、七动作、九内建对象

    jsp有哪些内置对象?作用分别是什么?分别有什么方法?

    在JSP中,有9个内置对象,它们是预定义的,可以直接在JSP页面中使用,无需显式声明。下面是这些内置对象的详细说明,以及它们的主要方法: 1. **request**:这个对象代表`HttpServletRequest`,它包含了来自客户端...

    jsp指令,page指令简单介绍

    当`isErrorPage`属性值为`true`时,JSP引擎会提供两个内置对象:`javax.servlet.jsp.error.PageContext`和`javax.servlet.jsp.el.ExceptionELResolver`,以便于访问和处理错误信息。示例代码如下: ```jsp ``` 在...

    浅析JSP的9大内置对象和4大作用域对象

    此外,JSP页面还允许开发者通过page指令和taglib指令等自定义指令来增强页面的功能和可维护性,这些指令虽然不是内置对象,但在JSP页面的开发中也占据重要的位置。 总之,深入理解和熟练运用JSP的内置对象和作用域...

    jsp内置对象

    以下是JSP中的九大内置对象及其类型: 1. **pageContext** - `javax.servlet.jsp.PageContext` - 控制JSP页面的执行流程,提供访问其他内置对象的方法。 2. **request** - `javax.servlet....

Global site tag (gtag.js) - Google Analytics