JSP简单运行原理----------九大隐式对象和四大域对象

本文详细介绍了JSP中的pageContext对象及其重要性,包括它如何封装其他八大隐式对象以及作为域对象的功能。讨论了page、request、session和application四个域对象的使用和区别,强调了它们在数据存储和传递中的作用。同时,讲解了JSP运行原理和九大隐式对象,展示了下载文件和计数的代码示例。此外,还涵盖了EL表达式在集合输出中的应用以及HTTP协议的基础知识,如请求响应和状态码。最后提到了JSP开发、数据库操作以及如何利用Session防止表单重复提交。
摘要由CSDN通过智能技术生成

1.getServletConfig()  

        在servlet初始化时,容器传递进来一个ServletConfig对象并保存在servlet实例中,该对象允许访问两项内容:初始化参数和

 ServletContext对象,前者通常由容器在文件中指定,

  允许在运行时向sevrlet传递有关调度信息,比如说getServletConfig().getInitParameter("debug")后者为servlet提供有关容器的信息。

 此方法可以让servlet在任何时候获得该对象及配置信息。  

 

getServletContext()  

   一个servlet可以使用getServletContext()方法得到web应用的servletContext即而使用getServletContext的一些方法来获得一些值,比如说getServletContext().getRealPath("/")来获得系统绝对路径,getServletContext().getResource("WEB-INF/config.xml")来获得xml文件的内容。

 

getServletContext()取得的是 <context-param>配置的参数 

getServletConfig()取得的是 <servlet> <init-param>配置的参数

 2: getServletContext()应用于整个web App,而getServletConfig()仅应用于当前Servlet。 但是ServletConfig对象拥有ServletContext的引用。所以可以通过getServletConfig()来获得web App的初始值。

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

pageContext对象

 

pageContext对象

    pageContext对象是JSP技术中最重要的一个对象,它代表JSP页面的运行环境,这个对象不仅封装了对其它8大隐式对象的引用,它自身还是一个域对象,可以用来保存数据。并且,这个对象还封装了web开发中经常涉及到的一些常用操作,例如引入和跳转其它资源、检索其它域对象中的属性等。

通过pageContext获得其他对象

    getException方法返回exception隐式对象

    getPage方法返回page隐式对象

    getRequest方法返回request隐式对象

    getResponse方法返回response隐式对象

    getServletConfig方法返回config隐式对象

    getServletContext方法返回application隐式对象

    getSession方法返回session隐式对象

    getOut方法返回out隐式对象

    pageContext封装其它8大内置对象的意义,思考:如果在编程过程中,把pageContext对象传递给一个普通java对象,那么这个java对象将具有什么功能? 

pageContext作为域对象

pageContext对象的方法

    public void setAttribute(java.lang.String name,java.lang.Object value)

    public java.lang.Object getAttribute(java.lang.String name)

    public void removeAttribute(java.lang.String name)

pageContext对象中还封装了访问其它域的方法

    public java.lang.Object getAttribute(java.lang.String name,int scope)

    public void setAttribute(java.lang.String name, java.lang.Object value,int scope)

    public void removeAttribute(java.lang.String name,int scope)

代表各个域的常量

    PageContext.APPLICATION_SCOPE

    PageContext.SESSION_SCOPE

    PageContext.REQUEST_SCOPE

    PageContext.PAGE_SCOPE

findAttribute方法    (*重点,查找各个域中的属性)

引入和跳转到其他资源

    PageContext类中定义了一个forward方法和两个include方法来分别简化和替代RequestDispatcher.forward方法和include方法。

方法接收的资源如果以“/”开头, “/”代表当前web应用。

JSP标签

    JSP标签也称之为Jsp Action(JSP动作)元素,它用于在Jsp页面中提供业务逻辑功能,避免在JSP页面中直接编写java代码,造成jsp页面难以维护。

JSP常用标签

1、<jsp:include>标签 

    <jsp:include>标签用于把另外一个资源的输出内容插入进当前JSP页面的输出内容之中,这种在JSP页面执行时的引入方式称之为动态引入。

