craftsman
craftsman

Reputation: 15653

Sending dynamically generated javascript file

Background:

I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:

resp.setContentType("text/javascript");
resp.getWriter().println(script);

Problem:

The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.

Question:

What should be done so that browser treats response from the servlet as a regular javascript file?

Thank you for help.

Upvotes: 5

Views: 8278

Answers (4)

BalusC
BalusC

Reputation: 1109635

It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.

I just did a quick test:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 6156155</title>
        <script src="javaScriptServlet"></script>
        <script>test()</script>
    </head>
    <body>
    </body>
</html>

with

@WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/javascript");
        response.getWriter().write("function test() { alert('peek-a-boo'); }");
    }

}

and I get

Screenshot of browser alert showing "peak-a-boo" message in it.

Upvotes: 6

zengsn
zengsn

Reputation: 5313

I think this way is better.

<%@ page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');

Set content type in JSP:

contentType="text/javascript; charset=UTF-8"

Upvotes: 0

Yohan Liyanage
Yohan Liyanage

Reputation: 7000

How do you refer to this servlet from your browser ?

If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.

Ex.

<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>

Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.

Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.

ex. Your servlet sends the following, using content type 'text/html' :

<html>
<body>
 <script type='text/javascript'>
     <!-- write your generated JS here -->
 </script>
</body>
</html>

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168845

You could always write the script 'in-line' to the web page.

Upvotes: 0

Related Questions