jsp初学书籍推荐_面向初学者的JSP示例教程

jsp初学书籍推荐

Welcome to the JSP Example Tutorial for Beginners. In last few posts, a wrote a lot about Java Servlet and got very good response from our readers. So I have started another series on JSP tutorials and this is the first post of the series.

欢迎使用面向初学者的JSP示例教程。 在最近的几篇文章中,A撰写了许多有关Java Servlet的文章,并获得了读者的良好响应。 因此,我开始了有关JSP教程的另一个系列,这是该系列的第一篇文章。

JSP示例教程 (JSP Example Tutorial)

jsp example, jsp tutorial, jsp example programs, jsp programming, jsp tutorial for beginners

In this JSP example tutorial, we will look into the basics of JSP, advantages of JSP over Servlets, Life Cycle of JSP, JSP API interfaces and Classes and where can we put JSP files in the web application.


在本JSP示例教程中,我们将研究JSP的基础知识,JSP相对于Servlet的优势,JSP的生命周期,JSP API接口和类,以及在何处将JSP文件放入Web应用程序中。

We will also look into the JSP Comments, Scriptlets, Directives, Expression, Declaration and JSP attributes in brief detail. Some of these topics are very important and we will look into them in more detail in future posts.

我们还将简要介绍一下JSP注释,脚本,指令,表达式,声明和JSP属性。 其中一些主题非常重要,我们将在以后的文章中对其进行更详细的研究。

