1.什么是jsp
JSP全名是Java Server Pages,它是建立在Servlet规范之上的动态网页开发技术;
2.JSP基本语法
JSP声明语句用于生命变量和方法,它以"<%!“开始,以”%>"结束,语法如下:
<%!
定义的变量或方法
%>
在chapter06项目的WebContent目录下创建一个名称为example01.jsp的文件,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<%!
int a=1;
int b=2;
%>
<%!
public String print(){
String str = "incast";
return str;
}
%>
<body>
<% out.println(a+b); %>
</br>
<% out.println(print()); %>
<br />
<%=a+b %>
<br/>
<%="function"+print() %>
</body>
</html>
运行结果如下:
3.JSP注释
同其他各种编程语言一样,JSP也有自己的注释方式语法如下:
<%-- --%>
在chapter06项目的WebContent下创建名称为example02的JSP页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- html注释 -->
//java注释
<% //java注释
out.println("java注释演示");
%>
</body>
</html>
4.JSP指令
page指令:在JSP页面中,经常需要对页面的某些特性进行描述
<%@ page 属性名1 = "属性值1" 属性名2= " 属性值2 "......%>
include指令:在实际开发时,有时需要在JSP页面静态包含一个文件,例如HTML文件,文本文件等
<%@ include file="被包含的文件地址"%>
在chapter06项目的WebContent目录下创建两个JSP页面文件date.jsp和include.jsp,在include.jsp文件中使用include指令将date.jsp文件包含其中:
date.jsp
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% out.println(new Date().toLocaleString()); %>
</body>
</html>
include.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎您</title>
</head>
<body>
欢迎您,现在的时间是:
<%@ include file="date.jsp" %>
</body>
</html>
运行结果:
5.JSP隐式对象
out对象:在JSP页面中,经常需要向客户端发送文本内容,这时需要使用out对象来实现;
在chapter06项目的WebContent目录下创建一个名称为out的JSP文件:
out.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.println("first line<br />");
response.getWriter().println("second line<br />");
%>
</body>
</html>
运行结果如下:
pageContext对象:使用该对象可以访问其他8个隐式对象;
在chapter06项目的WebContent目录下创建一个名称为pageContext.jsp;
pageContext.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
HttpServletRequest req = (HttpServletRequest)pageContext.getRequest();
// req.setAttribute("req","REQUEST","dashuju");
pageContext.setAttribute("req", "pageContext",pageContext.PAGE_SCOPE);
pageContext.setAttribute("req","dashuju",pageContext.REQUEST_SCOPE);
pageContext.setAttribute("req", "session",pageContext.SESSION_SCOPE);
pageContext.setAttribute("req", "application",pageContext.APPLICATION_SCOPE);
%>
<%=pageContext.findAttribute("req") %>
<hr/>
<%=(String)req.getAttribute("req") %>
</body>
</html>
运行结果: