vtokmak
vtokmak

Reputation: 1506

How to use JSTL and other Spring tag in javascript file?

I have two files, first one is list.jsp and other one is loadmore.js I am calling loadmore.js in list.jsp file. I want to use tags like <spring:message code="loadMore" /> and <c:out value="${loadmore}" /> in my JavaScript file. But I don't know how to use or import these libraries in JavaScript file.

Can you help how to do this?


Update: added the following to my configuration:

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>compilerSourceVM</param-name>
        <param-value>1.5</param-value>
    </init-param>
    <init-param>
        <param-name>compilerTargetVM</param-name>
        <param-value>1.5</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>

But now I get the following message in my FireBug console.

missing ) after argument list console.log("<spring:message code="label.empty" />"); 

Upvotes: 1

Views: 7774

Answers (2)

wabisabit
wabisabit

Reputation: 412

You can put all your external JavaScript inside a function that accepts variables defined in a <script> tag inside the .jsp.

In your .jsp (I'm using jQuery):

<script src='<spring:url value="/resources/script.js"/>'></script>

<script>
$(function() {
    var messages = {
        some_message: '<spring:message code="some.message" text="some.message"/>'   
    };

    init(messages);
});

And then in your .js file:

function init(msg) {
    console.log(msg.some_message);
}

Upvotes: 2

nfechner
nfechner

Reputation: 17545

In order to use JSP tags in a JS file, you need to apply your JSP Engine to it (e.g. Jasper in case of a Tomcat server). To do that, you could add the following to you web.xml file:

<servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>

Upvotes: 0

Related Questions