语法:

       <jsp:include page="relativeURL | <%=expression%>" flush="true|false" />

 

page属性用于指定被引入资源的相对路径,它也可以通过执行一个表达式来获得。

flush属性指定在插入其他资源的输出内容时,是否先将当前JSP页面的已输出的内容刷新到客户端。 

<jsp:include>与include指令的比较

    <jsp:include>标签是动态引入, <jsp:include>标签涉及到的2个JSP页面会被翻译成2个servlet,这2个servlet的内容在执行时进行合并。

而include指令是静态引入,涉及到的2个JSP页面会被翻译成一个servlet,其内容是在源文件级别进行合并。

不管是<jsp:include>标签,还是include指令,它们都会把两个JSP页面内容合并输出,所以这两个页面不要出现重复的HTML全局架构标签,否则输出给客户端的内容将会是一个格式混乱的HTML文档。

 

 

2、<jsp:forward>标签 

    <jsp:forward>标签用于把请求转发给另外一个资源。

语法:

       <jsp:forward page="relativeURL | <%=expression%>" />

page属性用于指定请求转发到的资源的相对路径,它也可以通过执行一个表达式来获得。

 

3、<jsp:param>标签 

    当使用<jsp:include>和<jsp:forward>标签引入或将请求转发给其它资源时,可以使用<jsp:param>标签向这个资源传递参数。

语法1:

       <jsp:include page="relativeURL | <%=expression%>">

              <jsp:param name="parameterName" value="parameterValue|<%= expression %>" />

       </jsp:include>

语法2:

       <jsp:forward page="relativeURL | <%=expression%>">

              <jsp:param name="parameterName" value="parameterValue|<%= expression %>" />

       </jsp:include>

<jsp:param>标签的name属性用于指定参数名,value属性用于指定参数值。在<jsp:include>和<jsp:forward>标签中可以使用多个<jsp:param>标签来传递多个参数。

映射JSP

<servlet>

       <servlet-name>SimpleJspServlet</servlet-name>

       <jsp-file>/jsp/simple.jsp</jsp-file>

       <load-on-startup>1</load-on-startup >

</servlet>

       ……

<servlet-mapping>

       <servlet-name>SimpleJspServlet</servlet-name>

       <url-pattern>/xxx/yyy.html</url-pattern>

</servlet-mapping>

如何查找JSP页面中的错误

    JSP页面中的JSP语法格式有问题,导致其不能被翻译成Servlet源文件,JSP引擎将提示这类错误发生在JSP页面中的位置(行和列)以及相关信息。

    JSP页面中的JSP语法格式没有问题,但被翻译成的Servlet源文件中出现了Java语法问题,导致JSP页面翻译成的Servlet源文件不能通过编译,JSP引擎也将提示这类错误发生在JSP页面中的位置(行和列)以及相关信息。

    JSP页面翻译成的Servlet程序在运行时出现异常,这与普通Java程序的运行时错误完全一样,Java虚拟机将提示错误发生在Servlet源文件中的位置(行和列)以及相关信息。

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

 

page,request,session,application四个域对象的使用及区别

 

