七、JSp

一、JSP介绍
JSP全名为Java Server Pages,中文名叫java服务器页面,其根本是一个简化的Servlet设计,它实现了在java当中使用HTML标签,是一种动态的网页技术标准也是javaee的标准,jsp与servlet一样也是在服务端执行的。当访问一个jsp页面时,其实也是在访问一个Servlet,服务器在执行jsp的时候,首先把jsp翻译成一个Servlet,所以我们访问jsp时,其实不是在访问jsp,而是在访问jsp翻译过后的那个Servlet。
二、案例
<body>
     <%
          SimpleDateFormat f = new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          String d = f.format(new Date());
          out.write(d);
     %>
</body>
三、原理
1 、访问到index.jsp页面,tomcat扫描到jsp文件,在%tomcat%/work把jsp文件翻译成java源文件
( index . .jsp   ->   index ..java) (翻译)
2、tomcat服务器把java源文件编译成class字节码文件 (编译)
index . java  ->  _01 index .class)
3、tomcat服务器构造_ index .jsp类对象
4、tomcat服务器调用_ index. jsp类里面方法,返回内容显示到浏览器。
第一次访问jsp:
走1,2,3,4
第n次访问jsp:
走4
注意:

  1. jsp文件修改了或jsp的临时文件被删除了,要重新走翻译(1)和编译(2)的过程
   三·、运行原理
 当我们通过浏览器访问index.jsp时,服务器首先将index.jsp翻译成一个index_jsp.class,在Tomcat服务器的D:\Tomcat7.0\work\Catalina\localhost\JSP\org\apache\jsp目录下可以看到index.jsp.class的源代码文件index.jsp.java

/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.70
* Generated at: 2018-03-30 01:39:54 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.Date;
import java.text.SimpleDateFormat;

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

  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 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,
                  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("\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");

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = f.format(new Date());
        out.write(d);
    
      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);
    }
  }
}

HttpJspBase 
public abstract class HttpJspBase
    extends HttpServlet
    implements HttpJspPage
        
    
{
    
    protected HttpJspBase() {
    }
    public final void init(ServletConfig config)
     throws ServletException
    {
        super.init(config);
     jspInit();
        _jspInit();
    }
    
    public String getServletInfo() {
     return Localizer.getMessage("jsp.engine.info");
    }
    public final void destroy() {
     jspDestroy();
     _jspDestroy();
    }
    /**
     * Entry point into service.
     */
    public final void service(HttpServletRequest request,  HttpServletResponse response)
     throws ServletException, IOException
    {
        _jspService(request, response);
    }
    
    public void jspInit() {
    }
    public void _jspInit() {
    }
    public void jspDestroy() {
    }
    protected void _jspDestroy() {
    }
    public abstract void _jspService(HttpServletRequest  request,
                        HttpServletResponse response)
     throws ServletException, IOException;
}

四、语法
1、JSP模版元素
  JSP页面中的HTML内容称之为JSP模版元素。
  JSP模版元素定义了网页的基本骨架,即定义了页面的结构和外观。
2、二、JSP表达式
  JSP脚本表达式(expression)用于将程序数据输出到客户端
      语法:<%= 变量或表达式 %>
      举例:输出当前系统时间:
<%= new java.util.Date() %>
JSP引擎在翻译脚本表达式时,会将程序数据转成字符串,然后在相应位置用 out.print(…) 将数据输给客户端。
          JSP脚本表达式中的变量或表达式后面不能有分号(;)。
   <%="<h1>hello</h1>"%>

三、JSP脚本片断
  JSP脚本片断(scriptlet)用于在JSP页面中编写多行Java代码。语法:
    <%
           多行java代码
    %>
  在<% %>中可以定义变量、编写语句,不能定义方法
注意事项:
  • jsp脚本片段中只能出现java代码,不能出现其他模版元素,jsp引擎在翻译jsp脚本片段中的java代码将被原封不动的放到servlet的 jspservice方法中
  • jsp脚本片段中的java代码必须严格遵循java语法,结尾要加分号
  • 在一个jsp页面中可以有多个脚本片段,在两个或多个脚本片段之间可以嵌套HTML及jsp元素      
