一、简单介绍
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或表达式 %>
--%>
<%= new java.util.Date()%>
<%--JSP脚本片段--%>
<%
int sum = 0;
for(int i = 1 ; i <= 100 ; i++){
sum = sum + i;
}
out.print("<h2>" + sum + "</h2>");
%>
<%--脚本片段的再实现--%>
<%
int x = 10;
out.print(x);
%>
<hr>
<%
int y = 20;
out.print(y);
%>
<%--在代码中嵌入HTML代码--%>
<%
for(int i = 0 ; i < 5 ; i ++){
%>
<h2>Hello Massimo!</h2>
<%
}
%>
<%--JSP申明--%>
<%!
static {
System.out.println("Loading Servlet......");
}
private int gloableVar = 0;
public void operation(){
System.out.println("进入了方法operation");
}
%>
<!--我是HTML注释-->
<%--我是JSP注释--%>
</body>
</html>
注意:JSP声明会被编译到JSP生成的Java类中!其它的,就会被生成到_jspService方法中!
在JSP,嵌入Java代码即可!
查看源代码:
HTML注释和JSP注释区别:
JSP的注释不会显示在客户端显示,HTML注释会。
二、JSP指令
常见作用:
1、导包
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入Date包--%>
<%@ page import="java.util.Date" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Date date = new Date();
out.print(date);
%>
</body>
</html>
效果:
2、定制错误页面
3、在web.xml中配置错误页面
一、创建404.jsp错误页面,当输入的url错误时,跳转到该页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="img/404.jpg" alt="400"/>
</body>
</html>
二、创建500.jsp错误页面,当代码出现错误时跳转到该页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="img/500.png" alt="500">
</body>
</html>
三、在web.xml中配置
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
四、项目结构
五、测试效果
404测试:
500测试:
测试代码
测试效果
4、提取公共页面
一、编写header.jsp作为头部页面
二、编写footer.jsp作为尾部页面
三、编写test.jsp作为主体页面
四、项目结构
五、测试效果
三、JSP标签提取公共页面
步骤与上述基本相同,只是将test.jsp更改如下:
区别:
<%@ include%>会将两个页面合二唯一;
部分源码:
< jsp:include>拼接页面,本质还是3个,常用,灵活性更高。
部分源码: