标签:
今天周末,首先祝大家过得开心。好了,今天要讲的就是怎样使用<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标签呢?
欢迎大家留言补充!
标签:
原文地址:http://www.cnblogs.com/huhx/p/dynamicJS.html