JSP教程 (JSP Tutorial)

  1. What is JSP and why do we need JSP?

    什么是JSP,为什么我们需要JSP?
  2. Advantages of JSP over Servlets?

    JSP优于Servlet?
  3. Life cycle of JSP Page

    JSP页面的生命周期
  4. Life cycle methods of JSP

    JSP的生命周期方法
  5. Simple JSP Example with Eclipse and Tomcat

    Eclipse和Tomcat的简单JSP示例
  6. JSP Files location in Web Application WAR File

    Web应用程序WAR文件中的JSP文件位置
  7. JSP API Interfaces and Classes

    JSP API接口和类
  • JSP Comments

    JSP注释
  • JSP Scriptlets

    JSP脚本
  • JSP Expression

    JSP表达式
  • JSP Directives

    JSP指令
  • JSP Declaration

    JSP宣言
  • JSP transformed Servlet Source Code and Class File location in Tomcat

    JSP转换了Tomcat中的Servlet源代码和类文件位置
  • JSP init parameters

    JSP初始化参数
  • Overriding JSP init() method

    重写JSP init()方法
  • Attributes in a JSP

    JSP中的属性
    1. 什么是JSP,为什么我们需要JSP? (What is JSP and why do we need JSP?)

      JSP (JavaServer Pages) is server side technology to create dynamic java web application. JSP can be thought as an extension to servlet technology because it provides features to easily create user views.

      JSP Page consists of HTML code and provide option to include java code for dynamic content. Since web applications contain a lot of user screens, JSPs are used a lot in web applications. To bridge the gap between java code and HTML in JSP, it provides additional features such as JSP Tags, Expression Language, Custom tags. This makes it easy to understand and helps a web developer to quickly develop JSP pages.

      JSP (JavaServer Pages)是创建动态Java Web应用程序的服务器端技术。 JSP可以看作是Servlet技术的扩展,因为它提供了易于创建用户视图的功能。

      JSP页面由HTML代码组成,并提供选项以包含用于动态内容的Java代码。 由于Web应用程序包含许多用户屏幕,因此JSP在Web应用程序中使用很多。 为了弥合Java代码和JSP中HTML之间的鸿沟,它提供了其他功能,例如JSP标记,表达式语言,自定义标记。 这使它易于理解,并帮助Web开发人员快速开发JSP页面。

    2. JSP优于Servlet? (Advantages of JSP over Servlets?)

      • We can generate HTML response from servlets also but the process is cumbersome and error prone, when it comes to writing a complex HTML response, writing in a servlet will be a nightmare. JSP helps in this situation and provide us flexibility to write normal HTML page and include our java code only where it’s required.
      • JSP provides additional features such as tag libraries, expression language, custom tags that helps in faster development of user views.
      • JSP pages are easy to deploy, we just need to replace the modified page in the server and container takes care of the deployment. For servlets, we need to recompile and deploy whole project again.

      Actually Servlet and JSPs compliment each other. We should use Servlet as server side controller and to communicate with model classes whereas JSPs should be used for presentation layer.

      • 我们也可以从servlet生成HTML响应,但是过程繁琐且容易出错,当涉及到编写复杂HTML响应时,编写servlet将是一场噩梦。 JSP可在这种情况下提供帮助,并为我们提供了编写普通HTML页面的灵活性,并且仅在需要时才包含Java代码。
      • JSP提供了其他功能,例如标签库,表达语言,自定义标签,这些功能有助于更快地开发用户视图。
      • JSP页面易于部署,我们只需要替换服务器中已修改的页面即可,容器负责部署。 对于servlet,我们需要重新编译并再次部署整个项目。

      实际上,Servlet和JSP相互补充。 我们应该使用Servlet作为服务器端控制器并与模型类进行通信,而JSP应该用作表示层。

    3. JSP页面的生命周期 (Life cycle of JSP Page)

      JSP life cycle is also managed by container. Usually every web container that contains servlet container also contains JSP container for managing JSP pages.

      JSP pages life cycle phases are:

      • Translation – JSP pages doesn’t look like normal java classes, actually JSP container parse the JSP pages and translate them to generate corresponding servlet source code. If JSP file name is home.jsp, usually its named as home_jsp.java.
      • Compilation – If the translation is successful, then container compiles the generated servlet source file to generate class file.
      • Class Loading – Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it gets loaded into memory.
      • Instance Creation – After JSP class is loaded into memory, its object is instantiated by the container.
      • Initialization – The JSP class is then initialized and it transforms from a normal class to servlet. After initialization, ServletConfig and ServletContext objects become accessible to JSP class.
      • Request Processing – For every client request, a new thread is spawned with ServletRequest and ServletResponse to process and generate the HTML response.
      • Destroy – Last phase of JSP life cycle where it’s unloaded into memory.

      JSP生命周期也由容器管理。 通常,每个包含servlet容器的Web容器还包含用于管理JSP页面的JSP容器。

      JSP页面的生命周期阶段为:

      • 转换 – JSP页面看起来不像普通的Java类,实际上是JSP容器解析JSP页面并转换它们以生成相应的servlet源代码。 如果JSP文件名是home.jsp,通常将其命名为home_jsp.java。
      • 编译 –如果转换成功,则容器会编译生成的servlet源文件以生成类文件。
      • 类加载 –将JSP编译为servlet类后,其生命周期类似于servlet,并且将其加载到内存中。
      • 实例创建 –将JSP类加载到内存中后,其对象将由容器实例化。
      • 初始化 –然后初始化JSP类,并将其从普通类转换为servlet。 初始化之后,JSP类可以访问ServletConfig和ServletContext对象。
      • 请求处理 –对于每个客户端请求,都会使用ServletRequest和ServletResponse生成一个新线程来处理和生成HTML响应。
      • 销毁 -JSP生命周期的最后阶段,将其卸载到内存中。
    4. JSP的生命周期方法 (Life cycle methods of JSP)

      JSP lifecycle methods are:

      1. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to initialize config params.
      2. _jspService(HttpServletRequest request, HttpServletResponse response) declared in HttpJspPage interface and response for handling client requests.
      3. jspDestroy() declared in JspPage interface to unload the JSP from memory.

      JSP生命周期方法是:

      1. 在JspPage接口中声明的jspInit() 。 在JSP生命周期中仅调用一次此方法以初始化配置参数。
      2. 在HttpJspPage接口中声明的_jspService(HttpServletRequest请求,HttpServletResponse响应)和用于处理客户端请求的响应。
      3. 在JspPage接口中声明的jspDestroy ()可以从内存中卸载JSP。
    5. Eclipse和Tomcat的简单JSP示例 (Simple JSP Example with Eclipse and Tomcat)

      We can use Eclipse IDE for building dynamic web project with JSPs and use Tomcat to run it. Please read Java Web Applications tutorial to learn how can we easily create JSPs in Eclipse and run it in tomcat.

      A simple JSP example page example is:

      home.jsp

      <%@ page language="java" contentType="text/html; charset=US-ASCII"
          pageEncoding="US-ASCII"%>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
      <title>First JSP</title>
      </head>
      <%@ page import="java.util.Date" %>
      <body>
      <h3>Hi Pankaj</h3><br>
      <strong>Current Time is</strong>: <%=new Date() %>
      
      </body>
      </html>

      If you have a simple JSP that uses only JRE classes, we are not required to put it as WAR file. Just create a directory in the tomcat webapps folder and place your JSP file in the newly created directory. For example, if your JSP is located at apache-tomcat/webapps/test/home.jsp, then you can access it in browser with URL https://localhost:8080/test/home.jsp. If your host and port is different, then you need to make changes in URL accordingly.

      我们可以使用Eclipse IDE通过JSP构建动态Web项目,并使用Tomcat运行它。 请阅读Java Web应用程序教程,以了解如何在Eclipse中轻松创建JSP并在tomcat中运行它。

      一个简单的JSP示例页面示例是:

      home.jsp

      如果您有一个仅使用JRE类的简单JSP,则不需要将其作为WAR文件放置。 只需在tomcat webapps文件夹中创建一个目录,然后将JSP文件放置在新创建的目录中。 例如,如果您的JSP位于apache- tomcat/webapps/test/home.jsp ,则可以在浏览器中使用URL https://localhost:8080/test/home.jsp 。 如果主机和端口不同,则需要相应地更改URL。

    6. Web应用程序WAR文件中的JSP文件位置 (JSP Files location in Web Application WAR File)

      We can place JSP files at any location in the WAR file, however if we put it inside the WEB-INF directory, we wont be able to access it directly from client.

      We can configure JSP just like servlets in web.xml, for example if I have a JSP example page like below inside WEB-INF directory:

      test.jsp

      <%@ page language="java" contentType="text/html; charset=US-ASCII"
          pageEncoding="US-ASCII"%>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
      <title>Test JSP</title>
      </head>
      <body>
      Test JSP Page inside WEB-INF folder.<br>
      Init Param "test" value =<%=config.getInitParameter("test") %><br>
      HashCode of this object=<%=this.hashCode() %>
      </body>
      </html>

      And I configure it in web.xml configuration as:

      Then I can access it with both the URLs https://localhost:8080/FirstJSP/Test.do and https://localhost:8080/FirstJSP/Test1.do

      Notice that container will create two instances in this case and both will have their own servlet config objects, you can confirm this by visiting these URLs in browser.

      For Test.do URI, you will get response like below.

      Test JSP Page inside WEB-INF folder.
      Init Param "test" value =Test Value
      HashCode of this object=1839060256

      For Test1.do URI, you will get response like below.

      Notice the init param value in second case is null because it’s not defined for the second servlet, also notice the hashcode is different.
      If you will make further requests, the hashcode value will not change because the requests are processed by spawning a new thread by the container.

      Did you noticed the use of config variable in above JSP example but there is no variable declared, it’s because its one of the 9 implicit objects available in JSP page, read more about them at JSP Implicit Objects.

      我们可以将JSP文件放在WAR文件中的任何位置,但是,如果将其放在WEB-INF目录中,我们将无法直接从客户端访问它。

      我们可以像配置web.xml中的servlet一样配置JSP,例如,如果我在WEB-INF目录中具有如下所示的JSP示例页面:

      test.jsp

      <%@ page language="java" contentType="text/html; charset=US-ASCII"
          pageEncoding="US-ASCII"%>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
      <title>Test JSP</title>
      </head>
      <body>
      Test JSP Page inside WEB-INF folder.<br>
      Init Param "test" value =<%=config.getInitParameter("test") %><br>
      HashCode of this object=<%=this.hashCode() %>
      </body>
      </html>

      我在web.xml配置中将其配置为:

      然后我可以使用URL https:// localhost:8080 / FirstJSP / Test.do和https:// localhost:8080 / FirstJSP / Test1.do来访问它

      注意,在这种情况下,容器将创建两个实例,并且两个实例都将具有自己的servlet配置对象,您可以通过在浏览器中访问这些URL来确认。

      对于Test.do URI,您将获得如下响应。

      Test JSP Page inside WEB-INF folder.
      Init Param "test" value =Test Value
      HashCode of this object=1839060256

      对于Test1.do URI,您将获得如下响应。

      注意第二种情况下的init参数值是null,因为它没有为第二个servlet定义,还请注意哈希码是不同的。
      如果您将发出进一步的请求,则哈希码值将不会更改,因为通过容器产生新线程来处理请求。

      你有没有注意到使用配置变量在上面的JSP的例子,但没有声明的变量,这是因为在JSP页面中提供的9个隐含对象的一个,以了解更多有关他们JSP隐式对象

    7. JSP API接口和类 (JSP API Interfaces and Classes)

      All the core JSP interfaces and classes are defined in javax.servlet.jsp package. Expression Language API interfaces are classes are part of javax.servlet.jsp.el package. JSP Tag Libraries interfaces and classes are defined in javax.servlet.jsp.tagext package.

      Here we will look into interfaces and classes of Core JSP API.

      所有核心JSP接口和类都在javax.servlet.jsp包中定义。 表达式语言API接口的类是javax.servlet.jsp.el软件包的一部分。 JSP标记库接口和类在javax.servlet.jsp.tagext包中定义。

      在这里,我们将研究Core JSP API的接口和类。

    • JspPage接口 (JspPage Interface)

      JspPage interface extends Servlet interface and declares jspInit() and jspDestroy() life cycle methods of the JSP pages.

      JspPage接口扩展了Servlet接口,并声明了JSP页面的jspInit()和jspDestroy()生命周期方法。

    • HttpJspPage接口 (HttpJspPage Interface)

      HttpJspPage interface describes the interaction that a JSP Page Implementation Class must satisfy when using the HTTP protocol. This interface declares the service method of JSP page for HTTP protocol as public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException.

      HttpJspPage接口描述了使用HTTP协议时JSP页面实现类必须满足的交互。 此接口声明用于HTTP协议的JSP页面的服务方法,因为public void _jspService(HttpServletRequest request,HttpServletResponse response)抛出ServletException,IOException

    • JspWriter抽象类 (JspWriter abstract Class)

      Similar to PrintWriter in servlets with additional facility of buffering support. This is one of the implicit variables in a JSP page with name “out”. This class extends java.io.Writer and container provide their own implementation for this abstract class and use it while translating JSP page to Servlet. We can get it’s object using PageContext.getOut() method. Apache Tomcat concrete class for JspWriter is org.apache.jasper.runtime.JspWriterImpl.

      与Servlet中的PrintWriter相似,具有额外的缓冲支持功能。 这是名称为“ out”的JSP页面中的隐式变量之一。 此类扩展了java.io.Writer,并且容器为该抽象类提供了自己的实现,并在将JSP页面转换为Servlet时使用它。 我们可以使用PageContext.getOut()方法获取它的对象。 JspWriter的Apache Tomcat具体类是org.apache.jasper.runtime.JspWriterImpl

    • JspContext抽象类 (JspContext abstract Class)

      JspContext serves as the base class for the PageContext class and abstracts all information that is not specific to servlets. The JspContext provides mechanism to obtain the JspWriter for output, mechanism to work with attributes and API to manage the various scoped namespaces.

      JspContext用作PageContext类的基类,并抽象出所有非特定于servlet的信息。 JspContext提供了获取用于输出的JspWriter的机制,与属性配合使用的机制以及用于管理各种作用域名称空间的API。

    • PageContext抽象类 (PageContext abstract Class)

      PageContext extends JspContext to provide useful context information when JSP is used for web applications. A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically.

      当将JSP用于Web应用程序时,PageContext扩展了JspContext以提供有用的上下文信息。 PageContext实例提供对与JSP页面关联的所有命名空间的访问,提供对若干页面属性的访问,以及在实现详细信息上方的一层。 隐式对象会自动添加到pageContext中。

    • JspFactory抽象类 (JspFactory abstract Class)

      The JspFactory is an abstract class that defines a number of factory methods available to a JSP page at runtime for the purposes of creating instances of various interfaces and classes used to support the JSP implementation.

      JspFactory是一个抽象类,它定义了一些在运行时可用于JSP页面的工厂方法,目的是创建用于支持JSP实现的各种接口和类的实例。

    • JspEngineInfo抽象类 (JspEngineInfo abstract Class)

      The JspEngineInfo is an abstract class that provides information on the current JSP engine.

      JspEngineInfo是一个抽象类,提供有关当前JSP引擎的信息。

    • ErrorData最终类 (ErrorData final Class)

      Contains information about an error, for error pages.

      包含有关错误的信息,用于错误页面。

    • JspException类 (JspException Class)

      A generic exception known to the JSP container, similar to ServletException.If JSP pages throw JspException then errorpage mechanism is used to present error information to user.

      JSP容器已知的通用异常,类似于ServletException。如果JSP页面抛出JspException,则使用errorpage机制将错误信息呈现给用户。

    • JspTagException类别 (JspTagException Class)

      Exception to be used by a Tag Handler to indicate some unrecoverable error.

      标签处理程序将使用该异常来指示某些不可恢复的错误。

    • SkipPageException类 (SkipPageException Class)

      Exception to indicate the calling page must cease evaluation. Thrown by a simple tag handler to indicate that the remainder of the page must not be evaluated. This exception should not be thrown manually in a JSP page.

      指示调用页面的异常必须停止评估。 由简单的标记处理程序抛出,以指示不得评估页面的其余部分。 不应在JSP页面中手动引发此异常。

  • JSP注释 (JSP Comments)

    Since JSP is built on top of HTML, we can write comments in JSP file like html comments as

    <-- This is HTML Comment -->

    These comments are sent to the client and we can look it with view source option of browsers.

    We can put comments in JSP files as:

    <%-- This is JSP Comment--%>

    This comment is suitable for developers to provide code level comments because these are not sent in the client response.

    由于JSP建立在HTML之上,因此我们可以在JSP文件中编写注释,例如html注释,如下所示:

    <-- This is HTML Comment -->

    这些评论发送到客户端,我们可以使用浏览器的查看源选项来查看它。

    我们可以在JSP文件中添加如下注释:

    <%-- This is JSP Comment--%>

    此注释适合开发人员提供代码级注释,因为这些注释不会在客户端响应中发送。

  • JSP脚本 (JSP Scriptlets)

    Scriptlet tags are the easiest way to put java code in a JSP page. A scriptlet tag starts with <% and ends with %>.

    Any code written inside the scriptlet tags go into the _jspService() method.

    For example:

    <%
    Date d = new Date();
    System.out.println("Current Date="+d);
    %>

    Scriptlet标记是将Java代码放入JSP页面的最简单方法。 scriptlet标记以<%开头,以%>结束。

    在scriptlet标记内编写的任何代码都将放入_jspService()方法。

    例如:

  • JSP表达式 (JSP Expression)

    Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and ends with %>.

    <% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>

    Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.

    由于大多数情况下,我们使用out.print()方法在JSP页面中打印动态数据,因此存在通过JSP表达式执行此操作的捷径。 JSP表达式以<%=开头,以%>结束。

    <% out.print("Pankaj"); %> 可以使用JSP表达式将<% out.print("Pankaj"); %>编写为<%= "Pankaj" %>

    注意, <%= %>之间的任何内容都作为参数发送到out.print()方法。 还要注意,scriptlet可以包含多个java语句,并且始终以分号(;)结尾,但表达式不以分号结尾。

  • JSP指令 (JSP Directives)

    JSP Directives are used to give special instructions to the container while JSP page is getting translated to servlet source code. JSP directives starts with <%@ and ends with %>

    For example, in above JSP Example, I am using page directive to to instruct container JSP translator to import the Date class.

    JSP指令用于在将JSP页面转换为Servlet源代码时向容器提供特殊说明。 JSP指令以<%@开头,以%>结尾

    例如,在上面的JSP示例中,我使用page指令来指示容器JSP转换器导入Date类。

  • JSP宣言 (JSP Declaration)

    JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.

    For example we can create an int variable in JSP at class level as <%! public static int count=0; %>

    JSP声明用于声明servlet类的成员方法和变量。 JSP声明以<%!开头<%! 并以%>结尾。

    例如,我们可以在JSP中以<%! public static int count=0; %>级别创建int变量<%! public static int count=0; %> <%! public static int count=0; %>

  • JSP转换了Tomcat中的Servlet源代码和类文件位置 (JSP transformed Servlet Source Code and Class File location in Tomcat)

    Once JSP files are translated to Servlet source code, the source code (.java) and compiled classes both are place in Tomcat/work/Catalina/localhost/FirstJSP/org/apache/jsp directory. If the JSP files are inside other directories of application, the directory structure is maintained.

    For JSPs inside WEB-INF directory, its source and class files are inside Tomcat/work/Catalina/localhost/FirstJSP/org/apache/jsp/WEB_002dINF directory.

    Here is the source code generated for above test.jsp page.

    test_jsp.java

    /*
     * Generated by the Jasper component of Apache Tomcat
     * Version: Apache Tomcat/7.0.32
     * Generated at: 2013-08-21 03:40:59 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.WEB_002dINF;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.jsp.*;
    
    public final class test_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 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=US-ASCII");
          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("\n");
          out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"https://www.w3.org/TR/html4/loose.dtd\">\n");
          out.write("<html>\n");
          out.write("<head>\n");
          out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=US-ASCII\">\n");
          out.write("<title>Test JSP</title>\n");
          out.write("</head>\n");
          out.write("<body>\n");
          out.write("Test JSP Page inside WEB-INF folder.<br>\n");
          out.write("Init Param \"test\" value =");
          out.print(config.getInitParameter("test") );
          out.write("<br>\n");
          out.write("HashCode of this object=");
          out.print(this.hashCode() );
          out.write("\n");
          out.write("</body>\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);
        }
      }
    }

    Notice following points in above servlet code;

    • The package of class starts with org.apache.jsp and if JSPs are inside other folders, it includes directory hierarchy too. Usually we dont care about it.
    • The generates servlet class is final and can’t be extended.
    • It extends org.apache.jasper.runtime.HttpJspBase that is similar to HttpServlet except that it’s internal to Tomcat JSP Translator implementation. HttpJspBase extends HttpServlet and implements HttpJspPage interface.
    • Notice the local variables at the start of _jspService() method implementation, they are automatically added by JSP translator and available for use in service methods, i.e in scriptlets.

    As a java programmer, sometimes it helps to look into the generated source for debugging purposes.

    将JSP文件转换为Servlet源代码后,源代码(.java)和已编译的类都将放置在Tomcat / work / Catalina / localhost / FirstJSP / org / apache / jsp目录中。 如果JSP文件位于应用程序的其他目录中,则将维护目录结构。

    对于WEB-INF目录中的JSP,其源文件和类文件位于Tomcat / work / Catalina / localhost / FirstJSP / org / apache / jsp / WEB_002dINF目录中。

    这是为以上test.jsp页面生成的源代码。

    test_jsp.java

    注意上面的servlet代码中的以下几点;

    • 该类的软件包以org.apache.jsp开头,如果JSP位于其他文件夹中,则它也包括目录层次结构。 通常我们不关心它。
    • 生成的Servlet类是最终的,不能扩展。
    • 它扩展了类似于HttpServlet的org.apache.jasper.runtime.HttpJspBase ,但它是Tomcat JSP Translator实现的内部。 HttpJspBase扩展了HttpServlet并实现了HttpJspPage接口。
    • 注意在_jspService()方法实现开始时的局部变量,它们由JSP转换程序自动添加,并且可用于服务方法(即scriptlet)中。

    作为Java程序员,有时出于调试目的,有助于查看生成的源代码。

  • JSP初始化参数 (JSP init parameters)

    We can define init parameters for the JSP page as shown in above example and we can retrieve them in JSP using config implicit object, we will look into implicit objects in JSP in more detail in future posts.

    我们可以为JSP页面定义初始化参数,如上面的示例所示,我们可以使用config隐式对象在JSP中检索它们,我们将在以后的文章中更详细地研究JSP中的隐式对象。

  • 重写JSP init()方法 (Overriding JSP init() method)

    We can override JSP init method for creating resources to be used by JSP service() method using JSP Declaration tags, we can override jspInit() and jspDestroy() or any other methods also. However we should never override _jspService() method because anything we write in JSP goes into service method.

    我们可以使用JSP声明标签覆盖JSP初始化方法来创建供JSP service()方法使用的资源,也可以覆盖jspInit()和jspDestroy()或任何其他方法。 但是,我们绝不应该重写_jspService()方法,因为我们在JSP中编写的所有内容都会进入服务方法。

  • JSP中的属性 (Attributes in a JSP)

    Apart from standard servlet attributes with request, session and context scope, in JSP we have another scope for attributes, i.e Page Scope that we can get from pageContext object. We will look it’s importance in custom tags tutorial. For normal JSP programming, we don’t need to worry about page scope.

    除了具有请求,会话和上下文范围的标准servlet属性外,在JSP中,我们还有另一个属性范围,即我们可以从pageContext对象获得的页面范围。 我们将在自定义标签教程中看到它的重要性。 对于普通的JSP编程,我们不必担心页面范围。

  • Thats all for JSP example tutorial for beginners. I hope it helps you in understanding the basic concepts of JSPs and help you in getting started. We will look into other JSP features in future posts.

    以上就是针对初学者的JSP示例教程。 我希望它能帮助您理解JSP的基本概念并帮助您入门。 我们将在以后的文章中探讨其他JSP功能。

    翻译自: https://www.journaldev.com/2021/jsp-example-tutorial-for-beginners

    jsp初学书籍推荐

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值