JSP原理笔记(二)
JSP脚本元素:表达式,Scriptlet,声明
表达式的概念
表达式是对数据的表示,系统将其作为一个值进行计算和
显示
表达式在JSP页面中的表现形式
<% = Java表达式 %>
Demo代码:
<%@page contentType="text/html; charset=utf-8" %><html><head><title>jsp表达式demo</title></head><body><h1>JSP表达式</h1><b>PI的值</b><%=Math.PI %><br><b>100,233中较大的值:</b><%=Math.max(100, 233) %><b>100,233中较小的值:</b><%=Math.min(100, 233) %><b>100+233的值</b><%=100+233 %> <b>(3+2)==5的值 :</b><%=(3+2)==5 %><br/> <b>(3+2)!=5的值 :</b><%=(3+2)!=5 %><br/></body></html>
Math类所在的包为什么不需要引入,因为Math所在的包是在java.lang中,凡是这个路径中的包都是系统自动引入的,不需要程序员手动import。
演示图片:

Scriptlet: JSP Scriptlet就是在JSP页面里嵌入一段Java代码
JSP Scriptlet在JSP页面中的表现形式
<% Java代码 %>
Demo代码:
<%@page contentType="text/html; charset=utf-8" %><html><head><title>scriptlet演示页面</title></head><body><h1>打印九九乘法表</h1><%--这是程序员注释,客户端是不可见的 --%><!-- 这是页面注释,客户端可见 --><%for(int i=1;i<=9;i++){for(int j=1;j<=i;j++){out.print(i+"*"+j+"="+i*j+" ");}out.println("<br>");}%></body></html>
演示页面效果:

JSP 声明的概念
JSP声明就是在JSP页面中声明Java方法或变量等
JSP声明在JSP页面中的表现形式
< % ! Java 代码 %>
Demo代码:
<%@page contentType="text/html; charset=utf-8"%><html><head><title>JSP声明学习页面</title></head><body><%!public final String author="Nicolas";public String getFamilyName(String name){ char fn=name.charAt(0);//获取第一个字符,当然前提是中文名return name+"的姓氏为:"+fn;}%><%String name1="赵云";String name2="尉迟恭";String name3="秦叔宝";out.print("<center>");out.print(getFamilyName(name1));out.print("<br>");out.print(getFamilyName(name2));out.print("<br>");out.print(getFamilyName(name3));out.print("<br>");out.println("页面作者是:"+"<font color=red size=5>"+author+"</font>");out.print("</center>");%></body></html>
演示页面:

JSP指令包括:page,include,taglib。
JSP 指令的语法为:
<%@ 指令名称 属性1="属性值1" 属性2="属性值2" … 属性n="属性值n"%>

page指令中有一个属性为errorPage,例如error="error.jsp",那么当前页面出错是会自动跳转到error.jsp"中。
可能出错页面errorTest.jsp代码:
<%@ page language = "Java" import="java.util.*" buffer = "8kb" errorPage="error.jsp" isErrorPage="false"%><html><head><title>错误友好提示测试页面</title></head><body>这是一个错误指向测试页面!<hr><%int a=1;int b=0;//b不能作为除数,否则会出错out.print(a/b);%></body></html>
错误提示友好页面error.jsp代码:
<%@page contentType="text/html; charset=utf-8" isErrorPage="true" %><html><head><title>错误友好提示页面</title></head><body><font size=6 color="red">出错了哦⊙﹏⊙b汗</font></body></html>
include 指令用于在运行时将 HTML文件或 JSP页面嵌入到另一个 JSP页面
include 指令语法
<%@ include file = ”文件名” %>
演示页面includeDemo.jsp源代码:
<%@page contentType="text/html; charset=utf-8" %><html><head><title>include演示页面</title></head><%@include file="head.jsp" %><h1>this is the original page 自己的页面哦<hr></h1></html><%@include file="head.jsp" %>
head.jsp源代码:
<%@page contentType="text/html; charset=utf-8" %><html><head><title>include测试页面</title></head><body>我是被include进去的页面哦,不相信的话,看页面源代码O(∩_∩)O哈哈~</body></html>
预览结果:

Scriptlet JSP脚本段被转成Servlet中service方法体(直接拷贝,内容不变),scriptlet不能再去定义方法,因为方法不能嵌套定义。
其中定义的变亮会转译成局部变量,而且会在同一个方法体中。