我一直試圖運行在我的javaee應用程序中使用jquery而不是純javascript。下面的代碼顯示了我一直無法得到我的頭的應用程序。每次運行應用程序,它都會給我一個空白頁面。不知何故jQuery不加載在tomcat服務器上。我該如何去解決它?JQuery不在tomcat工作
<html>
<head>
<title>Erycoking | JSON</title>
<script src="WEB-INF/lib/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON("${pageContext.request.contextPath}/getCDs.jsp", function (response) {
var cds = response.catalog.cd;
alert(JSON.stringify(cds));
$.each(cds, function (ind, val) {
$('body.container').append('<li>' + cds[ind].title + ' : '
+ cds[ind].artist + '</li>');
});
});
});
</script>
</head>
<body>
<ul class='container'></ul>
</body>
</html>
我getCDs.jsp是到這裏
<jsp:useBean id="fetchBean" class="fetcher.FetchXML" />
<jsp:getProperty name="fetchBean" property="json" />
我FetchXML.java是到這裏
public class FetchXML {
public void setJson(String json){}
public String getJson(){
JSONObject json = null;
try {
String xml = "";
URL url = new URL("http://www.w3schools.com/xml/cd_catalog.xml");
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line = br.readLine()) != null) xml+= line;
br.close();
xml = xml.replace("'", "");
json = XML.toJSONObject(xml.toLowerCase());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
}
最後我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>fetch.jsp</welcome-file>
</welcome-file-list>
</web-app>
這裏是我的文件結構 enter image description here
在一個標準的java web應用中,'WEB-INF/lib'文件夾用於存儲.jar文件,並且不會像JavaScript文件那樣作爲資源公開給網絡。而不是這樣做:將所有'.js','html'文件放在'WEB-INF'之外,如下所示:'web/js/jquery.js'然後當你需要使用它時,只需使用像這樣的相對路徑''請參閱此鏈接瞭解關於java web應用程序結構的更多信息https://softwareengineering.stackexchange.com/questions/222732/java-web-應用程序 - 文件夾結構 –
@DanielC。跟着你的建議,但它仍然不工作 – Erycoking
如果它不起作用,那麼請分享您從瀏覽器中獲得的控制檯日誌,它會給我們更多關於此行爲的信息。 –