JSP基础知识

 本篇依然为基础篇,主要讲解Jsp的9个内置对象。Jsp的内置对象为Servlet API的类或接口的实例化,它们的实例化过程由Jsp标准自动进行,意即:我们可以直接使用这些对象,而不需要声明它,这些内置对象分别为:application, config,response,request,exception,out,page,pagecontext,session;接下来,我就分别对几个主要对象的特性进行详细阐述:

1.application对象

它是javax.servlet.ServletContext类的对象,一般来说,它就代表整个WEB应用,对于它的属性值,在整个WEB应用(JSP或Servlet类)中都是公用的,最常用的方法是:setAttribute(name,value)和getAttribute(name);为此来做个测试:在同一个WEB工程中编写两个JSP文件,index.jsp如下:

  1. <%@ page language="java" import="java.util.*" %>  
  2. <%@ page pageEncoding="ISO-8859-1"%>  
  3. <html>  
  4.   <%!  
  5.     private int count = 0;  
  6.     public Integer getCount()  
  7.     {  
  8.         count ++ ;  
  9.         return count;  
  10.     }  
  11.   %>  
  12.   <body>  
  13.     <%  
  14.         application.setAttribute("count",getCount().toString());  
  15.         out.println("the value of count is :"+count);     %>  
  16.    </body>  
  17. </html>  

test_application.jsp内容如下:

  1. <%@page language="java" contentType="text/html; charset=ISO-8859-1"  %>  
  2. <html>  
  3.     <head>  
  4.         <title>测试application</title>  
  5.     </head>  
  6.     <body>  
  7.         <%out.println("get the value of count,the count is a field of application,value: "); %>  
  8.         <%=application.getAttribute("count")%>  
  9.     </body>  
  10. </html>  


我们先启动服务器,访问http://localhost:8080/index.jsp,其结果如下:

the value of count is :2,

每刷新一次页面,count的值就增1,此时我们再访问http://localhost:8080/test_application.jsp,其结果显示如下:

get the value of count,the count is a field of application,value: 2

没有进行任何参数传递,也没有直接获取javabean的属性,而是通过application对象,先设置属性(application.setAttribute("count",getCount().toString());),再从另一个页面中获得属性(application.getAttribute("count"))就能做到属性的全局共享,这便是使用application对象的作用。

 

application对象的另外一个强大作用就是能用来解析WEB.XML的配置信息,以下就是一个完整的连接和查询mysql数据库的例子,而访问数据库的url,密码,用户名等信息,均存储在web.xml中,在JSP文件中用application对象读取参数属性。

  1. <%@ page language="java" import="java.util.*" %>  
  2. <%@ page pageEncoding="ISO-8859-1"%>  
  3. <%@page import="java.sql.SQLException"%>  
  4. <%@page import="java.net.ConnectException"%>  
  5. <%@page import="java.sql.DriverManager"%>  
  6. <%@page import="java.sql.*" %>  
  7. <html>  
  8.   <body>  
  9.     <%   
  10.         Connection conn=null;  
  11.         Statement state=null;  
  12.         ResultSet rs=null;  
  13.         String driver=application.getInitParameter("driver");  
  14.         String url=application.getInitParameter("url");  
  15.         String user=application.getInitParameter("user");  
  16.         String password=application.getInitParameter("password");  
  17.         try{   
  18.              Class.forName(driver);  
  19.              conn=DriverManager.getConnection(url,user,password);  
  20.         }catch(SQLException e) {   
  21.             out.println("failed to connect the db");  
  22.         } catch(ClassNotFoundException e){  
  23.             out.println("can't find the driver class");  
  24.         }  
  25.         try{  
  26.             state=conn.createStatement();  
  27.             String queryAll="select*from user_information";  
  28.             rs=state.executeQuery(queryAll);  
  29.             while(rs.next())  
  30.             {  
  31.              int userid=rs.getInt(1);  
  32.              String username=rs.getString(2);  
  33.              String userpassword=rs.getString(3);  
  34.                
  35.              out.println("user id is: "+userid);  
  36.              out.println("user name is: "+username);  
  37.              out.println("user password is: "+userpassword);  
  38.             }   
  39.         }catch(SQLException e){  
  40.             out.println("research fialed!");  
  41.         }  
  42.         try{  
  43.             if(rs != null){  
  44.                 rs.close();  
  45.             }  
  46.             if(state != null){  
  47.                 state.close();            
  48.             }  
  49.             if(conn != null){  
  50.                 conn.close();  
  51.             }  
  52.         }catch(Exception e){  
  53.             out.println("error when close db");  
  54.         }  
  55.      %>  
  56.    </body>  
  57. </html>  


