JavaWeb——JSP学习

目录

JSP的三种注释

JSP的page指令

JSP的静态引入和动态引入

JSP九大内置对象

JSP的路径问题


问题:在学习了 Servlet 之后,使用 Servlet 进行页面的展现,代码书写过于麻烦。极大的影响了开发的效率,那么有没有一种方式可以让我们像以前写网页一样来进行网页的编程工作呢?
解决:使用 JSP 技术
概念:JSP 全名为 Java Server Pages,中文名叫 java 服务器页面,其根本是一个简化的 Servlet 设计,它 是由 SunMicrosystems 公司倡导、许多公司参与一起建立的一种动态网页技术标准。
特点:

  • 本质上还是 Servlet

跨平台,一次编写处处运行

  • 组件跨平台
  • 健壮性(对复杂的业务逻辑也能进行处理)和安全性

Jsp 的访问原理: 浏览器发起请求,请求 JSP,请求被 Tomcat 服务器接收,执行JspServlet 将请求的 JSP 文件转义成为对应的 java 文件(也是Servlet),然后执行转义好的 java 文件。

jsp访问原理图

    <!--服务器(tomcat)web.xml中的配置-->
    <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>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- The mappings for the JSP servlet -->
    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspx</url-pattern>
    </servlet-mapping>

eg:第一个jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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 '1.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>
    This is my JSP page. <br>
  </body>
</html>

查看1.jsp的运行原理

然后我们查看下经过处理的后的JSP文件内容:

本质上JSP文件还是Servlet的文件形式,只是为了我们开发者的方便操作。

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.93
 * Generated at: 2019-03-29 07:50:45 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.*;

public final class _1_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() {
  }

  //Servlet中的service方法
  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');
      out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>My JSP '1.jsp' starting page</title>\r\n");
      out.write("    \r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("    This is my JSP page. <br>\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } 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);
    }
  }
}
package org.apache.jasper.runtime;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;
import org.apache.jasper.compiler.Localizer;

/**
*  其实可以注意到,我们上面的Servlet中继承的是org.apache.jasper.runtime.HttpJspBase类,那如
*  我们所知Servlet需要继承HttpServlet,那不言而喻这个类必然继承了HttpServlet
*/
public abstract class HttpJspBase
  extends HttpServlet
  implements HttpJspPage
{
  private static final long serialVersionUID = 1L;
  
  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();
  }
  
  public final void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    //在此将request对象和respose对象传给_1_jsp.class中的方法
    _jspService(request, response);
  }
  
  public void jspInit() {}
  
  public void _jspInit() {}
  
  public void jspDestroy() {}
  
  protected void _jspDestroy() {}
  
  public abstract void _jspService(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws ServletException, IOException;
}

JSP的三种注释

  • 前端语言注释(在浏览器中可以看到)<!--    -->
    • 会被转译,也会被发送,但不会被浏览器执行
  • JAVA语言注释(三种)
    • 会被转译,但不会被Servlet执行
  • JSP注释(在浏览器中看不到)<%--  --%>
    • 不会被转译

JSP的page指令

<@%page  属性名=“属性值”  属性名=“属性值” ...... %>

  • language :  声明jsp要被转译成的语言
  • import : 声明转译的java文件要导入的包,不同的包使用逗号隔开
  • pageEncoding :  设置jsp文件的数据编码格式
  • contentType : 设置jsp数据响应给浏览器时,浏览器解析和编码格式
  • session :  设置转译的servlet中是否开始session支持,默认开启
  • errorPage :  设置jsp运行错误跳转的页面
  • extends :  设置jsp文件转译的java继承的父类(包名+类名)
  • buffer : “none” 或 ”8 kb”(默认值) 或 ”自定义值kb”; SP页面是否需要缓冲。即我们直到JSP转换后的Servlet中包含大量的通过out对象进行输出,但输出的数据并非直接写给浏览器,而是直到缓冲满时才将数据发送回浏览器上。
  • autoFlush : JSP页面是否自动刷新。默认为true
  • isThreadSafe :  默认为true;JSP中的“isThreadSafe”属性如果设置为“false”,那么表示转换后的Servlet将会继承SingleThreadMode接口,以Singleton(单线程)模式运行,这种模式同一个时刻只允许一个实例,若多个用户同时访问该JSP,那么只有先访问者完全访问完该页面后,后访问者才能开始进行访问。而如果“isThreadSafe”属性设置为“true”,默认值也是“true”,那么表示转换后的Servlet以多线程方式运行,是线程安全的。
  • 而如果“isThreadSafe”属性设置为“true”,默认值也是“true”,那么表示转换后的Servlet以多线程方式运行,是线程安全的。
  • info : 自定义信息;用于在JSP页面中定义一些说明,可以在Servlet中通过getServletInfo()方法获取通过page指令获取”info”的值。
  •  isErrorPage : 当我们将某个JSP页面设置为错误处理页面,那么我们最好将该页面设置page指令的“isErrorPage”属性,并置其为“true”。 默认为true;
  • isELIgnored : 该JSP页面是否忽略EL表达式  ; 默认值(false)

