1、jsp中可以写Java
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%=new java.util.Date()%> <% int sum=0; for (int i = 0; i < 100; i++) { sum+=i; } out.println("<h1>Sum="+sum+"</h1>"); %> <% for (int j = 0; j < 5; j++) { %> <h1>hello<%=j%></h1> <% } %> <%--这是JSP的注释--%> <!--这是HTML的注释--> </body> </html>
其中HTML的注释在网站上不能直接找到
JSP本质上就是servlet,他自动的声明了一些对象(例如out等),JSP有个service函数可以实现将JSP文件中的Java语言改为可以显示在网页上的HTML。
JSP文件在执行时是先变成.Java,.Java再编译成.java.class。
2.用JSP指令改写错误页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@page errorPage="error/500.jsp" %> <html> <head> <title>Title</title> </head> <body> <% int x=1/0; out.println(x); %> </body> </html> (jsp2.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>自定义500的图片</h1> <img src="../img/500.png" alt="500"> </body> </html> (500.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <img src="../img/404.webp" alt="404"> </body> </html> (400.jsp)
3、用JSP指令使用公共部分
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>我是头部</h1> </body> </html> (header.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>我是尾部</h1> </body> </html> (footer.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--合并--%> <%@include file="common/header.jsp"%> <h1>我是主体</h1> <%@include file="common/footer.jsp"%> <hr> <%--JSp标签 拼接一个新的--%> <jsp:include page="/common/header.jsp"/> <h1>我是主体</h1> <jsp:include page="/common/footer.jsp"/> </body> </html> (jsp3.jsp)