Web开发-JSP 序

    学习资料来自www.runoob.com

    JSP(Java Server Pages)与PHP、ASP.NET类似,也是运行在服务端的语言。

    JSP是以Java语言作为脚本语言,为服务器端的Java库提供了一个接口来服务于HTTP的应用程序,文件后缀为.jsp

1.什么是JSP

        Java Server Pages是一种动态网页开发技术,在原本静态的HTML文件上插入Java代码,通常以<%开头,以%>结束。

        JSP是一种Java Servlet,可以访问数据库,记录用户选择信息等等。同时,使用Java语言的优势在于可以容易的移植非MS平台。

2.Eclipse JSP/Servlet环境搭建

        在菜单栏Windows --> Preference中,选择Server中的Runtime Environments,然后选择右侧的Add

        选择自己的Tomcat版本,点击Next,选择JRE,点击Finish完成配置。

        选择File --> New --> Dynamic Web Project创建项目,在新建页面的Target Runtime中点击New Runtime,配置自己的Runtime和JRE,点击finish,记得勾选Generate web.xml deployment descriptor。

        

扫描二维码关注公众号,回复: 3686744 查看本文章

   deployment descriptor:部署的描述

   Web App Libraries:自己加的包可以放在里面

   build:放入编译之后的文件

   WebContent:放进写入的页面

   在WebContent文件夹下新建一个test.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>

</body>
</html>

      修改一下Title,在<body>标签中添加out.println("Hello World!");

      接着在程序运行之前,将浏览器选项Web Browser改成Default System web browser 

      接着运行项目 Run As --> Run on Server

      如果报错:"Starting Tomcat v8.0 at localhost" has encountered a problem. Serveral ports(8005,8080,8009) required by Tomcat Server at localhost are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the port. To start this server you will need to stop the other process or change the port number(s). "

      是因为Eclipse运行程序时会自动启动Tomcat,若Tomcat运行则会报错。手动关闭Tomcat后可正常运行。

      访问localhost:8080/TomcatTest/test.jsp

      也可以使用Servlet创建,选择File --> New --> Servlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
  * Servlet implementation class HelloServlet
  */
@WebServlet("/HelloServlet")

public class HelloServlet extends HttpServlet{
     private static final long serialVersionUID = 1L;

     /**
       * @see HttpServlet#HttpServlet()
       */
     public HelloServlet(){
         super();
         // TODO Auto-generated constructor stub
     }

     /**
       * @see HttpServlet@doGet(HttpServletRequest request, HttpServletResponse reponse)
       */
       protected void doGet(HttpServletRequest request, HttpServletResponse response)
                                                   throws ServletException,IOException{
          //使用GBK设置中文正常显示
          response.setCharacterEncoding("GBK");
          response.getWriter().write("菜鸟教材:http://www.runoob.com");
        }
       
        /**
          * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
        protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
           // TODO Auto-generated method stub
               doGet(request, response);
         }
}
        
            
          

      web.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
      xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <servlet>
      <!--类名-->
      <servlet-name>HelloServlet</servlet-name>
      <!--所在的包-->
      <servlet-class>com.runoob.test.HelloServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>HelloServlet</servlet-name>
      <!--访问的地址-->
      <url-pattern>/TomcatTest/HelloServlet</url-pattern>
      </servlet-mapping>
</web-app>
 

     3. JSP结构

               网络服务器需要一个JSP引擎,也就是一个容器处理JSP页面。容器负责截获对JSP页面的请求。

               JSP容器与Web服务器协同合作,为JSP的正常运行提供必要的运行环境和其他服务,并且能够正确识别专属于JSP网页特殊元素。

            Web服务器使用JSP创建网页过程:

            1.浏览器发送一个HTTP请求给服务器

            2.Web服务器识别这是对JSP网页的请求,并且将该请求传递给JSP引擎。通过使用URL或者.jsp文件来完成。

            3. JSP引擎从磁盘中载入JSP文件,然后将它们转化为Servlet。这种转化只是简单的将所有模板文本改用println()语句,并且将所有JSP转化成Java代码。

            4.JSP引擎将Servlet编译成可执行类,并将原始请求传递给Servlet。

            5.Web服务器的某组件将会调用Servlet引擎,然后载入并执行Servlet类。在执行过程中,Servlet产生HTML格式的输出并将其内嵌于HTTP Response中上交给Web服务器

            6.Web服务器以静态HTML网页的形式将HTTP Response返回到您的浏览器中。

            7.最终,Web浏览器处理HTTP Response中动态产生的HTML网页

4.JSP生命周期

         (1).编译阶段:Servlet容器编译Servlet源文件,生成Servlet类

         (2).初始化阶段:加载与JSP对应的Servlet类,创建其实例,并调用它的初始化方法

         (3).执行阶段:调用与JSP对应的Servlet实例的服务方法

         (4).销毁阶段:调用与JSP对应的Servlet实例的销毁方法,然后销毁Servlet实例

          

      JSP编译:当浏览器请求JSP页面时,首先会去检查是否需要编译这个文件。若未编译或编译后更改过,则编译这个JSP文件。 编译有三个步骤:解析JSP文件、将JSP文件转为Servlet、编译Servlet。

      JSP初始化:容器载入JSP文件后,它会在为请求提供任何服务前调用jspInit()方法。如果您需要执行自定义的JSP初始化任务,复写jspInit()方法,例如:

public void jspInit(){
   //初始化代码
}

       JSP执行:JSP网页完成初始化后,会调用_jspService()方法,_jspService()方法需要一个HttpServletRequest对象和一个HttpServletResponse对象作为它的参数,例如:

void _jspService(HttpServletRequest request, HttpServletResponse response)
{
   //服务端处理代码
}

      JSP清理:jspDestroy()方法在JSP中等价于Servlet的销毁方法。当需要执行任何清理工作时复写jspDestroy()方法,比如释放数据库连接或者关闭文件夹等。

public void jspDestroy()
{
   //清理代码
}

      JSP生命周期代码实例如下:

<%@ page language="java" contentType="text/html"; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>life.jsp</title>
</head>
<body>

<%!
   private int initVar=0;
   private int serviceVar=0;
   private int destroyVar=0;
%>

<%!
   public void jspInit(){
      initVar++;
      System.out.println("jspInit():JSP被初始化了"+initVar+"次");
   }
   public void jspDestroy(){
      destroyVar++;
      System.out.println("jspDestroy():JSP被销毁了"+destroyVar+"次");
   }
%>

<%
  serviceVar++;
  System.out.println("_jspService():JSP共响应了"+serviceBar+"次请求")

  String content1="初始化次数:"+initVar;
  String content2="相应客户请求次数:"+serviceVar;
  String content3="销毁次数:"+destroyVar;
%>
  <p><%=content1 %></p>
  <p><%=content2 %></p>
  <p><%=content3 %></p>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/Kayaobi/article/details/83096922