1.page指当前页面。只在一个jsp页面里有效 。
2.request 指从http请求到服务器处理结束,返回响应的整个过程。在这个过程中使用forward方式跳转多个jsp。在这些页面里你都可以使用这个变量。 
3.Session 有效范围当前会话,从浏览器打开到浏览器关闭这个过程。 
4.application它的有效范围是整个应用。 
作用域里的变量,它们的存活时间是最长的,如果不进行手工删除,它们就一直可以使用 
page里的变量没法从index.jsp传递到test.jsp。只要页面跳转了,它们就不见了。 
request里的变量可以跨越forward前后的两页。但是只要刷新页面,它们就重新计算了。 
session和application里的变量一直在累加,开始还看不出区别,只要关闭浏览器,再次重启浏览器访问这页,session里的变量就重新计算了。 
application里的变量一直在累加,除非你重启tomcat,否则它会一直变大。 
而作用域规定的是变量的有效期限。 
如果把变量放到pageContext里,就说明它的作用域是page,它的有效范围只在当前jsp页面里。 
从把变量放到pageContext开始,到jsp页面结束,你都可以使用这个变量。 
如果把变量放到request里,就说明它的作用域是request,它的有效范围是当前请求周期。 
所谓请求周期,就是指从http请求发起,到服务器处理结束,返回响应的整个过程。在这个过程中可能使用forward的方式跳转了多个jsp页面,在这些页面里你都可以使用这个变量。
如果把变量放到session里,就说明它的作用域是session,它的有效范围是当前会话。 
所谓当前会话,就是指从用户打开浏览器开始,到用户关闭浏览器这中间的过程。这个过程可能包含多个请求响应。也就是说,只要用户不关浏览器,服务器就有办法知道这些请求是一个人发起的,整个过程被称为一个会话(session),而放到会话中的变量,就可以在当前会话的所有请求里使用。
如果把变量放到application里,就说明它的作用域是application,它的有效范围是整个应用。 
整个应用是指从应用启动,到应用结束。我们没有说“从服务器启动,到服务器关闭”,是因为一个服务器可能部署多个应用,当然你关闭了服务器,就会把上面所有的应用都关闭了。
application作用域里的变量,它们的存活时间是最长的,如果不进行手工删除,它们就一直可以使用。 
与上述三个不同的是,application里的变量可以被所有用户共用。如果用户甲的操作修改了application中的变量,用户乙访问时得到的是修改后的值。这在其他scope中都是不会发生的,page, request, session都是完全隔离的,无论如何修改都不会影响其他人的数据。

 

pageContext对象的范围只适用于当前页面范围,即超过这个页面就不能够使用了。所以使用pageContext对象向其它页面传递参数是不可能的。 
request对象的范围是指在一JSP网页发出请求到另一个JSP网页之间,随后这个属性就失效。 
session的作用范围为一段用户持续和服务器所连接的时间,但与服务器断线后,这个属性就无效。比如断网或者关闭浏览器。 
application的范围在服务器一开始执行服务,到服务器关闭为止。它的范围最大,生存周期最长。

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

 

JSP运行原理和九大隐式对象及下载文件、访问次数的代码

  103人阅读  评论(0)  收藏  举报
 

JSP运行原理和九大隐式对象

        每个JSP 页面在第一次被访问时,WEB容器都会把请求交给JSP引擎(即一个Java程序)去处理。JSP引擎先将JSP翻译成一个_jspServlet(实质上也是一个servlet) ,然后按照servlet的调用方式进行调用。

由于JSP第一次访问时会翻译成servlet,所以第一次访问通常会比较慢,但第二次访问,JSP引擎如果发现JSP没有变化,就不再翻译,而是直接调用,所以程序的执行效率不会受到影响。

         JSP引擎在调用JSP对应的_jspServlet时,会传递或创建9个与web开发相关的对象供_jspServlet使用。JSP技术的设计者为便于开发人员在编写JSP页面时获得这些web对象的引用,特意定义了9个相应的变量,开发人员在JSP页面中通过这些变量就可以快速获得这9大对象的引用。

JSP九大隐式对象

request、response、config、application、exception、Session、page、out、pageContext

out隐式对象

out隐式对象用于向客户端发送文本数据。 

out对象是通过调用pageContext对象的getOut方法返回的,其作用和用法与ServletResponse.getWriter方法返回的PrintWriter对象非常相似。 

JSP页面中的out隐式对象的类型为JspWriter,JspWriter相当于一种带缓存功能的PrintWriter,设置JSP页面的page指令的buffer属性可以调整它的缓存大小,甚至关闭它的缓存。 

只有向out对象中写入了内容,且满足如下任何一个条件时,out对象才去调用ServletResponse.getWriter方法,并通过该方法返回的PrintWriter对象将out对象的缓冲区中的内容真正写入到Servlet引擎提供的缓冲区中:

设置page指令的buffer属性关闭了out对象的缓存功能

out对象的缓冲区已满

整个JSP页面结束

pageContext对象

