JSP简单介绍

JSP的发展史

JSP全名为Java Server Pages,中文名叫java服务器页面,其根本是一个简化的Servlet设计,它 [1] 是由Sun Microsystems公司倡导、许多公司参与一起建立的一种动态网页技术标准。JSP技术有点类似ASP技术,它是在传统的网页HTML(标准通用标记语言的子集)文件(.htm,.html)中插入Java程序段(Scriptlet)和JSP标记(tag),从而形成JSP文件,后缀名为(*.jsp)。 用JSP开发的Web应用是跨平台的,既能在Linux下运行,也能在其他操作系统上运行。
它实现了Html语法中的java扩展(以 <%, %>形式)。JSP与Servlet一样,是在服务器端执行的。通常返回给客户端的就是一个HTML文本,因此客户端只要有浏览器就能浏览。
JSP技术使用Java编程语言编写类XML的tags和scriptlets,来封装产生动态网页的处理逻辑。网页还能通过tags和scriptlets访问存在于服务端的资源的应用逻辑。JSP将网页逻辑与网页设计的显示分离,支持可重用的基于组件的设计,使基于Web的应用程序的开发变得迅速和容易。 JSP(JavaServer Pages)是一种动态页面技术,它的主要目的是将表示逻辑从Servlet中分离出来。
Java Servlet是JSP的技术基础,而且大型的Web应用程序的开发需要Java Servlet和JSP配合才能完成。JSP具备了Java技术的简单易用,完全的面向对象,具有平台无关性且安全可靠,主要面向因特网的所有特点。。

JSP 优点

(1)一次编写,到处运行。除了系统之外,代码不用做任何更改。
(2)系统的多平台支持。基本上可以在所有平台上的任意环境中开发,在任意环境中进行系统部署,在任意环境中扩展。相比ASP的局限性JSP的优势是显而易见的。
(3)强大的可伸缩性。从只有一个小的Jar文件就可以运行Servlet/JSP,到由多台服务器进行集群和负载均衡,到多台Application进行事务处理,消息处理,一台服务器到无数台服务器,Java显示了一个巨大的生命力。
(4)多样化和功能强大的开发工具支持。这一点与ASP很像,Java已经有了许多非常优秀的开发工具,而且许多可以免费得到,并且其中许多已经可以顺利的运行于多种平台之下。
JSP
JSP
(5)支持服务器端组件。web应用需要强大的服务器端组件来支持,开发人员需要利用其他工具设计实现复杂功能的组件供web页面调用,以增强系统性能。JSP可以使用成熟的JAVA BEANS 组件来实现复杂商务功能。

JSP 缺点

缺点
(1) 与ASP也一样,Java的一些优势正是它致命的问题所在。正是由于为了跨平台的功能,为了极度的伸缩能力,所以极大的增加了产品的复杂性。
(2) Java的运行速度是用class常驻内存来完成的,所以它在一些情况下所使用的内存比起用户数量来说确实是“最低性能价格比”了。

JSP发展史

1.2版本2.0版本
JSP1.2不支持EL,但可以使用外部的JSTL标签以便使用EL。JSP 2.0的一个主要特点是它支持表达语言(expression language)。JSTL表达式语言可以使用标记格式方便地访问JSP的隐含对象和JavaBeans组件,JSTL的核心标记提供了流程和循环控制功能。自制标记也有自定义函数的功能,因此基本上所有scriptlet能实现的功能都可以由JSTL替代。在JSP 2.0中,建议尽量使用EL而使JSP的格式更一致。
SimpleTag

JSP 2.0中加入了新的创建自制标记的API,javax.servlet.jsp.tagext.SimpleTag定义了用来实现简单标记的接口。和 JSP 1.2中的已有接口不同的是,SimpleTag接口不使用doStartTag和doEndTag方法,而提供了一个简单的doTag方法。这个方法在调用该标记时只被使用一次。而需要在一个自制标记中实现的所有逻辑过程、循环和对标记体的评估等都在这个方法中实现。从这个方面来讲, SimpleTag和IterationTag可以达到同等的作用。但SimpleTag的方法和处理周期要简单得多。在SimpleTag中还有用来设置JSP内容的setJspBody和getJspBody方法。Web容器会使用setJspBody方法定义一个代表JSP内容的 JspFragment对象。实现SimpleTag标记的程序可以在doTag方法中根据需要多次调用getJspBody.invoke方法以处理JSP内容。

重要功能被

