JSP

目录

 

1.jsp脚本和注释

jsp脚本:

jsp注释:

2.jsp运行原理---jsp本质就是servlet

jsp在第一次访问时会被WEB容器翻译成servlet,再执行

jsp本质是servlet

3.jsp指令

1.page指令 --- 属性最多的指令(实际开发中page指令默认)

2.include指令

3.taglib指令

4.JSP内置/隐式对象

1.out对象

2.pageContext对象

1)pageContext是一个域对象

2)可以获得其他8大隐式对象

5.JSP标签(动作)

1.页面包含(动态包含):

动态包含:

静态包含 : 

2.请求转发:


1.jsp脚本和注释

jsp脚本:

<%java代码%> ----- 内部的java代码翻译到service方法的内部

<% 
    int i=0;
    System.out.print(i);//在控制台打印
%>
 public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {
int i=0;
System.out.print(i);
}

<%=java变量或表达式> ----- 会被翻译成service方法内部out.print()

<%=i %>
<%=1+1 %>
<%=str %>
  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {
    out.print(i );
    out.print(1+1 );
    out.print(str );

}

<%!java代码%> ---- 会被翻译成servlet的成员的内容

<%!
	String str = "nihao China!";
%>
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
    String str = "nihao China!";
}

jsp注释:

  不同的注释可见范围是不同

  1. Html注释:<!--注释内容--> ---可见范围 jsp源码、翻译后的servlet、页面显示html源码
  2. java注释://单行注释  /*多行注释*/ --可见范围 jsp源码 翻译后的servlet
  3. jsp注释:<%--注释内容--%> ----- 可见范围 jsp源码可见

2.jsp运行原理---jsp本质就是servlet

jsp在第一次访问时会被WEB容器翻译成servlet,再执行

第一次访问---->index.jsp---->index_jsp.java---->编译运行

被翻译后的servlet在Tomcat的work目录中可以找到

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<% 
		int i=0;
		System.out.print(i);//在控制台打印
	%>
	<!-- 在页面输出 -->
	<%=i %>
	<%=1+1 %>
	<%-- jsp注释 --%>
	<%!
		String str = "nihao China!";
	%>
	<%=str %>
</body>
</html>

index_jsp.java 

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.52
 * Generated at: 2019-02-27 02:59:08 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.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {


		String str = "nihao China!";
	
  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;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  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=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, 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("<!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=ISO-8859-1\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\t");
 
		int i=0;
		System.out.print(i);//卿§å¶å°æå°
	
      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 { 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);
    }
  }
}

jsp本质是servlet

在apache-tomcat-7.0.52\conf中有内部的全局的web.xml配置文件。

当你在页面访问所有的.jsp,实质上都是servlet帮助响应和翻译的。

<servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspx</url-pattern>
</servlet-mapping>

3.jsp指令

jsp的指令是指导jsp翻译和运行的命令,jsp包括三大指令:

1.page指令 --- 属性最多的指令(实际开发中page指令默认)

属性最多的一个指令,根据不同的属性,指导整个页面特性

格式:<%@ page 属性名1= "属性值1" 属性名2= "属性值2" ...%>

常用属性如下:

language:jsp脚本中可以嵌入的语言种类

pageEncoding:当前jsp文件的本身编码---内部可以包含contentType

contentType:response.setContentType(text/html;charset=UTF-8)

session:是否jsp在翻译时自动创建session

import:导入java的包

errorPage:当当前页面出错后跳转到哪个页面

isErrorPage:当前页面是一个处理错误的页面

2.include指令

页面包含(静态包含)指令,可以将一个jsp页面包含到另一个jsp页面中

格式:<%@ include file="被包含的文件地址"%>

3.taglib指令

在jsp页面中引入标签库(jstl标签库、struts2标签库)

格式:<%@ taglib uri="标签库地址" prefix="前缀"%>

4.JSP内置/隐式对象

jsp被翻译成servlet之后,service方法中有9个对象定义并初始化完毕,我们在jsp脚本中可以直接使用这9个对象。

名称

类型

描述

out

javax.servlet.jsp.JspWriter

用于页面输出

request

javax.servlet.http.HttpServletRequest

得到用户请求信息,

response

javax.servlet.http.HttpServletResponse

服务器向客户端的回应信息

config

javax.servlet.ServletConfig

服务器配置,可以取得初始化参数