pageContext对象是JSP技术中最重要的一个对象,它代表JSP页面的运行环境,这个对象不仅封装了对其它8大隐式对象的引用,它自身还是一个域对象,可以用来保存数据。并且,这个对象还封装了web开发中经常涉及到的一些常用操作,例如引入和跳转其它资源、检索其它域对象中的属性等。

通过jsp写文件下载代码

<%@page import="java.io.OutputStream"%><%@page import="java.io.FileInputStream"%><%@page import="java.io.InputStream"%><%@page import="java.io.File"%><%@page import="java.net.URLEncoder"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%

   ServletContext context = this.getServletContext();

   String path = application.getRealPath("./images/da.jpg");

   //构造文件

   File file = new File(path);

   /*构造文件的输入流*/

   InputStream is = new FileInputStream(file);

   

   response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));

   OutputStream os   = response.getOutputStream();

   

   byte buffer[] = new byte[1024];

   int len=0;

    while((len=is.read(buffer))!=-1){

os.write(buffer,0,len);

}

os.flush();

os.close();

is.close();

%>

通过jsp写访问次数
 
<%@ page language="java" import="java.util.*"  pageEncoding="UTF-8"%>
<%int c=1;%>
<%Object count = application.getAttribute("count");%>
<%if(count ==null)
{application.setAttribute("count",c);%>
<%}else{application.setAttribute
("count",(Integer)(count)+1);}
out.println(count);
%>

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

 

总结出el表达式简单的集合输出方式

 

总结出el表达式简单的集合输出方式

一、EL简介
   1.语法结构
     ${expression}
   2.[].运算符
     EL 提供.[]两种运算符来存取数据。
     当要存取的属性名称中包含一些特殊字符,如.?等并非字母或数字的符号,就一定要使用 []。例如:
         ${user.My-Name}应当改为${user["My-Name"] }
     如果要动态取值时,就可以用[]来做,而.无法做到动态取值。例如:
         ${sessionScope.user[data]}data 是一个变量
   3.变量
     EL存取变量数据的方法很简单,例如:${username}。它的意思是取出某一范围中名称为username的变量。
     因为我们并没有指定哪一个范围的username,所以它会依序从PageRequestSessionApplication范围查找。
     假如途中找到username,就直接回传,不再继续找下去,但是假如全部的范围都没有找到时,就回传null
     属性范围在EL中的名称
         Page          PageScope
         Request          RequestScope
         Session          SessionScope
         Application      ApplicationScope
        