web.xml的完整信息如下:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <welcome-file-list>  
  8.     <welcome-file>index.jsp</welcome-file>  
  9.   </welcome-file-list>  
  10.   <context-param>  
  11.         <param-name>driver</param-name>  
  12.         <param-value>com.mysql.jdbc.Driver</param-value>  
  13.   </context-param>  
  14.   <context-param>  
  15.         <param-name>user</param-name>  
  16.         <param-value>root</param-value>  
  17.   </context-param>  
  18.   <context-param>  
  19.         <param-name>password</param-name>  
  20.         <param-value>900622</param-value>  
  21.   </context-param>  
  22.   <context-param>  
  23.         <param-name>url</param-name>  
  24.         <param-value>jdbc:mysql://localhost:3306/test_db</param-value>  
  25.   </context-param>  
  26. </web-app>  


页面执行结果为:

user id is: 1 user name is: James user password is: 123456

 2. pageContext对象


pageContext对象可以用来访问和设置各种范围的属性(包括page,request,session和application),事实上,如果给各种范围的属性设置成相同的属性名,那么各属性是互不影响的,这就相当于C++中同名变量在不同的生存范围内互不影响(如同名的全局变量和局部变量),而pageContext通常用来获得和设置各种范围的属性值,看下面实例:

  1.  <body>  
  2.     <%  
  3.               //使用不同内置对象设置不同范围属性  
  4.               pageContext.setAttribute("name","page_James");  //设置page范围属性  
  5.               request.setAttribute("name","request_James"); //设置request范围属性  
  6.               session.setAttribute("name","session_James"); //设置session范围属性  
  7.               application.setAttribute("name","application_James"); //设置application范围属性  
  8.               //使用pageContext设置不同范围属性  
  9.               pageContext.setAttribute("age","30");  //不指定属性的范围时默认为page范围  
  10.               pageContext.setAttribute("age","40",pageContext.REQUEST_SCOPE);  
  11.               pageContext.setAttribute("age","50",pageContext.SESSION_SCOPE);  
  12.               pageContext.setAttribute("age","60",pageContext.APPLICATION_SCOPE);  
  13.            %>  
  14.            <%="page范围的name值:"+(String)pageContext.getAttribute("name",pageContext.PAGE_SCOPE)%><br/>  
  15.            <%="page范围的age值: "+(String)pageContext.getAttribute("age",pageContext.PAGE_SCOPE) %><br/>  
  16.            <%="request范围name值: "+(String)pageContext.getAttribute("name",pageContext.REQUEST_SCOPE)%><br/>  
  17.            <%="request范围age值:"+(String)pageContext.getAttribute("age",pageContext.REQUEST_SCOPE) %><br/>  
  18.            <%="session范围name值: "+(String)pageContext.getAttribute("name",pageContext.SESSION_SCOPE) %><br/>  
  19.            <%="session范围age值:"+(String)pageContext.getAttribute("age",pageContext.SESSION_SCOPE) %><br/>  
  20.            <%="application范围name值:"+(String)pageContext.getAttribute("name",pageContext.APPLICATION_SCOPE) %><br/>  
  21.            <%="application范围name值:"+(String)pageContext.getAttribute("age",pageContext.APPLICATION_SCOPE) %>  
  22.   </body>  

其页面执行结果如下:

page范围的name值:page_James
page范围的age值: 30
request范围name值: request_James
request范围age值:40
session范围name值: session_James
session范围age值:50
application范围name值:application_James
application范围name值:60


3. request对象

 

 request对象是个很重要的对象,它被用于封装一次的用户请求参数,请求参数可以是表单值,可以是以request对象设置的属性值,也可以是url地址中所附带的少量字符串参数。  我们来看下面实例:

index.jsp的body部分

  1. <body>  
  2.         <%  
  3.     ArrayList<String> list = new ArrayList<String>() ;  
  4.     list.add("this");  
  5.     list.add(" is");  
  6.     list.add(" the");  
  7.     list.add(" list");  
  8.     for(int i = 0 ;i<list.size();i++)  
  9.     {  
  10.         out.println(list.get(i));  
  11.     }  
  12.     request.setAttribute("list",list);  
  13.  %>  
  14.   
  15.         <form action="request.jsp" id="form" method="post" >  
  16.             用户名:<input type="text" name="username"><hr/>  
  17.             密    码:<input type="text" name="userpwd"><hr/>  
  18.             <input type="submit" value="提   交">  
  19.         </form>  
  20. </body>  
request.jsp的body部分:

  1. <body>  
  2.         <%="user name is: "+request.getParameter("username")  %><br/>  
  3.         <%="user password is: "+request.getParameter("userpwd") %><br/>  
  4.         <%  
  5.             ArrayList<String> list = (ArrayList<String>)request.getAttribute("list");  
  6.             for(int i = 0 ;i<list.size() ; i++)  
  7.             {  
  8.                 out.println(list.get(i));  
  9.             }  
  10.          %>  
  11.     </body>  

大概看来,这段代码应该没错,如果我们在“用户名”中输入:james,在“密码”中输入:admin,那么,我们预料的显示结果应该是

