1.三种基本语法
<%= xxx%> 将xxx变量输出到页面
<%= new Date(System.currentTimeMillis()).toLocaleString()%>
<% int a = 1; %> 编写脚本片段
<%
for (int i = 0; i < 5; i++) {
out.print("<h1>"+i+"</h1>");
}
%>
由于使用<%%><%=%>两种语法编写的代码最终都会转化为在一个_jspService方法内的java代码(如图),所以一个变量不能被定义两次
那么,我们如果想要在方法外部编写代码怎么办呢?于是有第三种语法
<%! int a = 0;%>
在类下声明
<%int a = 1;%>
<%!int a = 1;%>
可以看到声明后的变量a在类下,而非在方法下,使得a的作用域更大
2.自定义设置错误跳转页面
当我们在JSP文件中编写如以下代码时,页面会报500错误
<%int a = 1 / 0;%>
我们可以在JSP代码首行加入以下代码,错误页面就会跳转到我们指定的页面
<%@ page errorPage="error/error500.jsp" %>
我们也可以在web.xml文件中加入以下配置,具有同样的效果
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
3.提取公共页和拼接页面
- 提取公告页
<%@include file="include/header.jsp"%>
<%@include file="include/footer.jsp"%>
源码
通过源码我们可以看到这种办法只是方法中加了两段html标签
假如我们分别在两个file文件中都添加
<%int a = 1;%>
就会报500错误
这也再一次说明通过include标签提取公告页具有一点局限性:即这些文件中相互不能重复定义变量,因为他们最终都会被全部写在一个方法內
- 通过指令拼接页面
<jsp:include page="include/header.jsp"></jsp:include>
<jsp:include page="include/footer.jsp"></jsp:include>
可以看到使用jsp:include指令后,在源码调用了其他方法拼接页面,所以解决需要拼接的多个页面不能重复定义变量的问题