二、EL隐含对象
   1.与范围有关的隐含对象
   与范围有关的EL 隐含对象包含以下四个:pageScoperequestScopesessionScope applicationScope
   它们基本上就和JSPpageContextrequestsessionapplication一样;
   EL中,这四个隐含对象只能用来取得范围属性值,即getAttribute(String name)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSP Simple Examples Index 1. Creating a String In jsp we create a string as we does in a java. In jsp we can declare it inside the declaration directive or a scriptlet directive. String Length In java, Strings are objects that belong to class java.lang.String. A string is a sequence of simple characters. We can get the length of the string by using the method length() of java.lang.String. Declaring string array in java An array is the collection of same data type. Suppose if we have a declare an array of type String, then it will store only the String value not any other data type. When we have a closely related data of the same type and scope, it is better to declare it in an array. Multidimensional array java A two dimensional array can be thought as a grid of rows and columns. The first array will reflect to a row and the second one is column. int array Array is a collection of same data type. Suppose if we have declared an array of type int then the array will take only the int values and not any other data types. We can find find out the length of the variable by using the variable length . JSP string array String array cannot hold numbers or vice- versa. Arrays can only store the type of data specified at the time of declaring the array variable. Custom exceptions Custom Exception inherits the properties from the Exception class. Whenever we have declare our own exceptions then we call it custom exceptions. Throwing an exception All methods use the throw statement to throw an exception. The throw statement requires a single argument a throwable object. Here is an example of a throw statement. Arrayindexoutofboundsexception ArrayIndexOutOfBoundException is thrown when we have to indicate that an array has been accessed with an illegal index. printStackTrace in jsp printStackTrace is a method of the Throwable class. By using this method we can get more information about the error process if we print a stack trace from the exception. Runtime Errors Errors are arised when there is any logic problem with the logic of the program. Try catch in jsp In try block we write those code which can throw exception while code execution and when the exception is thrown it is caught inside the catch block. Multiple try catch We can have more than one try/catch block. The most specific exception which can be thrown is written on the top in the catch block following by the less specific least. Nested try catch We can declare multiple try blocks inside the try block. The most specific exception which can be thrown is written on the top in the catch block following by the less specific least. kilometers per liter to miles per gallon Kilometers per liter : The distance traveled by a vehicle which is running on gasoline or diesel fuel in a kilometer. Miles per Gallon: The distance traveled by a vehicle which is running on gasoline or diesel fuel in a mile. Ascii values table ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as @, #, $, and so on. ASCII was developed when non- printing characters were rarely used. life cycle of a jsp page Life of the the jsp page is just same as the servlet life cycle. After get translated the jsp file is just like a servlet. Page directive attributes A directive is a way to give special instructions to the container at page translation time. The page directive is written on the top of the jsp page. Html tags in jsp In this example we have used the html tag inside the println() method of the out implicit object which is used to write the content on the browser. Password Controls In this program we are going to know how the server determines whether the password entered by the user is correct or not. This whole process is controlled on the server side. Multiple forms in jsp The form tag creates a form for user input. A form can contain checkboxes, textfields, radio- buttons and many more. Forms are used to pass user- data to a specified URL which is specified in the action attribute of the form tag. Interface in jsp In interface none of its methods are implemented. All the methods are abstract. There is no code associated with an interface. In an interface all the instance methods are public and abstract. Interfaces are always implemented in the class. They add extra behaviors to the class. Inheritance in java with example Inheritance is one of the concept of the Object- Oriented programming. It allows you to define a general class, and later more specialized classes by simply adding some new details. Constructor inheritance Constructors are used to create objects from the class. Constructor declaration are just like method declaration, except that they do not have any return type and they use the name of the class. The compiler provides us with a default constructor to the class having no arguments. Abstract classes We does not make a object of the abstract class. This class must be inherited. Unlike interface the abstract class may implement some of the methods defined in the class, but in this class at least one method should be abstract. Using Super class Variables With Sub-classed Objects One of the strong features of java is that it is follows a OOPs concept, and one of the feature of OOP in java is that, we can assign a subclass object or variable to the variable of the superclass type. Log files Log files keeps a records of internet protocol addresses (IP), Http status, date, time, bytes sent, bytes recieved, number of clicks etc. Calculate a factorial by using while loop In this example we are going to find out the factorial of 12 by using the while loop. In while loop the loop will run until the condition we have given gets true. Calculating factorial After going through this example you will be understand how you can calculate the factorial by using recursion in jsp. To make a program on factorial, firstly it must be clear what is recursion. Celsius Fahrenheit Celsius is a unit to measure temperature scale on which water freezes at 0 degree and boiling point is 100 degree. This unit is discovered by Celsius in 1742, a Swedish astronomer and physicist, he has invented the centigrade, or Celsius thermometer divided between the freezing and boiling points of water into 100 parts. comment in jsp In a jsp we should always try to use jsp- style comments unless you want the comments to appear in the HTML. Jsp comments are converted by the jsp engine into java comments in the source code of the servlet that implements the Jsp page. Html tag inside out implicit object In this program we are going to use a html tag inside a out object. out object is used to display the content on the browser. To make this program run use out object inside which define some html code along with the content you want to display on the browser Jsp methods In this example we are going to show you how we can declare a method and how we can used it. In this example we are making a method named as addNum(int i, int b) which will take two numbers as its parameters and return integer value. Multiple methods Jsp is used mainly for presentation logic. In the jsp we can declare methods just like as we declare methods in java classes. Methods can be declared in either declaration directive or we can declare it in scriptlet. If we declare method inside declaration directive, then the method is applicable in the whole page. Passing Array method Array is a collection of similar data type. It is one of the simplest data structures. Arrays holds equally sized data elements generally of the similar data type. Two index In this example we will show how we can use two indexes in a for loop. We can solve this problem by using for loop defined inside the scriptlet directive. Date in JSP To print a Date in JSP firstly we are importing a class named java.util.Date of the package java.util. This package is imported in the jsp page so that the Date class and its properties can accessed in the JSP page. If- Else Ladder A ladder means a vertical set of steps. It is a computer generated list of pairings used in eliminations. Nested If We use the if condition to check if the particular condition is true then it should perform a certain task, and if a particular condition is not true then it should do some other tasks. Quintessential JSP Quintessential means representing the perfect example of a class or quality. It is pure and concentrated essence of a substance. Include File JSP using directive and include action <%@ include file = " "%>: - This is include directive. This directive has only one attribute named as file, which is used to include a file in the jsp page at the translation time. <jsp:include page = " ">:- This is known as the include standard action. This standard action is used to include a file at run time. This standard action is evaluated at the run time. Snoop in JSP It mostly contains the request information, ServletContext initialization parameters, ServetContext attributes, request headers, response headers etc. sendRedirect In JSP sendRedirect() method is a method of HttpServletResponse interface. In sendRedirect() the object of request will be generated again with the location of page which will perform the request of the client. Request Header in JSP Whenever an http client sends a request, it sends the request in the form of get or post method or any other HttpRequest methhods. It can also sends the headers with it. Specific request headers in JSP Whenever an http client sends a request, it can also sends the headers with it. All the headers are optional except Content-length, which is required only for POST request. Java class in JSP To use the class inside the jsp page we need to create an object of the class by using the new operator. At last use the instance of the class to access the methods of the java file. Setting Colors in JSP In Jsp also we can set the background color which we want, the font color can be changed. The table can be coloured . By using the colors code we can give colors according to our wish. Sine Table in JSP Mathematically, the sine of an angle is the ratio of the length of the opposite side to the length of the hypotenuse of an imaginary right triangle having that angle in it. Applet In Jsp Applets are small programs or applications written in java. These applets are those small programs that runs on web browsers, usually written in java. We can use the applets in jee also. In jee it runs on the context of web application on a client computer. Creating a Local Variable in JSP Consider a situation where we have to declare a variable as local, then we should declare the methods and variables in tag except the declaration directive. Method in Declaration Tag Anything which will be declared inside declaration tag will be applicable within the whole application. We call this tag a Declaration Tag. The syntax of this tag is <%! --------- %>. Forward a JSP Page The request object goes to the controller then the controller decides by which jsp or servlet this request will be processed, then the request object is passed to that jsp or servlet and the output is displayed to the browser by the response object. Random in JSP Random numbers are the numbers that are determined entirely by chance. User does not have any control over the working of random numbers. random() is a method of Math class which extends java.lang package. JSP include directive By using the include tag the file will be included in the jsp page at the translation time. In this example we have created a jsp file which has to be included in the other jsp file by using the tag <%@ include file = " "%>. Literals in JSP Literals are the values, such as a number or a text string, that are written literally as part of a program code. A literal is a expression of a value, including a number or a text string. Passing Parameter using <jsp: param> Request parameters can be passed by using <jsp: param>. This tag contains two attributes: 1) name 2) value. Tag Handler Custom tags are usually distributed in the form of a tag library, which defines a set of related custom tags and contains the objects that implement the tags. Custom tag libraries allow the java programmer to write code that provides data access and other services, and they make those features available to the jsp author in a simple to use XML- like fashion. UseBean Syntax: <jsp:useBean id= "nameOfInstance" scope= "page | request | session | application" class= "package.class" type= "package.class > </jsp:useBean>. Expression Language In JSP EL means the expression language , it is a simple language for accessing data, it makes it possible to easily access application data stored in JavaBeans components. EL Basic Arithmetic Addition (+), subtraction (-), multiplication (*), division (/ or div), and modulus (% or mod) are all supported in Expression Language. Error conditions, like division by zero are handled easily by the expression language.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值