五、声明
   JSP页面中编写的所有代码,默认会翻译到servlet的service方法中, 而Jsp声明中的java代码被翻译到_jspService方法的外面。语法:
    <%!
        java代码
    %>
  所以, JSP声明可用于定义JSP页面转换成的Servlet程序的静态代码块、成员变量和方法
  多个静态代码块、变量和函数可以定义在一个JSP声明中,也可以分别单独定义在多个JSP声明中。
  JSP隐式对象的作用范围仅限于Servlet的_jspService方法,所以在JSP声明中不能使用这些隐式对象。
六、注释
显示注释:
    HTML:<!-- -->被注释的文本和代码,会翻译到servlet中,然后发送到客户端
隐式注释:
        java的注释:被注释的文本和代码,会翻译到servlet中,不会发送的客户端
        jsp的注释:不会翻译到servlet中,不会发送到客户端
七、jsp指令
  1、  指令语法
        JSP指令的基本语法格式:<%@ 指令 属性名="值" %>
例如:
<%@ page contentType="text/html;charset=gb2312"%>
        如果一个指令有多个属性,这多个属性可以写在一个指令中,也可以分开写。
  例如:
 <%@ page contentType="text/html;charset=gb2312"%>
 <%@ page import="java.util.Date"%>
        也可以写作:
         <%@ page contentType="text/html;charset=gb2312" import="java.util.Date"%>
2、page指令
<%@ page
    [ language="java" ]
    [ extends="package.class" ]//httpjspbase
    [ import="{package.class | package.*}, ..." ]
    [ session=" true | false" ]//是否使用内置对象session
    [ buffer="none | 8kb | sizekb" ]
    [ autoFlush=" true | false" ]
    [ isThreadSafe=" true | false" ]
    [ info="text" ]
    [ errorPage="relative_url" ]
    [ isErrorPage="true | false" ]
    [ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ]
    [ pageEncoding="characterSet | ISO-8859-1" ]
    [ isELIgnored="true | false" ]
%>
  • page指令的import属性
      在Jsp页面中,Jsp引擎会自动导入下面的包
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
  可以在一条page指令的import属性中引入多个类或包,其中的每个包或类之间使用逗号(,)分隔
例如:
             <%@ page import="java.util.*,java.io.*,java.sql.*"%>
上面的语句也可以改写为使用多条page指令的import属性来分别引入各个包或类
例如:
<%@ page import="java.util.Date"%>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %
  • page指令的errorPage属性
errorPage属性的设置值必须使用相对路径,如果以“/”开头,表示相对于当前Web应用程序的根目录(注意不是站点根目录),否则,表示相对于当前页面

错误处理页Error404
<%@ page language="java" contentType="text/html;  charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>
<!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>error</h1>
<%=exception.getMessage() %>
</body>
</html>
错误页jsp
<%@ page language="java" contentType="text/html;  charset=UTF-8"
    pageEncoding="UTF-8" errorPage="/Error404.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>
<%=10/0 %>
</body>
</html
通过excption.getMessage();获取异常信息
可以在web.xml文件中使用<error-page>元素为整个Web应用程序设置错误处理页面。
    <error-page>元素有3个子元素,
    <error-code>、<exception-type>、<location>
    <error-code>子元素指定错误的状态码,
例如:<error-code>404</error-code>
    <exception-type>子元素指定异常类的完全限定名,
例如:<exception-type>java.lang.ArithmeticException</exception-type>
    <location>子元素指定以“/”开头的错误处理页面的路径,例如:    <location>/404Error.jsp</location>

如果设置了某个JSP页面的errorPage属性,那么在web.xml文件中设置的错误处理将不对该页面起作用。
使用errorPage属性指明出错后跳转的错误页面

  • include
用于在jsp界面中包含web资源,把多个web资源一起翻译到一个servlet中
属性:file“相对路径”
  • taglib
引入标签库
url:路径
p:别名


猜你喜欢

转载自blog.csdn.net/gj_user/article/details/80147768