user name is :james

user password is: admin

this is the list

而事实上,请求提交后,页面出错,显示一堆错误信息。

在这里要注意,提交请求和页面跳转是两个不同的概念,范围属性和请求参数也是两个不同的概念,提交请求后,请求参数会被servlet封装到request对象中,这一点毋庸置疑,但不会将属性也封装到servlet中,只有当发生< jsp:forward>跳转时,才会将属性提交到要转发的页面,如果我们将index.jsp改为如下:

  1. <body>  
  2.         <%  
  3.     ArrayList<String> list = new ArrayList<String>() ;  
  4.     list.add("this");  
  5.     list.add(" is");  
  6.     list.add(" the");  
  7.     list.add(" list");  
  8.     for(int i = 0 ;i<list.size();i++)  
  9.     {  
  10.         out.println(list.get(i));  
  11.     }  
  12.     request.setAttribute("list",list);  
  13.  %>  
  14.  <%  
  15.     ArrayList<String> list2 = new ArrayList<String>();  
  16.     list2 = (ArrayList<String>)pageContext.getAttribute("list",pageContext.REQUEST_SCOPE);  
  17.     for(int i = 0 ;i<list2.size() ; i++)  
  18.     {  
  19.         out.println(list.get(i));  
  20.     }  
  21.  %>  
  22.  <jsp:forward page="request.jsp"></jsp:forward> // !!!!!注意多加了这一句!!!  
  23.         <form action="request.jsp" id="form" method="post" >  
  24.             用户名:<input type="text" name="username"><hr/>  
  25.             密    码:<input type="text" name="userpwd"><hr/>  
  26.             <input type="submit" value="提   交">  
  27.         </form>  
  28. </body>  
那么request.jsp的显示内容将又会为:

user name is:null

user password is:null

this is the list

index.jsp中未提交请求前就发生跳转,所以name和password值没有设置,而forward跳转会传递属性,所以会在跳转页面request.jsp中正常接收。


4. response和out对象


response对象和out对象都是用来向页面输出信息的流对象,其不同之处在于:out对象只能输出字符流(只能输出文字),却不能输出字节流(如位图),而response对象却可以做到这一点;在大多数情况下,out完全可以替代response的作用,而有时候response的功能却不容忽视,甚至起关键作用:如可以创建cookie,可以设置定时刷新的页面,可以不使用forward跳转来实现不带属性的跳转。 以下来看一下response创建cookie的示例:

在index.jsp中代码如下:

  1. <body>  
  2.         <form action="request.jsp" id="form" method="post" >  
  3.             用户名:<input type="text" name="username"><hr/>  
  4.             密    码:<input type="text" name="userpwd"><hr/>  
  5.             <input type="submit" value="提   交">  
  6.         </form>  
  7. </body>  

在request.jsp中代码如下:

  1. <body>  
  2.         <%  
  3.             String userName = request.getParameter("username");   
  4.             String userPassword = request.getParameter("userpwd");  
  5.             Cookie nameCookie = new Cookie("username",userName); //创建cookie  
  6.             nameCookie.setMaxAge(24*3600);//设置生存时间为24小时  
  7.             Cookie pwdCookie = new Cookie("userpwd",userPassword);  
  8.             pwdCookie.setMaxAge(24*3600);  
  9.             response.addCookie(nameCookie); //添加cookie  
  10.             response.addCookie(pwdCookie);  
  11.          %>  
  12.                  <jsp:forward page="prove.jsp"></jsp:forward>   
  13. </body>  
这样,凡是客户端输出用户名和密码的话,其便会存储在客户端的硬盘中,24小时后就自动清除,如此可以提供更友好的服务。


我们继续创建一个验证页: prove.jsp,其代码如下:

  1. <body>  
  2.         <%  
  3.             Cookie cookies[] = request.getCookies();  
  4.             for(Cookie c:cookies)  
  5.             {  
  6.                 if(c.getName().equals("username") || c.getName().equals("userpwd"))  
  7.                 {  
  8.                     out.println(c.getName()+":"+c.getValue());  
  9.                 }  
  10.             }  
  11.          %>  
  12.   </body>  

在index.jsp页面中的用户名中填入:James,在密码中输入:admin,

此时页面显示结果为:

username:James    userpwd:admin

事实上,在24小时内任意时间段输入http://jxpc-001:8080/ExtJs/request.jsp,那么网页最终都会显示为这样的结果。

5. session对象

对于session对象,我不打算多述,因为其作用基本与request相同,只是生命周期比request要长,从浏览器打开到关闭浏览器,如同一个单网页下设置了一个session范围属性和request范围属性,当页面关闭时,session范围属性我们可以不用forward跳转而在任何地方获得,其都不会丢失,而request范围属性,在关闭网页后,任何一个非forward跳转页中均获取不到,因为它的生命周期只在一次forward之间,断开这次forward,其属性会丢失掉。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值