session

javax.servlet.http.HttpSession

用来保存用户的信息

application

javax.servlet.ServletContext

所有用户的共享信息

page

java.lang.Object

指当前页面转换后的Servlet类的实例

pageContext

javax.servlet.jsp.PageContext

JSP的页面容器

exception

java.lang.Throwable

表示JSP页面所发生的异常,在错误页中才起作用

被翻译后的servlet在Tomcat的work目录找index_jsp.java,这9个对象都在servlet方法中创建了。

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;
    java.lang.Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);
    if (exception != null) {
      response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    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=ISO-8859-1");
      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;
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { 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);
    }
  }
}

1.out对象

out的类型:JspWriter

out作用就是想客户端输出内容----out.write()

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	aaaaaaaaaaa
	<%
		out.write("bbbbbb");
		response.getWriter().write("ccccc");
	%>
	<%="ddddddddd" %>
</body>
</html>

 é¡µé¢è¾“出ccccccc aaaaa bbbbbbb ddddddJSP

out缓冲区默认8kb。可以设置成0,代表关闭out缓冲区,内容直接写到respons缓冲器

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="ISO-8859-1" buffer="0kb" %>

页面输出aaaaaaaa bbbbbb cccccc dddddddd 

2.pageContext对象

jsp页面的上下文对象,作用如下:

page对象与pageContext对象不是一回事

1)pageContext是一个域对象

setAttribute(String name,Object obj)

getAttribute(String name)

removeAttrbute(String name)

pageContext可以向指定的其他域中存取数据

setAttribute(String name,Object obj,int scope)

getAttribute(String name,int scope)

removeAttrbute(String name,int scope)

findAttribute(String name)

---依次从pageContext域,request域,session域,application域中获      取属性,在某个域中获取后将不在向后寻找

四大作用域的总结:

page域:当前jsp页面范围

request域:一次请求

session域:一次会话

application域:整个web应用

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<%
		//使用pageContext向request与存数据
		request.setAttribute("name", "zhangsan");
		pageContext.setAttribute("name", "sunba");
		pageContext.setAttribute("name", "lisi", PageContext.REQUEST_SCOPE);
		pageContext.setAttribute("name", "wangwu", PageContext.SESSION_SCOPE);
		pageContext.setAttribute("name", "qianqi", PageContext.APPLICATION_SCOPE);
		
		
	%>
	<%=request.getAttribute("name") %>
	<%=pageContext.getAttribute("name",PageContext.REQUEST_SCOPE) %>
	
	<!-- findAttribute从小到大搜索域的范围中name -->
	<!-- page域(PageContext对象)<request域<session域<application域 -->
	<%=pageContext.findAttribute("name") %>
	
</body>
</html>

2)可以获得其他8大隐式对象

例如: pageContext.getRequest() getResponse()....

<%
	pageContext.getRequest();
	pageContext.getOut();
	//method(request,response,session,pageContext);
	//传多个对象,只需要传一个pageContext即可
	method(pageContext);
%>

5.JSP标签(动作)

1.页面包含(动态包含):<jsp:include page="被包含的页面"/>

动态包含:

<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>this is include1 page</h1>
	<!-- 包含include2 -->
	<jsp:include page="/include2.jsp"></jsp:include>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>this is include2 page</h1>
</body>
</html>

 include1_jsp.java

public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {
      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=ISO-8859-1\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\t<h1>this is include1 page</h1>\r\n");
      out.write("\t<!-- 包含include2 -->\r\n");
      out.write("\t");
      org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/include2.jsp", out, false);
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
}

include2_jsp.java

public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {
      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=ISO-8859-1\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\t<h1>this is include2 page</h1>\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
}

静态包含 : 

先将两个jsp页面内容拼凑在一起,然后再翻译成servlet。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>this is include1 page</h1>
	<%@ include file="/include_2.jsp" %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>this is include2 page</h1>
</body>
</html>

 

 include_005f1_jsp.java

public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

      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=ISO-8859-1\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\t<h1>this is include1 page</h1>\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=ISO-8859-1\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\t<h1>this is include2 page</h1>\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
}

JSP 

2.请求转发:<jsp:forward page="要转发的资源" />

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<jsp:forward page="/forward2.jsp"></jsp:forward>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>xxxxxxxxxxxxxxxx</h1>
</body>
</html>