JSP 簡單入門與 IDEA 開發環境配置


原作者為 RioTian@cnblogs, 本作品采用 CC 4.0 BY 進行許可,轉載請注明出處。

在學 Java 連接數據庫時老師提到過 JSP,剛好這個學期有 JSP 的課程,現做一些基礎以及環境配置的介紹。

什么是 JSP?

  • 動態網頁技術標准
  • 能把 Java 代碼嵌入靜態的頁面中
  • JSP 編譯器把 JSP 文件編譯成 Java 寫的 Servlet(服務器端程序),再交由 Java 編譯器
<html>
    <title>Hello world!</title>
    <body>
        <%=out.println("Hello world!")%>
    </body>
</html>

環境配置

  1. 語言環境:JDK
  2. 網頁服務器:Tomcat,安裝教程
  3. IDE:IntelliJ IDEA / Eclipse

前兩點非常簡單不再贅述。

老師竟然說 JSP 沒什么好用的編輯器只能在 Eclipse 中寫(黑人問號

明明 IDEA 就很好....

這里記錄一下 IDEA 如何配置 JSP 的開發環境

IntelliJ IDEA Configuration

  • 新建一個 Java Enterprise 項目,下面 Application Server 選擇新建

    選擇 Tomcat Server,設置 Tomcat Home (安裝目錄)

這里需要注意 IDEA 可能會沒有權限訪問 Tomcat 的目錄,導致無法讀取 Tomcat,需要手動訪問一次該目錄提權:

  • Windows:資源管理器直接訪問,會提示需要管理員權限,點繼續就 OK 了

  • Linux:chmod 777

  • 下面 Additional Libraries and Frameworks 選擇 Web Application,

    點 Next,改名創建,得到如下圖所示結構的項目

image-20210917213110401
  • 打開 index.jsp

    打開右上角 Edit Configuration

    選擇 Application server

    URL 一般是:http://localhost:8080/demo_war_exploded/

    其中 demo 為項目名字,_war_exploded 為自動生成的后綴,需要保留

  • 打開 Deployment,界面應如下圖

​ 如果這個 war_exploded 沒有出現在里面的話點擊右邊加號自己加進去

  • 簡單寫一下 index.jsp

    比如下面實現了一個簡單的 Hello world 的頁面

<html>
    <title>Hello world!</title>
    <body>
        <%=out.println("Hello world!")%>
    </body>
</html>
  • 點擊右上角 Run,開始運行

update:21.9.22

切回至“Server”,在“Open Browser”設置里,

建議勾選上“After Launch”,意思為當啟動TomCat后,自動打開瀏覽器並運行項目,此時同樣可以在別的瀏覽器手動輸入地址進行訪問。

建議將“On 'Update' action”和“On frame deactivation”設置為“Update classes and resources”,這樣當修改項目內容時會自動更新字節碼文件和資源文件,避免反復重啟TomCat服務器:

Question & Solution

運行之后會大概率出現以下問題,不要問我怎么知道的…


\[QAQ \]


  • 端口超界,不能為 - 1

原因:Tomcat 安裝的默認 Shutdown 端口為 - 1,需要修改一下

解決:打開 Tomcat 安裝目錄下的 server.xml,類似如下路徑

C:\Program Files\apache-tomcat-8.5.71-windows-x64\apache-tomcat-8.5.71\conf\server.xml

修改 shutdown port 為任一未被占用的端口 (1024 - 65535),如圖中 8005 位置

  • 端口 8080 已被占用

原因:Tomcat 運行中並占用了 8080 端口

解決:打開剛才的 Edit Configuration,修改 Tomcat Server Settings 中的 HTTP port 為任一未被占用的端口 (1024 - 65535),如圖中”8088”,同時別忘修改上面的 URL 的端口

  • output 輸出亂碼

原因:Tomcat 根據你的操作系統默認語言使用了 GBK 編碼

解決:打開 Tomcat 安裝目錄下的 logging.properties,類似如下路徑

C:\Program Files\apache-tomcat-8.5.71-windows-x64\apache-tomcat-8.5.71\conf\logging.properties

修改大約第 47 行的

java.util.logging.ConsoleHandler.encoding = UTF-8

java.util.logging.ConsoleHandler.encoding = GBK

  • 打開網頁 404

    原因:URL 寫錯了,定位不到文件

    解決:Edit Configuration 中檢查一下 URL 是否與端口設置一致,是否正確定位了文件路徑

  • 輸出一堆紅色字

    正常現象,開發者選色鬼才

  • 網頁調試的方法

    運行之后修改了代碼,怎么才能重新看到修改后的網頁呢?

    無需終止 Tomcat 重新運行,只需在左下這個位置點擊 Deploy,然后刷新網頁就可以啦

如果沒有問題此時應該可以正確運行啦,開始在 IDE 中愉快的寫 JSP 吧(霧


\[QAQ \]


基本語法

因為了解不深,詳細的就不多說了。

除了特別的這幾個,其他的都和 HTML 與 Java 語法規則差不多。

腳本

<%
	//在這里編寫你的Java代碼
%>

任何文本、HTML 標簽、JSP 元素必須寫在腳本程序的外面

聲明

<%!
    //Java
%>

用於聲明變量、方法,要寫函數只能在這里面

必須先聲明才可以使用

表達式

<%= //Java %>

表達式里面的代碼可以不寫分號

注釋

<%-- 該部分注釋在網頁中不會被顯示 --%> 

<!-- 該部分注釋在網頁源代碼中會被顯示 --> 

指令

<%@ page 頁面屬性 %>
<%@ include 包含文件 %>
<%@ taglib 標簽 %>

模板

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!--導入的Java包-->
<html>
<head>
    <title>網頁標題</title>
</head>
<body>

<%!
    //定義變量
%>

<%!
    //定義函數
%>

<%
    //腳本
%>

<!-- 在這里定義其他網頁上展示的組件 -->

</body>
</html>

示例:計算 N 的階乘

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Calc</title>
</head>
<body>
<div style="text-align: center;"/>
<h1>
  Calculate N!
</h1>
<!--*.jsp-->
<form action="index.jsp"/>
<input type="number" name="num"/><br/><br/>
<input type="submit"/><br/><br/>
<form/>

<%!
    private int n = -1;
%>
<%!
    public int fac(int n) {
        if (n < 0) {
            return n;
        } else if (n == 0) {
            return 1;
        } else {
            int product = 1;
            for (int i = 1; i <= n; i++) {
                product *= i;
                if (product < 0) {
                    break;
                }
            }
            return product;
        }
    }
%>
<%
    try {
        int n = fac(Integer.parseInt(request.getParameter("num")));
        if (n < 0) {
            out.print("<h2>invalid</h2>");
        } else {
            out.print("<h2>"+n+"</h2>");
        }
    } catch (Exception e) {
        //ignore java.lang.NumberFormatException: null
    }
%>

</body>
</html>

示例:數據庫查詢系統

  • 依賴包:mysql-connector-java-5.1.*.jar
  • 可能需要將 jar 包拷貝到項目路徑下的 WEB-INF/lib 中(不存在就新建)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
    <title>Database Query System</title>
</head>
<body>
<div style="text-align: center;">
    <h1>Database Query System</h1>
    <h2>powered by bipy</h2><br/>
    <form method="post">
        <textarea name="SQL_statement" rows=10 cols=100></textarea><br/>
        <input type="submit" name="Submit"/>
        <input type="reset" name="Clear"/>
    </form>
</div>
<br/>
</body>
<%!
    private Statement statement;
    private String sql_input;
    private Connection connection;
    private boolean status = false;
%>
<%!
    //判斷SQL語句類型,並返回結果(影響個數/報錯/結果集)
    public Object process(String sql) {
        try {
            if (sql.toLowerCase().matches("^(update|create|use|drop|delete|insert).*$")) {
                return statement.executeUpdate(sql);
            } else if (sql.toLowerCase().matches("^(show|select).*$")) {
                return statement.executeQuery(sql);
            } else {
                return "Not Supported";
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return "SQL syntax error";
        }
    }
%>
<%
    try {
        //避免重新建立連接而丟棄前面步驟
        if (!status) {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost", "root", "123");
            statement = connection.createStatement();
            status = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
%>
<div style="text-align: center">
    <%
    	//結果輸出
        sql_input = request.getParameter("SQL_statement");
        if (sql_input != null) {
            Object rt = process(sql_input);
            if (rt instanceof String) {
                out.print("<h2>" + rt.toString() + "</h2>");
            } else if (rt instanceof Integer) {
                out.print("<h2>" + "Query OK. " + rt + " effected." + "</h2>");
            } else {
                ResultSet rs = (ResultSet) rt;
                ResultSetMetaData rsmd = rs.getMetaData();
                out.println("<table align=\"center\" border=\"1\">");
                out.println("<tr>");
                for (int i = 1; i <= rsmd.getColumnCount(); ++i)
                    out.println("<th>" + rsmd.getColumnName(i) + "</th>");
                out.println("<tr>");
                while (rs.next()) {
                    out.println("<tr>");
                    for (int i = 1; i <= rsmd.getColumnCount(); ++i)
                        out.println("<td>" + rs.getString(i) + "</td>");
                    out.println("</tr>");
                }
                out.println("</table>");
            }
        }
    %>
</div>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM