1. 程式人生 > 其它 >jsp指令元素 include中遇到的index_jsp.class檔案不生成的問題及原因

jsp指令元素 include中遇到的index_jsp.class檔案不生成的問題及原因

  今天使用jsp指令元素include將兩個jsp頁面引入另一個jsp頁面,啟動伺服器發現報500的錯誤,說index_jsp.class無法找到。於是去本地找了一下,發現確實沒有生產.class檔案

  

  那說明是.java檔案編譯生成.class檔案的過程中出現了問題,也就是這個.java檔案是有bug的,才會導致編譯無法通過。

  無法通過的jsp頁面程式碼如下圖:

 index.jsp頁面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/6/18
  Time: 11:07
  To change this template use File | Settings | File Templates.
--%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <base href="<%=basePath%>">
<title>title</title> </head> <body> <%@ include file="top.jsp"%> <h1>index頁面</h1> <%@ include file="bottom.jsp"%> </body> </html>

top.jsp頁面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/6/18
  Time: 
11:08 To change this template use File | Settings | File Templates. --%> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <base href="<%=basePath%>"> <title>title</title> </head> <body> <h1>頭部</h1> </body> </html>

問題就出在上面指令碼元素中的basePath,因為指令元素的include是靜態包含,會將被包含的jsp合併到當前jsp頁面中形成一份jsp檔案,然後翻譯成一份java檔案。這樣翻譯出來的java檔案就會有三個basePath

變數的定義,在java中變數只能宣告一次,所以編譯無法通過,無法生成.class檔案,導致異常的發生。

解決辦法,只需要將top.jsp和bottom.jsp頁面中的String basePath相關的程式碼刪除,保證最後的java檔案中不會重複宣告變數即可。