четверг, 29 мая 2014 г.

Generate javascript with jsp

What if you need to dynamically  generate your javascript file on server? I mean no JSON file, but regular javascript files.

You can achieve this with jsp like so:

1) Set the header on your jsp "<%@page language="java" contentType="text/JavaScript" pageEncoding="UTF-8" isELIgnored="true"%>".

Pay attention to attribute isELIgnored. If you use jQuery or some other js library then you'd better set isELIgnored to true to prevent servlet container to interpret the constructions like ${} as EL constructs.

2) In web.xml create the record for servlet like
  <servlet>
        <servlet-name>initjs</servlet-name>
        <jsp-file>/init.jsp</jsp-file>
    </servlet>

and create servlet-mapping like this:
<servlet-mapping>
        <servlet-name>initjs</servlet-name>
        <url-pattern>/init.js</url-pattern>
    </servlet-mapping>


Deploy your application and access you jsp as if it were js file: /init.js. You will see your javascript file generated by servlet container.

Комментариев нет:

Отправить комментарий