今天周末,首先祝大家過得開心。好了,今天要講的就是怎樣使用<script>去請求一個servlet,加載一些js資源以及額外的邏輯處理:
目錄:
首先我們說一下,一般js引入到jsp或者html的幾種方式:
document.write("<script src='test.js'><\/script>");
s1.src="test.js"
var head= document.getElementsByTagName('HEAD').item(0);
var script = document.createElement("script");
script.type = "text/javascript";
script.src="test.js";
head.appendChild(script);
function ajaxPage(sId, url){
var oXmlHttp = GetHttpRequest() ;
oXmlHttp.onreadystatechange = function() {
if (oXmlHttp.readyState == 4)
{
includeJS( sId, url, oXmlHttp.responseText );
}
}
oXmlHttp.open('GET', url, false);//同步操作
oXmlHttp.send(null);
}
function includeJS(sId, fileUrl, source) {
if ( ( source != null ) && ( !document.getElementById( sId ) ) ){
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement( "script" );
oScript.type = "text/javascript";
oScript.id = sId;
oScript.text = source;
oHead.appendChild(oScript );
}
}
function GetHttpRequest() {
alert("huhx");
}
好了,進入我們今天的正題,讓我們一起學習條在scirpt中引入servlet,並加載js的:我們創建一個web項目
一、 創建一個Servlet,命名為:JsServlet.java
package com.tomhu.servlet;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/x-javascript");
byte abyte0[] = new byte[512];
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
String path = getServletContext().getRealPath("js/ajax.js");
InputStream inputStream = new FileInputStream(path);
do {
int i = inputStream.read(abyte0);
if (i < 0)
break;
bytearrayoutputstream.write(abyte0, 0, i);
} while (true);
byte abyte1[] = bytearrayoutputstream.toByteArray();
ServletOutputStream httpservletresponse = response.getOutputStream();
response.setContentLength(abyte1.length);
httpservletresponse.write(abyte1);
inputStream.close();
httpservletresponse.flush();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
二、 ajax.js的位置以及內容:
//javascript
function test() {
alert("hello world.");
}
三、 為了看到結果,我們定義在index.jsp中寫入了以下內容:
<script type="text/javascript" src="servlet/JsServlet"> ...... <button onclick="test()">Button1</button>
四、 點擊按鈕,出現Hello World的彈窗,ajax.js中的test方法得到執行:
五、 既然script標簽能引入Servlet,那麼css的link標簽呢?
歡迎大家留言補充!