Jsp的基本語法
阿新 • • 發佈:2019-02-05
什麼是Jsp
JSP(全稱JavaServer Pages) 其根本是一個簡化的Servlet設計,他實現了在java中使用Html標籤。jsp是一種動態網路技術標準.也是JAVAEE的標準。Jsp和Servlet一樣,是伺服器端執行的。
Jsp與其他動態網站開發技術的優缺點
Jsp元素構成
jsp指令
page指令
jsp註釋
jsp指令碼語法
jsp宣告變數
jsp表示式表示方法
<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css " href="styles.css">
-->
</head>
<body>
Hello This is my JSP page.
<br>
<h1>大家好</h1>
<!-- 我是html註釋 -->
<%--我是jsp註釋 --%>
<%!String s = "jack";
int add(int x, int y) {
return x + y;
}%>
<%
//單行註釋
/*
多行註釋
*/
out.print("歡迎學習javaee");
%>
<br> 你好<%=s%><br> x+y=<%=add(10, 5)%>
<br>
<%!SimpleDateFormat sdf = new SimpleDateFormat();
String date = sdf.format(new Date());%>
今天是<%=date%>
</body>
</html>
顯示效果如下
下面我們用兩種方法列印九九乘法表
<%@page import="com.sun.xml.internal.fastinfoset.tools.PrintTable"%>
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'execise.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>九九乘法表</h1>
<%!String pirntTable1() {
String s = "";
for (int i = 1; i < 10; i++) {
for (int j = 1; j <= i; j++) {
s += i + "*" + j + "=" + (i * j) + " ";
}
s += "<br>";
}
return s;
}%>
<br>
<%=pirntTable1()%>
<h1>指令碼方式列印九九乘法表</h1>
<%!void pirntTable2(JspWriter out) throws Exception {
for (int i = 1; i < 10; i++) {
for (int j = 1; j <= i; j++) {
out.println(i + "*" + j + "=" + (i * j)
+ " ");
}
out.println("<br>");
}
}%>
<br>
<%
pirntTable2(out);
%>
</body>
</html>
效果如圖