JSP2.0中的一个主要功能是JSP fragment,它的基本特点是可以使处理JSP的容器推迟评估JSP标记属性。我们知道一般JSP是首先评估JSP标记的属性,然后在处理JSP标记时使用这些属性,而JSP fragment提供了动态的属性。也就是说,这些属性在JSP处理其标记体时是可以被改变的。JSP需要将这样的属性定义为 javax.servlet.jsp.tagext.JspFragment类型。当JSP标记设置成这种形式时,这种标记属性实际上的处理方法类似于标记体。在实现标记的程序中,标记属性可以被反复评估多次。这种用法称为JSP fragment。JSP fragment还可以定义在一个SimpleTag处理程序中使用的自制标记动作。像前面例子说明的,getJspBody返回一个 JspFragment对象并可以在doTag方法中多次使用。需要注意的是,使用JSP fragment的JSP只能有一般的文本和JSP action,不能有scriptlet和scriptlet表达式。

JSP语法

一个JSP页面可以被分为以下几部份:

  • 静态数据,如HTML
  • JSP指令,如include指令
  • JSP脚本元素和变量
  • JSP动作
  • 用户自定义标签
静态数据

静态数据在输入文件中的内容和输出给HTTP响应的内容完全一致。此时,该JSP输入文件会是一个没有内嵌JAVA或动作的HTML页面。而且,客户端每次请求都会得到相同的响应内容。

JSP指令

JSP指令控制JSP编译器如何去生成servlet,以下是可用的指令:

  • 包含指令include –包含指令通知JSP编译器把另外一个文件完全包含入当前文件中。效果就好像被包含文件的内容直接被粘贴到当前文件中一样。这个功能和C预处理器所提供的很类似。被包含文件的扩展名一般都是"jspf"(即JSPFragment,JSP碎片):
    <%@ include file=“somefile.jsp” %>
  • 页面指令page –页面指令有以下几个选项:
importcontentTypeerrorPageisErrorPageisThreadSafe
使一个JAVA导入声明被插入到最终页面文件。规定了生成内容的类型。当生成非HTML内容或者当前字符集character set并非默认字符集时使用。处理HTTP请求时,如果出现异常则显示该错误提示信息页面。如果设置为TRUE,则表示当前文件是一个错误提示页面。表示最终生成的servlet是否安全线程(threadsafe)。

注意:在同一个JSP文件中只有"import"导入页面指令可以被多次使用。

  • 标签库指令taglib –标签库指令描述了要使用的JSP标签库。该指令需要指定一个前缀prefix(和C++的命名空间很类似)和标签库的描述URI:
<%@ taglib prefix="myprefix" uri="taglib/mytag.tld" %>
JSP脚本

标准脚本变量
以下是永远可用的脚本变量:
out – JSPWriter用来写入响应流的数据
page – servlet自身
pageContext –一个PageContext实例包括和整个页面相联系的数据,一个给定的HTML页面可以在多个JSP之间传递。
request –HTTP request对象
response –HTTP response对象
session –用于保持客户端与服务器连接的对象

脚本元素

有三个基本的脚本元素,作用是使JAVA代码可以直接插入servlet.
一种是声明标签,在JAVA SERVLET的类体中放入一个变量的定义。静态的数据成员也可以如此定义。
<%! int serverInstanceVariable = 1; %>
一种是脚本标签,在JAVA SERVLET的类的_jspService()方法中放入所包含的语句。
<% int localStackBasedVariable = 1; out.println(localStackBasedVariable); %>
一种是表达式标签,在JAVA SERVLET的类中放入待赋值的表达式,表达式注意不能以分号结尾。
<%= "expanded inline data " + 1 %>

JSP动作
jsp:includejsp:paramjsp:forwardjsp:pluginjsp:fallbackjsp:getPropertyjsp:setPropertyjsp:useBean
使一个JAVA导入声明被插入到最终页面文件。规定了生成内容的类型。当生成非HTML内容或者当前字符集character set并非默认字符集时使用。处理HTTP请求时,如果出现异常则显示该错误提示信息页面。如果设置为TRUE,则表示当前文件是一个错误提示页面。表示最终生成的servlet是否安全线程(threadsafe)。从指定的JavaBean中获取一个属性值。在指定的JavaBean中设置一个属性值。创建或者复用一个JavaBean变量到JSP页。

JSP标准标签库

