At the time of writing I couldn’t find an easy way to automate Javascript obfuscation when building a Maven project. Using the Googles Closure compiler I decided to work on my own concept. This guide shows how you can incorporate the same process into your maven projects.
EDIT: wro4j is a plugin that makes use of the Closure compiler however it only allows for SIMPLE_CUSTOMIZATIONS level obfuscation.
Firstly, you need to include the Exec-Maven. This plugin allows you to execute Java applications during your build process. Include this plugin in your maven pom.xml like so:
Notice the configuration of the plugin. Firstly we are targeting the goal ‘java’. I shall discuss this later. Secondly, we define a main class. This is the Java application the plugin will run. Finally we have the arguments, these are the arguments that will be passed to the ‘public static void main(String[] args)’ method. In the example above we pass the input file and the location/name of the output file.
Now for the ‘JavascriptObfuscator’ class. This class communicates with the Closure Compiler API passing in the raw Javascript from the input file – asking for the obfuscated version from the API and then saving the output to the specified output file.
The class *must* have at least two arguments – the input and output file – however you can pass further arguments which allow you to customise the Closure compiler obfuscation.
I have been working with Spring-JS for a while now and have noticed that there doesn’t seem to be too many examples out there. This tutorial should hopefully address one common usage of Spring JS and its Ajax simplifications.
One common use of any Ajax framework is to have a page list a number of items. Then allow the user to add to those items. When adding an item a popup is displayed asking for the item details. Upon saving the item the popup is closed and the list underneath is refreshed. All actions working through Ajax and without changing page.
As a flow this would be:
User clicks to list items
User clicks to add items
Popup displayed asking for new item details
User clicks save within popup
If new details passes validation
List of items refreshed and popup closed
Getting hold of the sample code
I have hosted the completed project on GitHub. So please feel free to clone the repository @ git://github.com/eggsy84/SpringPopupRefreshList.git
Also if anyone has any contributions to add to the project please drop me an email or submit a request via GitHub for write access. The GitHub page is https://github.com/eggsy84/SpringPopupRefreshList. You can also download the project from this site. The rest of the tutorial will continue assuming you have grabbed the source code.
The servlet XML
We firstly need to configure our Spring MVC through the servlet-context.xml file. For Spring-JS and partial rendering to work we define the use of Apache Tiles as our view resolving mechanism. We can do this by simply configuring a few beans:
<!-- Enables the Spring MVC @Controller programming model --><annotation-driven/><context:component-scanbase-package="uk.co.eggsylife.controller"/>
We’re informing Spring to scan the ‘uk.co.eggsylife.controller’ package. The complete servlet-context.xml can be seen online.
The configuration XML
For the purpose of this tutorial, the application lists students and allows the user to add students. The ‘students’ bean acts as an in-memory database that is added to at runtime. It is a simple Java ArrayList of Student model objects. Typically you will have your own model objects and different CRUD operations on those objects.
Within the application when a Student is added we also validate the details entered. A simple Student Validator is created and referenced from the configuration XML.
Finally we tell Spring the location of our ValidationMessages message properties file. If the user enter any details incorrectly we can raise an error for the field entered and specify a message code for the error. Spring will then look up that message code from the ValidationMessages.properties file
Earlier in the tutorial we referenced the location of the Tile definitions, ‘/WEB-INF/tile-defs/tile-defs.xml’. This file declares all the views the web application uses and is crucial to making Spring JS and partial rendering function correctly.
Firstly we define an overall template that can be be used for any views our application requires. Declaring a template allows you to re-use the styling across multiple views.
The ‘template.jsp’ file is pretty basic. It simple declares the HTML headers. Each time we change the ‘content’ of this Tile definition it will continue to be surrounded by the markup on the template.jsp.
This means that every page will have the title set as above and every page will have the ‘Spring Edit…..’ paragraph present. Also note we are including the various Spring required Javascript files. By default they are located in the /resources/ folder of the web application. They are required in order to make Spring-JS Ajax functions work.
In this example I have also included the Dojo Tundra theme to improve the look and feel of the sample application but this is by no means required.
The tutorial only has one screen which lists students and should look similar to figure 1.
Figure 1
This screen simply lists the students and provides a link for the user to add a new student. When a new student is added we don’t navigate away from the page we simply append the student to the bottom of the list.
We firstly declare the overall ‘students.view’ which extends our default template as mentioned earlier. This view is actually a template itself and requires two entries – a list of students and a student edit dialog. The ‘students.jsp’ file is as follows:
<%@ include file="/WEB-INF/pages/include.jsp" %>
<tiles:insertAttribute name="studentsList" />
<tiles:insertAttribute name="studentEditDialog" />
The ‘students.jsp’ doesn’t contain much other than the inclusion of the two areas of content. ‘studentList’ and ‘studentEditDialog’. First of all lets look at the ‘studentList.jsp’ file which we inject into the ‘studentsList’ attribute.
The view simply lists each student in a table and provides a link to be able to add students. There are two main things to note on this JSP. Firstly notice that it is wrapped in a ‘DIV’ element with the same id as the tiles attribute defintion, ‘studentsList’. This is crucial to making Spring partial refresh work. Also note the way in which we ‘decorate’ the ‘Create new student’ link with Spring Javascript.
Firstly we declare the ‘dojo.addOnLoad’ function. This means that this piece of Javascript will execute when the page loads. Next we use the ‘Spring.addDecoration’ method to add the Ajax decorations. This function takes a number of parameters. Firstly the ‘elementId’ This is the id of the element that we attach the decoration to. In this case we are attaching the decoration to the ‘Create new student’ link. The event is then specified. We want the Ajax actions to run when the link is clicked so we specify the ‘onclick’ event. Next we set the ‘popup’ variable to ‘true’. This means that whatever the response is we want it rendered as a popup dialog.
The final parameter is ‘fragments’. This identifies which areas of content we want refresh. We state that we want both the ‘studentsList’ and the ‘studentEditDialog’ updated. Notice the names match our tiles attributes and that we wrap the ‘studentsList.jsp’ in a DIV with the id of ‘studentsList’. This way Spring knows how to identify content and replace it.
Now lets look at the ‘studentEditDialog’ content. In this instance we are injecting a utility JSP file that closes any open dialogs. The JSP is basically a bit of Javascript that closes any open Dojo popup dialogs. When first listing the students it is not particularly useful as we haven’t got any open dialogs. However when we save a new student a redirect to the students list view the JSP’s use will become clear.
<!-- This is a utility JSP that closes any Dojo Modal dialogs -->
<script type="text/javscript">
dojo.query(".dijitDialog").forEach(function(element) {
dijit.byId(element.id).hide();
});
</script>
The last tile definition is the view that contains our full student edit dialog. The dialog allows users to create a new student, asking for the student name and id number.
The only difference with this definition is the that we switch out the ‘dialogClose.jsp’ with the actual student edit dialog. The student edit dialog is as follows:
Again, notice we wrap the content in a DIV element with the same id as our tiles attribute, ‘studentEditDialog’. We then go on to declare a Spring form. For now I won’t go on to discuss the Spring MVC and form bindings. Finally note we attach the Spring decorations again. The only difference is this time we specify a form id and remove the popup attribute. We attach the code to the ‘Save student’ button which is the submit button for the ‘studentForm’. This means that we want our Ajax events to be actioned when the form is submitted.
The tutorial only has one controller. The ‘StudentController’ handles the three primary functions of the application. It handles the showing of the students list (GET), the showing of the edit dialog (GET) and the adding of a student (POST).
The list of students is handled by the ‘showStudentsList’ method.
It simply adds our list of students to the view and returns the ‘students.view’ tile definition. The list of students is Autowired from our Spring app-config file as defined earlier. It is wired to handle the URL ‘/students’.
Secondly there is the ‘showStudentEditForm’ method. This handles the URL ‘/students/edit’ and is called when the user clicks the ‘Create new student’ link.
privatestaticfinalString STUDENT_EDIT_DIALOG_VIEW_KEY ="studentsListAndEditDialog.view";
@RequestMapping(value="/students/edit", method=RequestMethod.GET)publicString showStudentEditForm(ModelMap modelMap){// Object class will be used as our// form backing object
Student student =new Student();
modelMap.addAttribute("student", student);return STUDENT_EDIT_DIALOG_VIEW_KEY;}
It returns the ‘studentsListAndEditDialog.view’ and adds a new ‘Student’ object to the view for our form. This object is used as the form backing object. The Student object is a POJO and will be seen later. Finally we have the ‘saveStudentEdit’ method that is actioned when the form is submitted. If the form is submitted without errors then it simply returns the same view as the listing of the students. If the user submits the form and it contains errors then it returns the edit form view with details of the error.
Notice if the form doesn’t have errors we add the student object back into the collection of students and update the list of students in the view. This is important so that the list of students is updated with the student that has just been added. The utility JSP that closes any open Dojo modal dialogs now comes into full use as it makes sure that the edit student dialog is closed after a student has been successfully added. The method responds to the POST request method so it is actioned when our form is ‘POSTED’. The complete StudentController includes all the above methods.
The Validator and Student POJO
To wrap things up the final two Java classes the application uses is the StudentValidator and the POJO Student object.
The validator simply checks that the user has entered both a first name and last name. The Student object encapsulates items a student has.
That should have gave you a complete example on how to use Spring-JS alongside Spring MVC and perform partial refresh of the content. The key to understanding the tutorial is understanding the tie between between the tiles defintions, the identified DIV elements and the usage of Javascript to link the two together.
The project can be downloaded as a Zip from GitHub. For those familiar with Git you can also get the project from the Git Repository under the URL ‘git://github.com/eggsy84/SpringPopupRefreshList.git’. If anyone would like to comment or have anything to contribute to the codebase please let me know.