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() {"
...
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.