别人对于page指令的理解,及其是错误页面的处理

作用:配置jsp文件转译相关的参数

 

JSP的局部代码块:

  • 特点:局部代码块中声明的java代码会被原样的转译到jsp对应的servlet文件中的_JspService方法中;并且代码中声明的变量是局部变量
  • 使用:<% java代码 %>
  • 缺点:使用局部代码在jsp中进行逻辑判断特别麻烦,
  • 开发:在servlet中进行逻辑判断处理,在jsp中进行页面显示

JSP的全局代码块

  • 特点:声明的java代码会作为全局代码转译到相应的servlet中
  • 使用:<%!   java全局代码  %>
  • 注意 :  全局代码块中声明的代码,需要在局部代码块中调用

JSP的脚本段语句:

  • 特点:帮助我们快速的获取变量和方法的返回值作为数据响应给浏览器
  • 使用:<%=  变量名或是方法%>
  • 注意:不可以使用分号
  • 位置: “任意位置”
<%@ page language="java" import="java.util.*" pageEncoding="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 '1.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">
  </head>
  
  <body>
  	<!-- jsp的局部代码块 -->
    <% int a = 4;  %>
    <% if(a > 2) { %>
    
    <i>我在学习jsp的局部代码块</i>
    
    <%} else{ %>
    
    <i>我学习,我快乐</i>
    <% } %>
    
    <!-- jsp的全局代码块 -->
    <%! int s = 10;%>
    <%! 
    	void test(){
    		System.out.println("jsp全局代码块的学习");
    	}
     %>
     
     <% test();%>
     
     
     <!-- jsp的脚本段语句 -->
     <%= s %>
     <%!
     	int test1(){
     		return 1;
     	}
      %>
      <%= test1() %>
    
	
  </body>
</html>

以下是该代码所生成的java代码

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.93
 * Generated at: 2019-03-29 11:58:33 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.*;

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

 int s = 10;
 
    	void test(){
    		System.out.println("jsp全局代码块的学习");
    	}
     

     	int test1(){
     		return 1;
     	}
      
  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');
      out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>My JSP '1.jsp' starting page</title>\r\n");
      out.write("    \r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("  \t<!-- jsp的局部代码块 -->\r\n");
      out.write("    ");
 int a = 4;  
      out.write("\r\n");
      out.write("    ");
 if(a > 2) { 
      out.write("\r\n");
      out.write("    \r\n");
      out.write("    <i>我在学习jsp的局部代码块</i>\r\n");
      out.write("    \r\n");
      out.write("    ");
} else{ 
      out.write("\r\n");
      out.write("    \r\n");
      out.write("    <i>我学习,我快乐</i>\r\n");
      out.write("    ");
 } 
      out.write("\r\n");
      out.write("    \r\n");
      out.write("    <!-- jsp的全局代码块 -->\r\n");
      out.write("    ");
      out.write("\r\n");
      out.write("    ");
      out.write("\r\n");
      out.write("     \r\n");
      out.write("     ");
 test();
      out.write("\r\n");
      out.write("     \r\n");
      out.write("     \r\n");
      out.write("     <!-- jsp的脚本段语句 -->\r\n");
      out.write("     ");
      out.print( s );
      out.write("\r\n");
      out.write("     ");
      out.write("\r\n");
      out.write("      ");
      out.print( test1() );
      out.write("\r\n");
      out.write("    \r\n");
      out.write("\t\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } 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);
    }
  }
}

JSP的静态引入和动态引入

静态引入(编译时包含)

  • <%@include  file =" 你要引入的jsp文件的相对路径" %>
  • 特点:
    • 会将引入的jsp文件和当前的jsp文件合并在一起转译成一个java(Servlet)文件
    • 在网页中也就显示了合并后的效果
  • 注意:
    • 静态引入的jsp文件不会单独的转译成一个java(Servlet)文件
    • 当前jsp文件和被静态引入的jsp文件不能声明相同的变量名和方法名

动态引入(运行时包含)

  • <jsp:include  page =" 要引入的jsp文件的相对路径"> </jsp:include>
  • 特点:
    • 被引入的jsp文件单独转译,在当前转译好的java文件中调用引入的jsp文件的转译文件
    • 在网页中显示合并的结果
  • 注意:动态引入中允许声明同名变量和方法

优点:降低jsp代码的冗余,便于后期维护升级;