JSTL 库安装
Apache Tomcat安装JSTL 库步骤如下:
从Apache的标准标签库中下载的二进包(jakarta-taglibs-standard-current.zip)。下载地址:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/
下载jakarta-taglibs-standard-1.1.1.zip 包并解压,将jakarta-taglibs-standard-1.1.1/lib/下的两个jar文件:standard.jar和jstl.jar文件拷贝到/WEB-INF/lib/下。
使用任何库,你必须在每个JSP文件中的头部包含标签。
核心标签
核心标签是最常用的JSTL标签。引用核心标签库的语法如下:
<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
标签 描述
<c:out > 用于在JSP中显示数据,就像<%= … >
<c:set > 用于保存数据
<c:remove > 用于删除数据
<c:catch> 用来处理产生错误的异常状况,并且将错误信息储存起来
<c:if> 与我们在一般程序中用的if一样
<c:choose> 本身只当做<c:when>和<c:otherwise>的父标签
<c:when> <c:choose>的子标签,用来判断条件是否成立
<c:otherwise > <c:choose>的子标签,接在<c:when>标签后,当<c:when>标签判断为false时被执行
<c:import> 检索一个绝对或相对 URL,然后将其内容暴露给页面
<c:forEach > 基础迭代标签,接受多种集合类型
<c:forTokens> 根据指定的分隔符来分隔内容并迭代输出
<c:param> 用来给包含或重定向的页面传递参数
<c:redirect > 重定向至一个新的URL.
<c:url> 使用可选的查询参数来创造一个URL
格式化标签
JSTL格式化标签用来格式化并输出文本、日期、时间、数字。引用格式化标签库的语法如下:
<%@ taglib prefix=“fmt” uri=“http://java.sun.com/jsp/jstl/fmt” %>
标签 描述
fmt:formatNumber 使用指定的格式或精度格式化数字
fmt:parseNumber 解析一个代表着数字,货币或百分比的字符串
fmt:formatDate 使用指定的风格或模式格式化日期和时间
fmt:parseDate 解析一个代表着日期或时间的字符串
fmt:bundle 绑定资源
fmt:setLocale 指定地区
fmt:setBundle 绑定资源
fmt:timeZone 指定时区
fmt:setTimeZone 指定时区
fmt:message 显示资源配置文件信息
fmt:requestEncoding 设置request的字符编码
SQL标签
JSTL SQL标签库提供了与关系型数据库(Oracle,MySQL,SQL Server等等)进行交互的标签。引用SQL标签库的语法如下:
<%@ taglib prefix=“sql” uri=“http://java.sun.com/jsp/jstl/sql” %>
标签 描述
sql:setDataSource 指定数据源
sql:query 运行SQL查询语句
sql:update 运行SQL更新语句
sql:param 将SQL语句中的参数设为指定值
sql:dateParam 将SQL语句中的日期参数设为指定的java.util.Date 对象值
<sql:transaction > 在共享数据库连接中提供嵌套的数据库行为元素,将所有语句以一个事务的形式来运行
XML 标签
JSTL XML标签库提供了创建和操作XML文档的标签。引用XML标签库的语法如下:
<%@ taglib prefix=“x” uri=“http://java.sun.com/jsp/jstl/xml” %>
在使用xml标签前,你必须将XML 和 XPath 的相关包拷贝至你的<Tomcat 安装目录>\lib下:
XercesImpl.jar:
xalan.jar:
标签 描述
<x:out> 与<%= … >,类似,不过只用于XPath表达式
<x:parse> 解析 XML 数据
<x:set > 设置XPath表达式
<x:if > 判断XPath表达式,若为真,则执行本体中的内容,否则跳过本体
<x:forEach> 迭代XML文档中的节点
<x:choose> <x:when>和<x:otherwise>的父标签
<x:when > <x:choose>的子标签,用来进行条件判断
<x:otherwise > <x:choose>的子标签,当<x:when>判断为false时被执行
<x:transform > 将XSL转换应用在XML文档中
<x:param > 与<x:transform>共同使用,用于设置XSL样式表
JSTL函数
JSTL包含一系列标准函数,大部分是通用的字符串处理函数。引用JSTL函数库的语法如下:
<%@ taglib prefix=“fn” uri=“http://java.sun.com/jsp/jstl/functions” %>
函数 描述
fn:contains() 测试输入的字符串是否包含指定的子串
fn:containsIgnoreCase() 测试输入的字符串是否包含指定的子串,大小写不敏感
fn:endsWith() 测试输入的字符串是否以指定的后缀结尾
fn:escapeXml() 跳过可以作为XML标记的字符
fn:indexOf() 返回指定字符串在输入字符串中出现的位置
fn:join() 将数组中的元素合成一个字符串然后输出
fn:length() 返回字符串长度
fn:replace() 将输入字符串中指定的位置替换为指定的字符串然后返回
fn:split() 将字符串用指定的分隔符分隔然后组成一个子字符串数组并返回
fn:startsWith() 测试输入字符串是否以指定的前缀开始
fn:substring() 返回字符串的子集
fn:substringAfter() 返回字符串在指定子串之后的子集
fn:substringBefore() 返回字符串在指定子串之前的子集
fn:toLowerCase() 将字符串中的字符转为小写
fn:toUpperCase() 将字符串中的字符转为大写
fn:trim() 移除首位的空白符

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、付费专栏及课程。

余额充值