Question

I am developing a webpage in JSP which uses a big ammount of dynamically generated JavaScript code from a Java backend class. It is about Google Maps and a JS library called MarkerClusterer.

Currently this class is generating the JavaScript code by handling Strings in Java and printing it directly into the JSP page, but it's getting a little bit complicated to write JS within Java String and maintain that.

The JavaScript requires a lot of modifications all the time, as this class is being used in different projects. Ideally I would like to package this in a way it could be used as a library, not requiring further modifications, so that's the question, what is the best way to do that?

Here's a part of the code:

public class JavascriptGenerator {

    public String gerarPorRegiao(String contextPath, List<Endereco> lista, boolean infoWindowEnabled) {
        String saida = "";

        saida += "<script type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?sensor=false\"></script>"
                + "<script type=\"text/javascript\" src=\""
                + contextPath
                + "/js/markerclusterer.js\"></script>"
                + "<script type=\"text/javascript\">"
                + "var map;";
        for(Estado e: Estado.values()) {
            saida += "var mc" + e.toString() + ";";
        }
                saida += "var selecionado;"
                + "var center = new google.maps.LatLng(-11.0, -51.9);"
                + "var geocoder = new google.maps.Geocoder();"
                + "var infowindow = new google.maps.InfoWindow();"
                + "var markerContent = new Array();"
                + "function geocoderInit() {"
...
Was it helpful?

Solution

I would say: don't.

Don't generate javascript dynamically. It will be a nightmare to maintain. Keep your js in a static file, and use ajax to fetch your data. Your data can be in the form of JSON. JSON can be auto-generated from an object hierarchy using one of many JSON libs you can download.

OTHER TIPS

one thing you can do is , use a string buffer and add all you java script stuff into it. Then write it a file with .js as extension. so, this makes your script maintainable

You could write a separate JSP file that creates the javascript. Then all static parts of the Javascript would be as usual:

var map;

<% for(Estado e: Eastado.values()) { %>
var mc<%=e.toString()%>;
<% } %>

var selecionado;
...

This JSP can then be loaded by the HTML page your other JSP creates:

<script type="text/JavaScript" src="path/to/jsp/file.jsp"></script>

If your script needs access to data, you could pass parameters via URL:

<script type="text/JavaScript" src="path/to/jsp/file.jsp?id=15"></script>

Then, in the script, in a filter or anything similar, you can directly use these parameters or use them to load data from a database or so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top