<%@ page language="java" import="java.util.*" pageEncoding="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%>">
  </head>
  
  <body>
    <h1>我是主页面,下来看我如何静态导入文件</h1>
    <br>
    <br>
    <!-- 静态导入文件 -->
    <%@include  file="2.jsp"%>
    <!-- 动态导入文件 -->
    <jsp:include page="3.jsp"></jsp:include>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
  </head>
  		
  <body>
    <br>
    <br>
    <h1>俺就是要被静态引入的文件</h1>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
  <head>
    <base href="<%=basePath%>">
  </head>
  
  <body>
    <br>
    <br>
    <h1>俺就是要被动态引入的文件</h1>
  </body>
</html>

下面就是在网页呈现出来的结果

以下是生成的java(servlet)文件

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.93
 * Generated at: 2019-03-29 13:15:56 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.*;
import java.util.*;

public final class include_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;

  static {
    _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1);
    _jspx_dependants.put("/2.jsp", Long.valueOf(1553864077503L));
  }

  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');
      out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("    <h1>我是主页面,下来看我如何静态导入文件</h1>\r\n");
      out.write("    <br>\r\n");
      out.write("    <br>\r\n");
      out.write("    <!-- 静态导入文件 -->\r\n");
      out.write("    ");
      out.write('\r');
      out.write('\n');



      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    \r\n");
      out.write("  </head>\r\n");
      out.write("  \t\t\r\n");
      out.write("  <body>\r\n");
      out.write("    <br>\r\n");
      out.write("    <br>\r\n");
      out.write("    <h1>俺就是要被静态引入的文件</h1>\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
      out.write("\r\n");
      out.write("    <!-- 动态导入文件 -->\r\n");
      out.write("    ");
      org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "3.jsp", out, false);
      out.write("\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } 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);
    }
  }
}

查看jsp被转译成java(servlet)的work目录下的文件时,被静态导入的文件并未转译成java(Servlet)文件

jsp转发标签forward :

  • 使用: <jsp:forward  page="要转发的jsp文件的相对路径"></jsp:forward>
  • 特点:一次请求、地址栏信息不变
  • 注意:
    • 在转发标签的俩个标签中除了写<jsp:param  name= "键名"  value = "值数据"  />子标签不会报错,其他任意字符都会报错
      • name :附带的数据的键名
      • value :附带数据内容
    • 获取数据 request.getParameter("name")
    • 数据会以?的形式拼接在转发路径的后面

JSP九大内置对象

内置对象:jsp文件转译成servlet文件时自动生成的并声明的对象,我们在jsp中直接使用即可

注意:内置对象在jsp中使用,只能放在局部代码块和脚本段语句来使用,不能在全局代码块中使用

九大对象:

  • pagecontext :页面上下文文件,封存了其他内置对象,封存了当前jsp的运行信息
    • 注意 : 每个jsp文件单独拥有一个pagecontext对象
    • 作用域 :  当前页面
  • requesrt :  封存当前请求数据的对象,由tomcat服务器创建,一次请求
  • session : 此对象用来存储用户的不同请求的共享数据,一次会话
  • application : 也就是servletContext对象,一个项目中只有一个,存储用户共享数据的对象
  • respose :  响应对象,用来响应请求处理结果给浏览器对象,设置请求头,重定向
  • out : jsp内部使用,带有缓冲区的响应对象,效率高于respose
  • page:代表当前页面,相当于java中的this
  • exception:异常对象,存储当前运行的异常信息
    • 注意:在使用此对象时,需要在page指令中设置属性:isErrorPage="true"开启;
  • config:也就是ServletConfig,主要用来换气web.xml中配置的数据,完成一些初始化数据读取

四个作用域:

  • pagecontext:当前页面,解决了当前页面中的数据共享问题(范围小,很少使用),获取其他内置对象
  • request:一次请求,一次请求的servlet的数据共享,通过请求转发,将数据流转给下一个servlet
  • session:一次会话,一个用户的不同请求的数据共享,将数据从一次请求流转给其他请求。
  • application:项目内,不同用户的数据共享问题,将数据从一个用户流转给其他用户
  • 作用:数据的流转

JSP的路径问题

  • 在jsp中资源路径可以使用相对路径来实现跳转,但是会出现问题
    • 问题一:资源的位置不可以随便改变;位置改变===》找不到对于的位置
    • 问题二:需要使用../进行文件的跳转,使用起来比较麻烦
  • 使用绝对路径:(必须掌握)
    • /虚拟项目名/项目资源路径
    • 例如:
      • <a href = "/jsp/a.jsp">a.jsp</a>
    • 注意:在jsp中资源的第一个/ 表示的是服务器根目录,相当于localhost:8080
  • 使用JSP自带的全局路径的声明
    • <%
               String path = request.getContextPath();
               String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      %>   
         
    • <base href="<%=basePath%>">   
    • 作用:给资源前面添加项目路径,   http://localhost:8080/JSP/                                                                                                                                                                                                                                                                                                   

猜你喜欢

转载自blog.csdn.net/qq_41965731/article/details/88892164
今日推荐