首页 > 开发 > JSP > 正文

JSP初学者教程:学习JSP的基本指令

2020-02-05 13:51:23
字体:
来源:转载
供稿:网友

1,脚本标记

声明将要用到的语言:

<%@ page language="java" %>指明jsp指令,表明后面的脚本代码将采用java语言语法

引用包中的类:

<%@ page import="java.util.*" %>表示要用到java.util包里的类

声明变量:

<%! int count=0;%>声明一个整形变量,并赋初值0。声明要符合java语法规范,并且要";"结尾。

声明方法:

<%! int show(int val){{return val;}%> or <%! area s=new area(5.0); %> 使用变量和方法之前一定要声明。

输出表达式:

<%=2*x%>直接输出表达式的值,x必须是前面已声明过的变量(不能用分号),相当于asp中的<%=%>

html注释符:

<!--注释[<%=表达式%>]-->,注意的是注释中可以用表达式。

隐藏注释符:

<%--here are comments,only can see in server.--%>表示是jsp注释,在服务器端将被忽略,也不转化为html的注释,在客户端查看源码时是看不到的。

注:在<%-- --%>之间,可以任意写注释语句,但是不能使用"--%>",若一定要使用,请在最后使用"--%/>"。

包含另一个jsp文件:

<%jsp:include page="another.jsp"%> or <%@ include page="another.jsp"%>表示在当前页面插入另一个文件another.jsp的内容

小脚本(scriptlet):

<% java程序代码 %>在scriptlet中可以包含多个jsp语句、方法、变量或者表达式。

普通的jsp语句:

<% for(int i=0,i<10,i++)//jsp的正文部分
out.println(i+"<br>");
%>

2.指令

jsp的指令有page、include两种

page指令(属性:6个)

language属性:

<@ page language=”java” %>//指明所用的的语言

import属性:

<@ page import=”java.util.*” %>//载入包

注意:在java中,要载入多个包,就用import分别指用,并用分号隔开;在jsp中,如用一个import指明多个包,用逗号隔开。

如:<%@ page import=”java.util.*,java.lang.*”%>

也可<%@ page import=”java.util.*”%>

<%@ page import=” java.lang.*”%>(但不主张这样用,不规范。)

session属性:

<@ page session=”true or false” %>缺省情况下session的值为true
如:<%@ page session=”true”%>
<% if(session.getvalue(“name”)==null)
session.putvalue(“name”,”123456”);
else session.putvalue(“name”,session.getvalue(“name”)+”1”);
%>
<% out.println(session.getvalue(“name”));%>

若session=”false”,则会出现编译错。

errorpage属性:

指当前页面程序发生错误时,由errorpage指定的程序来处理

写法:

<@ page errorpage=”errorpage.jsp” %>
如:
test.jsp: <%@page errorpage=”errorpage.jsp”@>
<%!int i=0;%>
<%=7/i%>
errorpage.jsp: <%@page iserrorpage=”true”@>
<%=exception%>
运行test.jsp,将会看到被0除的错误信息。

iserrorpage属性:

指明了当前程序是否为另一程序的例外处理程序。不论它是否设置,例外都会导向当前程序,问题在于当前程序能否得到此例外的对象。如设定为true,将会产生发生的例外的一个对象exception,并可以在代码中使用它;若设定了false,使用exception程序将将会在编译时出错。

如:将上例的true改为false,将会出现以下错误:

error:500
unable to compile class for jsp
写法:
<%@page iserrorpage=”true”@>

contenttype属性:

指定了mime的类型和jsp文件的字符编码方式,它们都是最先传送给客户端。

mime类型有:text/plain、text/html(缺省类型)、text/html、image/gif、image/jpeg、image/jpeg

缺省的字符编码方式:iso8859-1

include指令

作用:是用来向当前页中插入一个静态文件的内容,这个文件可能是html文件、jsp文件或其它文本文件,格式如下:

<%@ include file=”include.inc”%>
如:
native.jsp:
<body>
native file start here.<br>
<%@ include file=”include.inc”%>
native file end here.<br>
</body>
include.inc:
include file start here.<br>
<%! string str=”here is include’s context!”;%>
<% out.pringln(str+”<br>”);%>
include file end here.<br>
运行native.jsp,结果如下:
native file start here.
include file start here.
here is include’s context!
include file end here.
native file end here.

注意:因为include.inc文件是在编译时才插入的,所以只改 include.inc文件内容,而不对原jsp页面做修改,得到的结果仍将是以前的结果。(因为一开始jsp引擎就判断了jsp页面没被改动过,就直接执行已存在的字节码,而不对源代码重新编译,这样对include做的修改也就在这没有反映。)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表