可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to call a function of javascript from servlet.
servlet code:
File ff = new File(uploadedFile+"/"+fileName+".mp4"); FileOutputStream fileOutSt = new FileOutputStream( ff ); fileOutSt.write(data); fileOutSt.close(); request.setAttribute("src", ff); RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/jsfunction.js"); dispatcher.include(request, response);
my javascript code:
myfunction(fileInput) { var fileUrl = window.URL.createObjectURL(fileInput); }
The problem is javascript calls but it display the code content but not execute it. how can i get fileURL.
回答1:
Several things are wrong here:
First, the inclusion of your javascript source is improper, because the javascript must be included (or referenced) always within an HTML file. In your case, instead, you are serving a MP4 file.
If you must absolutely execute that js code (remember that js is always executed in a browser), I suggest you serve an HTML page instead. In this case, the jsfunction.js script must be referenced within the HTML code:
<html> <head> <script type="text/javascript" src="jsfunction.js" /> </head> <body> ... </body> </html>
Second: Even if you include the script, you must then invoke your function. You can call it immediately, from a scriptlet, or as a response to some client event (onclick, onload, etc).
回答2:
javascript plays on client side and Servlet plays on server side. You cannot execute Javascript on serverside. It should execute by browser.
I suggest you to make a javascript call in window onload.
回答3:
RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. But not to JS. Since JS always runs in browser itself.
request.setAttribute("filename",filenamehere); //put filename RequestDispatcher requestDispatcher; requestDispatcher = request.getRequestDispatcher("/filename.jsp");//dispatch here requestDispatcher.forward(request, response);
In filename.jsp
String value = (String)request.getAttribute("filename");//getting filename
Do like this. This way we will get the file url.
How to pass response from servlet to html
Call your servlet in same html using ajax with jquery.
In servlet
//getting input from `html` page String userName = request.getParameter("userName").trim(); //now process your request here //forward response to `html` page response.setContentType("text/plain"); response.getWriter().write("your file url");
In html call this servlet using ajax
$.ajax({ url : 'yourservletaction', data : { userName : $('#userName').val()//if you want to send any input do like this }, success : function(responseText) { $('#ajaxGetUserServletResponse').text(responseText);//getting file url as response. so use this url in you js } });