1

So in eclipse when you generate a .jsp file it automatically includes the following top line:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

Is there a way to also include javascript code so that I can have some of the file written in java and some written in javascript?

4
  • 1
    Um, include an external JavaScript file? Do you realize that Java and JavaScript do not run at the same time? Commented Mar 15, 2013 at 2:21
  • 2
    But what if I need to use information from my java code? For example, I want to query a mysql database using java and then use the information I get there to do stuff with javascript Commented Mar 15, 2013 at 2:23
  • 1
    Learn about the page lifecycle. Commented Mar 15, 2013 at 2:24
  • 1
    That's a very vague statement. Commented Mar 15, 2013 at 2:25

2 Answers 2

4

Usually I include my JavaScript in JSP like this:

<script type="text/javascript" src="js/script.js"></script>

This way I can minimize the js code and also cache it differently than JSP files in Tomcat.

Sign up to request clarification or add additional context in comments.

Comments

1

The answer is Yes, you can add the js in jsp. And this also has benefit. It helps you to use the values stored in request and session, because the js code which contains the jsp stuff in jsp will be compiled while the *.js file will not. And also you should keep in mind that you'd better put the js code in .js file not in jsp, so the browser doesn't need to load it repeatly and code seems more clear, also good for debug. Another answer has give you the example code to import js file, so I just ignore it.

8 Comments

So how exactly would I take the values stored in a request and use it in javascript code?
var userId='<%=(String)request.getAttribute("userId")%>'
@OQJF From when did JavaScript start to compile ? Its much better to have the JS code in separate .js file.
@A. K. your misunderstood what I mean, And surely I know that we'd better put js code in *.js, but for some special thing that we have to do this to directly contact with request or session. Nothing is the absolute, right?
@OQJF There is no limitation in putting JavaScript code in .js files. If you want to use a request attribute in JavaScript code, then retrieve the request attribute in JSP and pass the value to JavaScript function present in .js file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.