JSP基础语法
JSP注释
comment.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 这个注释客户端可以看见 -->
<%-- jsp中的注释,客户端无法看见 --%>
<%
//java中的单行注释,客户端无法看见
/*
java中的多行注释,客户端无法看见
*/
%>
</body>
</html>
Scriptlet
scriptlet_demo01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//定义局部变量,编写语句
int x = 10;
String info = "www.mldnjava.cn";
out.println("<h2>x="+x+"</h2>");
out.println("<h2>info="+info+"</h2>");
%>
</body>
</html>
scriptlet_demo02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 定义全局变量,方法,类 -->
<%! public static final String INFO = "www.mldnjava.cn"; %>
<!-- 用于输出一个变量或一个具体的常量 -->
<%=1 %><br/>
<%=INFO %>
</body>
</html>
尽量不要使用system.out.print();进行输出
input_table_value.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="print_table.jsp" method="post">
<table border="1" width="100%">
<tr>
<td>输入表格的行数:</td>
<td><input type="text" name="row"></td>
</tr>
<tr>
<td>输入表格的列数:</td>
<td><input type="text" name="col"></td>
</tr>
<tr>
<td>
<input type="submit" value="显示">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
print_table.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int rows = 0;
int cols = 0;
//读取input_table_value.jsp post的row和col,将之强制转换为int类型
try{
rows = Integer.parseInt(request.getParameter("row"));
cols = Integer.parseInt(request.getParameter("col"));
}catch(Exception e){}
if(rows>0&&cols>0){
%>
<table border="1" width="100%">
<%
for(int x = 1;x <= rows; x++){
%>
<tr>
<%
for(int y = 1; y <= cols; y++){
%>
<td> <%=x%> * <%=y%> = <%=(x * y)%></td>
<%
}
%>
</tr>
<%
}
%>
</table>
<a href="input_table_value.jsp"><input type="button" value="返回"></a>
<%
}else{
%>
<%--输入不符合时弹出对话框指示,并自动返回到输入数值处 --%>
<script type="text/javascript" language="javascript">
alert("输入不合法!");
/* alert(document.location === window.location);//true */
//window.location.href="input_table_value.jsp";
//document.location.href="input_table_value.jsp";
//以上两种好像等价,待探索
window.document.location.href="input_table_value.jsp";
</script>
<%
}
%>
</body>
</html>
scriptlet标签
此标签具有和<% %>
一样的效果,更加美观一些,无强制要求
scriptlet_tag.jsp
<jsp:scriptlet>
String url = "www.MLDNJAVA.cn";
</jsp:scriptlet>
<h2><%=url %></h2>
page指令
设置页面的MIME、文件编码
page_demo01.jsp
<%@ page language="java" contentType="application/msword; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- pageEncoding是JSP文件本身的编码,contentType是服务器发送给客户端的内容编码 --> <!-- txt text/plain -->
<!-- doc application/msword -->
<!-- png image/png -->
<!-- jpg/jpeg image/jpeg -->
<!-- htm/html text/html-->
<table border="1">
<%
//指定文件下载后的保存名称是mldn.doc
response.setHeader("Content-Disposition", "attachment;filename=mldn.doc");
%>
<tr><td>欢迎大家</td></tr>
<tr><td>欢迎大家!!</td></tr>
<tr><td>欢迎大家!!!</td></tr>
</table>
</body>
</html>
错误页的设置
服务器端跳转
show_error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page errorPage="error.jsp" %>
<%-- 出现错误将会跳转到error.jsp --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int result = 10 / 0;
%>
<%=result %>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<%-- 表示出现错误该页面可以处理错误 --%>
<% response.setStatus(200); %>
<%-- 设置了200的HTTP状态码,表示本页没有错误,防止tomcat也认为本页出现了错误,从而无法显示 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>程序出现了错误!</h1>
</body>
</html>
数据库连接操作
page指令使用import导入所需要的Java开发包
mldn.sql
/*
Navicat MySQL Data Transfer
Source Server : myproject
Source Server Version : 50562
Source Host : localhost:3306
Source Database : mldn
Target Server Type : MYSQL
Target Server Version : 50562
File Encoding : 65001
Date: 2019-04-27 02:23:48
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
`empno` int(4) NOT NULL,
`ename` varchar(10) DEFAULT NULL,
`job` varchar(9) DEFAULT NULL,
`hiredate` date DEFAULT NULL,
`sal` float(7,2) DEFAULT NULL,
PRIMARY KEY (`empno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES ('', '李兴华', '经理', '2001-09-16', '2000.30');
INSERT INTO `emp` VALUES ('', '董鸣楠', '销售', '2003-10-09', '1500.90');
INSERT INTO `emp` VALUES ('', '张惠', '销售', '2005-03-12', '800.00');
INSERT INTO `emp` VALUES ('', '刘明', '销售', '2005-03-09', '1000.00');
INSERT INTO `emp` VALUES ('', '杨军', '分析员', '2005-01-12', '2500.00');
INSERT INTO `emp` VALUES ('', '王月', '经理', '2006-09-01', '2500.00');
INSERT INTO `emp` VALUES ('', '李祺', '分析员', '2003-10-01', '3000.00');
将mysql的驱动"mysql-connector-java-5.1.47-bin.jar"复制到Tomcat\lib 目录中,重启服务器
使用JSP列出emp表数据
驱动程序使用
com.mysql.jdbc.Driver
list_emp.jsp
<%@page import="org.apache.tomcat.dbcp.dbcp2.PStmtKey"%>
<%@page import="com.sun.crypto.provider.RSACipher"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
//定义数据库驱动程序
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
//数据库连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
public static final String DBUSER = "root";
public static final String DBPASS = "2580";
%>
<%
Connection conn = null; //声明数据库连接对象
PreparedStatement pstmt = null; //声明数据库操作
ResultSet rs = null; //声明数据库结果集
%>
<%
try{ //数据库操作中会出现异常,所以要使用try...catch处理
Class.forName(DBDRIVER); //数据库驱动程序加载
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);//取得数据库连接
String sql = "SELECT empno,ename,job,sal,hiredate FROM emp";
pstmt = conn.prepareStatement(sql); //实例化prepareStatement对象
rs = pstmt.executeQuery(); //执行查询操作
%>
<center>
<table border="1" width="80%">
<tr> <!-- 输出表格的行显示 -->
<td>雇员编号</td> <!-- 输出表格的行显示信息 -->
<td>雇员姓名</td>
<td>雇员工作</td>
<td>雇员工资</td>
<td>雇佣日期</td>
</tr>
<%
while(rs.next()){
int empno = rs.getInt(1); //循环emp表中的行记录
String ename = rs.getString(2); //取出雇员编号
String job = rs.getString(3); //取出雇员姓名
float sal = rs.getFloat(4); //取出雇员工作
java.util.Date date = rs.getDate(5);//取出雇佣日期
%>
<tr> <!-- 循环输出雇员的信息 -->
<td><%=empno %></td>
<td><%=ename %></td>
<td><%=job %></td>
<td><%=sal %></td>
<td><%=date %></td>
</tr>
<%
}
%>
</table>
</center>
<%
}catch(Exception e){ //异常处理
System.out.println(e); //向Tomcat中打印
}finally{
rs.close();
pstmt.close();
conn.close();
}
%>
</body>
</html>
包含指令
info.htm
<h2>
<font color="red">info.htm</font>
</h2>
info.jsp
<h2>
<font color="green"><%="info.jsp" %></font>
</h2>
info.inc
<h2>
<font color="blue">info.inc</font>
</h2>
静态包含
先包含,再处理
include_demo01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>静态包含操作</h1>
<%@include file="info.htm" %>
<%@include file="info.jsp" %>
<%@include file="info.inc" %>
</body>
</html>
动态包含
先处理,再包含
include_demo02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>静态包含操作</h1>
<jsp:include page="info.htm"/> <!-- 此处为标签指令,必须完结 -->
<jsp:include page="info.jsp"/> <!-- 此处为标签指令,必须完结 -->
<jsp:include page="info.inc"/> <!-- 此处为标签指令,必须完结 -->
</body>
</html>
使用request.getParameter()方法进行参数的传递
receive_param.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>参数一:<%=request.getParameter("name") %></h1>
<h1>参数二:<%=request.getParameter("info") %></h1>
include_demo03.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username="LiXinHua"; //定义一个变量
%>
<h1>动态包含并传递参数</h1>
<jsp:include page="receive_param.jsp">
<jsp:param value="<%=username %>" name="name"/>
<jsp:param value="www.mldnjava.cn" name="info"/>
</jsp:include> <!-- 此处为标签完结指令,必须完结 -->
</body>
</html>
静态包含与动态包含的优劣之分
静态包含处理页 include_demo04.jsp(错误的页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int x = 100;
%>
<h1>include_demo04.jsp -- <%=x %></h1>
<%@include file="include.jsp" %>
<!-- 运行出现500错误,因为静态包含时,先将全部的内容包含到一起,然后再编译,导致了x的多次定义出错 -->
</body>
</html>
动态包含处理页 include_demo05.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int x = 100;
%>
<h1>include_demo05.jsp -- <%=x %></h1>
<jsp:include page="include.jsp"></jsp:include>
</body>
</html>
跳转指令
服务器跳转,页面地址未发生改变
不传递参数时
<jsp:forword page="{要包含的文件路径|<%=表达式 %>}"/>
传递参数时(中间不能有空格)
<jsp:forward>
<jsp:param name="参数名称" value="参数内容"/>
</jsp:forward>
forward_demo01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username = "LiXinHua";
%>
<jsp:forward page="forward_demo02.jsp">
<jsp:param value="<%=username %>" name="name"/>
<jsp:param value="www.MLDNJAVA.cn" name="info"/>
</jsp:forward>
</body>
</html>
forward_demo02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>这是跳转之后的页面</h1>
<h2>参数一:<%=request.getParameter("name") %></h2>
<h2>参数二:<%=request.getParameter("info") %></h2>
</body>
</html>
实例操作:用户登录程序实现(JSP+JDBC实现)
创建数据库表
/*
Navicat MySQL Data Transfer
Source Server : myproject
Source Server Version : 50562
Source Host : localhost:3306
Source Database : mldn
Target Server Type : MYSQL
Target Server Version : 50562
File Encoding : 65001
Date: 2019-04-27 03:28:48
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userid` varchar(30) NOT NULL,
`name` varchar(30) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('admin', 'administrator', 'admin');
登录界面
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>请登录...</title>
</head>
<body>
<center>
<h1>登录操作</h1>
<hr>
<form action="login_check.jsp" method="post">
<table border="1">
<tr>
<td colspan="2"><center>用户登录</center></td>
</tr>
<tr>
<td>登录ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>登录密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登录">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
<hr>
</center>
</body>
</html>
校验界面
login_check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录校验</title>
</head>
<body>
<%!
//定义数据库驱动程序
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
//数据库连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
public static final String DBUSER = "root";
public static final String DBPASS = "2580";
%>
<%
Connection conn = null; //声明数据库连接对象
PreparedStatement pstmt = null; //声明数据库操作
ResultSet rs = null; //声明数据库结果集
boolean flag = false; //标志位
String name = null; //接收用户的真实姓名
%>
<% //JDBC会抛出异常,使用try...catch处理
try{
Class.forName(DBDRIVER); //加载驱动程序
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);//取得数据库连接
//编写要使用的SQL语句,验证用户id和密码,如果正确,则取出真实姓名
String sql = "SELECT name FROM user WHERE userid=? AND password=?";
pstmt = conn.prepareStatement(sql); //实例化prepareStatement对象
pstmt.setString(1, request.getParameter("id")); //设置查询所需要的内容
pstmt.setString(2, request.getParameter("password")); //设置查询所需要的内容
rs = pstmt.executeQuery(); //执行查询操作
if(rs.next()){ //如果可以查询到,则表示合法用户
name = rs.getString(1); //取出真实姓名
flag = true; //修改标志位,如果为true,表示登录成功
}
}catch(Exception e){
System.out.println(e);
}finally{
try{ //关闭操作会抛出异常,使用try...catch处理
rs.close(); //关闭查询对象
pstmt.close(); //关闭操作对象
conn.close(); //关闭数据库连接
}catch(Exception e){}
}
%>
<%
if(flag){ //登录成功,跳转到成功页
%>
<%-- <jsp:forward page="login_success.jsp"> --%> <!-- 执行跳转操作 -->
<%-- <jsp:param value="<%=name %>" name="uname"/> --%>
<%-- </jsp:forward> --%>
<%
response.setHeader("refresh", "3;URL=login_success.jsp"); //定时跳转
session.setAttribute("uname", name);
%>
<h3>用户如果登录成功,三秒后跳转到欢迎页!</h3>
<h3>如果没用跳转,请按<a href="login_success.jsp">这里</a></h3>
<%
}else{//登陆失败,跳转到失败页
%>
<jsp:forward page="login_failure.jsp"></jsp:forward><!-- 执行跳转操作 -->
<%
}
%>
</body>
</html>
登陆成功页面
login_success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>欢迎您,<%=session.getAttribute("uname")%></title>
</head>
<body>
<center>
<%
if(session.getAttribute("uname") != null){ //已经设置过属性,所以不为空
%>
<h1>登录操作</h1>
<hr>
<h2>登录成功</h2>
<h2>欢迎<%=session.getAttribute("uname")%>光临本系统,<a href="logout.jsp">注销</a>!</h2>
<%
}else{ //非法用户,没有登陆过,session中没有userid的存在
%>
<h3>请先进行系统的<a href="login.html">登录</a>!</h3>
<%
}
%> <%-- <h2>欢迎<font color="red"><%=request.getParameter("uname") %></font>光临!</h2> --%>
</center>
</body>
</html>
登录失败页面
login_failure.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆失败</title>
</head>
<body>
<center>
<h1>登录操作</h1>
<h2>登录失败,请重新<a href="login.html">登录</a></h2>
</center>
</body>
</html>
退出页面
logout.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>已退出系统</title>
</head>
<body>
<h3>亲爱的<%=session.getAttribute("uname")%>,您已成功退出本系统,三秒后跳转回登录界面!</h3>
<h3>若果没有跳转,请按<a href="login.html">这里</a></h3>
<%
response.setHeader("refresh", "3;URL=login.html"); //定时跳转
session.invalidate(); //注销,session清空
%>
</body>
</html>