JSP技术
1.jsp脚本和注释
jsp脚本:
1)<%java代码%>——>内部的 java 代码翻译到 service 方法内部。
2)<%=java变量或表达式>——>会被翻译成 service 方法内部 out.print()。
3) <%! java代码%>——>会被翻译成 servlet 的成员内容。
<%@ 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 i = 0;
System.out.print(i);
%>
<%= i %>
<%!String str = "hello world!!!"; %>
<%= str %>
</body>
</html>
效果:
jsp注释:
1)html注释:<!--注释内容-->(可见范围都有 jsp源码 翻译后的 servlet 页面三者)
2)java注释: //单行注释 /*多行注释*/(jsp 源码 翻译后的 servlet)
3) jsp注释:<%--注释内容--%>(jsp源码)
2.jsp运行原理(本质就是 servlet)
jsp 在第一次被访问时会被 Web 容器翻译成 servlet ,在执行过程:
第一次访问——>HelloServlet.java——>HelloServlet_jsp.java
3.jsp 指令(3个)
jsp 的指令是指导 jsp 翻译和运作的命令,jsp 指令包括三大指令:
1)paga 指令
属性最多的一个指令,根据不同的属性,指导整个页面的特性
格式:<%@ paga 属性名1 = “属性值1”属性名2 = “属性名2”...%>
常用属性如下:
language : jsp 中嵌入的语言。
pagaEncoding :当前 jsp 本身的编码——>内部可以包含 contentType
contentType :文本类型。response.setContextType(text/html;charset = UTF-8);
import : 导包
errorPaga :配置错误页面
2) include 指令
页面包含指令,可以将一个 jsp 页面包含到另一个 jsp 页面中。
格式 : <%@ include file = "被包含文件地址">
3)taglib 指令
引入标签库。
index.jsp
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session = "true" errorPage = "/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>
<%@ include file = "/demo.jsp" %>
<%
int i = 0;
System.out.print(i);
List list = new ArrayList();
//int y = 1/0;
%>
<%= i %>
<%!String str = "hello world!!!"; %>
<%= str %>
</body>
</html>
翻译后的 java 代码
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.88
* Generated at: 2018-08-02 09:34:07 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.List;
import java.util.ArrayList;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
String str = "hello world!!!";
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
static {
_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1);
_jspx_dependants.put("/demo.jsp", Long.valueOf(1533132452526L));
}
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
"/error.jsp", true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("<title>Insert title here</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
out.write("\t");
out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("<title>Insert title here</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
out.write("\t<br/>\r\n");
out.write("\t<h1>This is demo jsp !!!</h1>\r\n");
out.write("</body>\r\n");
out.write("</html>");
out.write('\r');
out.write('\n');
out.write(' ');
int i = 0;
System.out.print(i);
List list = new ArrayList();
//int y = 1/0;
out.write("\r\n");
out.write("\t\r\n");
out.write("\t");
out.print( i );
out.write('\r');
out.write('\n');
out.write(' ');
out.write('\r');
out.write('\n');
out.write(' ');
out.print( str );
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
4.jsp 内置/隐式对象(九个)
名称 | 类型 | 描述 |
out | javax.servlet.jsp.JspWriter | 用于页面输出 |
request | javax.servlet.http.HttpServletRequest | 得到用户请求信息 |
response | javax.sevlet.http.HttpServletResponse | 服务器向客户端的回应信息 |
config | javax.servlet.ServletConfig | 服务器配置,可以获取初始化参数 |
session | javax.servlet.http.HttpSession | 用来保存用户的信息 |
application | javax.servlet.ServletContext | 所有用户的共享信息 |
pageConntext | javax.servlet.jsp.PageContext | JSP 的页面容器 |
exception | java.lang.Throwable | 表示 JSP 页面所发生的异常,在错误页面才起作用 |
page | java.lang.Object | 表示 JSP 页面转换后的 servlet 类的实例 |
(1)out 对象
out 的类型 : JspWriter
out 缓冲区默认 8kb 可以设置为 0 写入 response 缓冲区
out.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>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
<%
out.write("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
response.getWriter().write("cccccccccccccccccccccccc");
%>
<%="dddddddddddddddddddddd" %>
</body>
</html>
输出结果:
(2)pageContext 对象
jsp页面上下文对象
作用范围:当前页面
可以获得其他 8 个内置对象!!!
pageContext.getRequest();
pageContext.getResponse();
pageContext.getOut();
pageContext.getSession();
pageContext.getPage();
pageContext.getException();
pageContext.getServletConfig();
pageContext.getServletContext();
pageContext 是一个域对象
pageContext.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; UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//使用 pageContext 向其他域存信息
pageContext.setAttribute("name", "zhangsan",PageContext.REQUEST_SCOPE);
pageContext.setAttribute("name", "lisi",PageContext.SESSION_SCOPE);
pageContext.setAttribute("name", "wangwu",PageContext.APPLICATION_SCOPE);
%>
<%=pageContext.getAttribute("name",PageContext.REQUEST_SCOPE)%>
<%=pageContext.getAttribute("name",PageContext.SESSION_SCOPE)%>
<%=pageContext.getAttribute("name",PageContext.APPLICATION_SCOPE)%>
<!-- pageContext.findAttribute会从小到大搜索范围内的 name -->
<%= pageContext.findAttribute("name") %>
<%
pageContext.getRequest();
pageContext.getResponse();
pageContext.getOut();
pageContext.getSession();
pageContext.getPage();
pageContext.getException();
pageContext.getServletConfig();
pageContext.getServletContext();
%>
</body>
</html>
四大作用域的总结:
page 域(pageContext) : 当前 jsp 页面。
request 域 : 一次请求。
session 域 : 一次会话。
application 域 : 整个 web 应用。
1.jsp 标签
1)页面包含(动态包含):<jsp : include page = "被包含的页面"/>
include1.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>
<!--包含 include2 -->
<h1>This is include1 !!!</h1>
<jsp:include page="include2.jsp"></jsp:include>
</body>
</html>
include2.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>This is include2 !!!</h1>
</body>
</html>
2)请求转发(请求转发):<jsp : forward page = "要转发的资源"/>
forward1.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>This is forward1 !!!</h1>
</body>
</html>
forward2.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>This is forward2 !!!</h1>
</body>
</html>
效果:
静态包含和动态包含的区别?
demo : 商品页面的展示
数据库的部分:
CREATE TABLE `product` (
`pid` VARCHAR(32) NOT NULL,
`pname` VARCHAR(50) DEFAULT NULL,
`market_price` DOUBLE DEFAULT NULL,
`shop_price` DOUBLE DEFAULT NULL,
`pimage` VARCHAR(200) DEFAULT NULL,
`pdate` DATE DEFAULT NULL,
`is_hot` INT(11) DEFAULT NULL,
`pdesc` VARCHAR(255) DEFAULT NULL,
`pflag` INT(11) DEFAULT NULL,
`cid` VARCHAR(32) DEFAULT NULL,
PRIMARY KEY (`pid`)
)
表结构:
项目结构:
实体类:
package com.ma.domain;
public class Product {
private String pid;
private String pname;
private double market_price;
private double shop_price;
private String pimage;
private String pdate;
private int is_hot;
private String pdesc;
private int pflag;
private String cid;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getMarket_price() {
return market_price;
}
public void setMarket_price(double market_price) {
this.market_price = market_price;
}
public double getShop_price() {
return shop_price;
}
public void setShop_price(double shop_price) {
this.shop_price = shop_price;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public String getPdate() {
return pdate;
}
public void setPdate(String pdate) {
this.pdate = pdate;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
public int getPflag() {
return pflag;
}
public void setPflag(int pflag) {
this.pflag = pflag;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Product [pid=" + pid + ", pname=" + pname + ", market_price="
+ market_price + ", shop_price=" + shop_price + ", pimage="
+ pimage + ", pdate=" + pdate + ", is_hot=" + is_hot
+ ", pdesc=" + pdesc + ", pflag=" + pflag + ", cid=" + cid
+ "]";
}
}
ProductListServlet
package com.ma.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
importorg.apache.commons.dbutils.QueryRunner;
importorg.apache.commons.dbutils.handlers.BeanListHandler;
import com.ma.domain.Product;
import com.ma.utils.C3P0Utils;
/**
* Servlet implementation class ProductListServlet
*/
public class ProductListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//准备好所有数据-----List<Product>
QueryRunner runner = new QueryRunner(C3P0Utils.getDataSouce());
String sql = "select * from product";
List<Product> productList = null;
try {
productList = runner.query(sql, new BeanListHandler<Product>(Product.class));
} catch (SQLException e) {
e.printStackTrace();
}
//商品集合准备好
//将数据存到 request 域转发给 product_list.jsp 显示
request.setAttribute("productList", productList);
request.getRequestDispatcher("/product_list.jsp").forward(request, response);;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
工具类:
package com.ma.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.management.RuntimeErrorException;
import javax.sql.DataSource;
importcom.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public static DataSource getDataSouce(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///web17?useUnicode=true&characterEncoding=UTF-8</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="oracle">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///web_07</property>
<property name="user">root</property>
<property name="password">123</property>
</named-config>
</c3p0-config>
效果: