servlet / jsp 學習——java,關係,區別,核心概念,代碼例子

互聯網三大基石

  • HTTP: HyperText Transfer Protocol, 傳輸數據
  • URL:    Uniform Resource Locator, 定位數據
  • HTML: HyperText Markup Language, 顯示數據

servlet

servlet 就是 java,是繼承父類 HttpServlet 的 java 類。在服務器端運行,用於處理用戶的請求並給予響應。

servlet 運行過程

  1. 瀏覽器發送請求到服務器
  2. 服務器根據請求的 URL,去調用相應的 servlet(servlet 有不止一個),servlet 操作數據庫,獲取信息
  3. 通過 servlet 中打印流對象,將生成的 HTML 數據輸出給服務器
  4. 服務器將 servlet 生成的 HTML 數據再輸出給客戶端瀏覽器
  5. 瀏覽器根據服務器傳回的 HTML 數據解析,再發送請求,最終顯示出頁面

可以看出,瀏覽器和servlet不直接溝通,web服務器是媒介。下面這幅圖片很好的描述了各種關係:

圖:注意要區分Web服務器和應用服務器。Apache是Web服務器;Tomcat是Java應用服務器。Web服務器用來處理HTTP, URL, 和HTML;Tomcat用來處理Java的應用,JSP/Servlet。在開發Java的Web程序的時候,Apache和Tomcat配合在一起使用,Apache處理靜態頁面,Tomcat處理動態頁面。

servlet 學習網站


jsp

jsp經過編譯,成爲 java 類(此類的超類的超類,最終是 HttpServlet,因此也可以說 jsp 就是 servlet),所以 jsp 也是java。jsp java + html。有時候寫 jsp 就像是在寫 HTML,然後嵌套一點 Java。JSP 是簡化 Servlet 編寫的一種技術,它將 Java 和 HTML 混合在一起編寫。動態產生的內容使用 Java 代碼編寫,而固定不變的靜態內容採用 HTML 編寫。

jsp 文件在第一次運行的時候,通過 jsp 引擎( JspServlet ),會生成對應的 java 文件和 class(位置:tomcat/work/Catalina/localhost/web項目名/org/apache/jsp)

jsp 語法分爲三種不同的類型:
編譯器指令
1. page,頁面設置 < %@ page … %>)
2. include,源碼級別導入 < %@ include … %>)
3. taglib
腳本語法
1. HTML註釋,Servlet中會生成,會發給瀏覽器 < !– comments –>
2. 隱藏註釋,Servlet中不會生成,不發給瀏覽器< %– comments –>
3. 聲明,< %! … %>
4. 表達式,< %= … %>
5. java腳本段,< % … %>,在這裏直接寫入 java 代碼,變量,方法等
動作語法
< jsp:forward >, < jsp:include >, < jsp:plugin >等

jsp 學習網站


補充

servlet 和 jsp 都是屬於 Java EE 內容。Servlet 負責相應請求產生數據,並把數據通過轉發技術帶給 JSP,數據顯示用 JSP 來做。

比較 優勢 劣勢
servlet 邏輯處理方便 頁面表現麻煩
jsp 頁面表現方便 邏輯處理麻煩

 
所以 servlet 和 jsp 互補使用,一般項目是 jsp + servlet + javabean 的配置。更高級的話,使用ssh的框架。

動態網頁,數據動態生成的網頁。所謂動態生成,就是網頁事先不存在,而是瀏覽器發出請求的時候,臨時生成。它以數據庫技術爲基礎,不獨立存在於服務器上面。相關的語言有 jsp,php,asp,cgi。

web.xml:是網絡程序中一個很重要的配置文件,是 xml 的格式,servlet 的配置就在這裏面。只在服務器啓動的時候,加載一次。一個 web 項目有一個 web.xml,一個 web 項目有多個 servlet。從瀏覽器發出一個請求過來,服務器怎麼從多個 servlet 中找到某一個需要的 servlet 呢? web.xml 中的配置通過映射,解決了這個問題。相關的標籤有< servlet >,< servlet-name >, < servlet-class >, < servlet-mapping >< url-pattern >

圖:輸入url,找到對應的servlet類。步驟是1-2-3-4

Tomcat: 一個開源的Java應用服務器。和 Apache 服務器只支持靜態網頁相比,Tomcat 支持動態網頁。Tomcat 提供了servlet 引擎,還可以解析 jsp,是開發和調試 servlet,jsp 的首選。


show me the code

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 'index.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> 
    Hello World, this is my JSP page.<br>
  </body>
</html>

 
jsp 編譯過後的 java 代碼:(java代碼比較冗餘,拼湊字符串的感覺。。)

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;

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

  private static java.util.List _jspx_dependants;

  public Object getDependants() {
    return _jspx_dependants;
  }

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

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      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 'index.jsp' starting page</title>\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("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body> \n");
      out.write("    Hello World, this is my JSP page.<br>\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

 
用瀏覽器打開jsp文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章