Wednesday, January 28, 2009

Java First Moment of a Day

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);

Java First Moment of a Month

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);

Java First Moment of a Year

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);

Java First Moment of a Week

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);

Monday, January 12, 2009

Spring, Velocity and Dropdown List

Here is how I put a dropdown list, e.g. groups, on one of my Spring, Velocity web applications.

First, the key word is springFormSingleSelect. In my velocity file, I wrote

#springFormSingleSelect("command.group", ${groups}, "style='width:270px;'")

Second, use referenceData to populate values in the "groups" in the Controller class.

referenceData(...) {
Map model ...
... add (key, value) into a Map called groups
model.put("groups", groups);
return model;
}

Third, create a custom property editor, GroupEditor extends PropertyEditorSupport and override the setAsText method.

Note the Spring Framework will pass you the groupId and you need to create a Group object from the groupId, then call setValue(group).

Fourth, register the GroupEditor in the initBinder method.

binder.registerCustomerEditor(Group.class, new GroupEditor());

You may find the groups data will disappear after onSubmit. Don't worry, there is an easy fix. Instead of return a new ModelAndView, return showForm(request, response, errors, model). You can put whatever you need into the "model".

I spent a full weekend to sort everything out. Hope it can help you.