Search

Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Java Performance and best coding Tips

1.        Try, catch block should not be in loop (unless specifically required).

2.     All Collection API Classes should be specifically reinitialized to null (since JVM has to specifically do it & GC spends much time in doing these functions).

3.        Release JDBC resources when done with tasks.

4.        Use inner join instead of multiple queries.

5.        Optimize SQL queries.

6.        Always use Dynamic SQL (Prepare Statement) rather than the static SQL like Statement.

7.        Try to avoid repeated DB calls to retrieve the same data. Instead of that retrieve the data from the table and keep the data in Java objects and use that in the subsequent call. (make Model class for that and use getter, setter methods)

8.        Avoid Select * instead give the names of fields to be selected in query (e.g. Select id,name from Student).
9.        Using getXX(int ColumnIndex) instead of getXX(String columnName): Depending upon the no of columns in your resultSet, a getXX field operation using column Index is two times as fast as than using Column Name.

10.     Do not use Vectors, instead of that use Collection classes like ArrayList.

11.     Avoid using method call as loop termination test. E.g. Don’t use list.size(), instead use store that in a temporary variable and then use the temporary variable for testing loop termination test.

12.     Avoid throwing Exception in normal flow of execution since try-catch-finally block is costly.

13.     Build proper WHERE clause in SQL SELECT for database indexing. (In left of Join select table with less no of records).

14.     Try using java Collection classes instead of array.

15.     String Concatenation: Check that For String concatenation use StringBuilder (JDK 1.5 has StringBuilder over StringBuffer) instead of String ‘+’ operator.

16.     Debugging Statements: Do not use System.out.println or printstackTrace(). Use log4j.debug() for debugging. In catch blocks add log4.error() wherever applicable.

17.     Prepare Statement: Use prepared statement for retrieving data when we have parameterized queries(insert, update, delete) else use statements.

18.     Avoid object instantiation inside Loop. If possible create object outside loop and reuse the same object inside the loop.

19.     Minimize object lifetimes. Keep the lifetimes of your data as short as possible. Place the declaration in the most nested block that first uses the data. If operator new is used, do the new just before the first use, and the set the reference to null just after the last use.

20.     Minimum use of Session variables in the code instead set variables in Request. Set session variables as null after use.

21.     The constants are not static we can make it final for better performance(e.g. if we have fix value for variable than make it final private void testMethod(final int id){}).

22.     Apply Transactions wherever necessary.

23.     Apply Query Caching if is required as per functionality.

24.     Minimize data conversions or Castings

25.     Try to use primitive java objects instead Wrapper classes as like Wrapper classes (i.e. Integer) allocate large data amounts in memory.

26.     Replace a long if-else-if chain by a switch if possible; this is much faster.

27.     Declaring a method as private, final, or static makes calls to it faster. Of course, you should only do this when it makes sense in the application.

28.     Do not add JavaScript directly in the JSP Code; instead include JS File and include in Jsp (e.g <script src=”include/common.js”></script>).

29.     Use STRUTS, JSTL specific UI Tag Library in JSP pages.

30.     Exceptions are taken care in the code and highest levels of Exceptions are routed to Error Page; others are properly logged using logger.


Spring Annotations Tutorial / Example

In this example you will see how to populate a form using Spring annotations. The annotated user controller class is shown below.
package com.vaannila.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.vaannila.domain.Community;
import com.vaannila.domain.Country;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;

@Controller
@RequestMapping("/userRegistration.htm")
@SessionAttributes("user")
public class UserController {

private UserService userService;

@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}

@ModelAttribute("countryList")
public List<Country> populateCountryList() {
return userService.getAllCountries();
}

@ModelAttribute("communityList")
public List<Community> populateCommunityList() {
return userService.getAllCommunities();
}

@RequestMapping(method = RequestMethod.GET)
public String showUserForm(ModelMap model) {
User user = new User();
model.addAttribute("user", user);
return "userForm";
}

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("user") User user) {
userService.add(user);
return "redirect:userSuccess.htm";
}

}
The populateCountryList() and populateCommunityList() methods are used to populate the country and community list respectively. The @ModelAttribute annotation when used at the method level is used to indicate that the method contain reference data used by the model, so it should be called before the form is loaded. This is similar to overriding the referenceData() method when extending theSimpleFormController.
You can also do this in the showUserForm() method like this.
@RequestMapping(method = RequestMethod.GET)
public String showUserForm(ModelMap model) {
User user = new User();
model.addAttribute(userService.getAllCountries());
model.addAttribute(userService.getAllCommunities());
model.addAttribute("user", user);
return "userForm";
}
Since we use ModelMap here by default the names of the list will be countryList and communityList.

Struts Export WorkBook to Excel Tutorial

In this example we will see how to export a WorkBook to Excel. ExcelCreator class is used to create the HSSFWorkbook. The ExcelCreator class contains the following code.
01.public class ExcelCreator {
02. 
03.public HSSFWorkbook createWorkbook(ArrayList userList) throws Exception {
04. 
05.HSSFWorkbook wb = new HSSFWorkbook();
06.HSSFSheet sheet = wb.createSheet("User Data");
07. 
08./**
09.* Setting the width of the first three columns.
10.*/
11.sheet.setColumnWidth(03500);
12.sheet.setColumnWidth(17500);
13.sheet.setColumnWidth(25000);
14. 
15./**
16.* Style for the header cells.
17.*/
18.HSSFCellStyle headerCellStyle = wb.createCellStyle();
19.HSSFFont boldFont = wb.createFont();
20.boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
21.headerCellStyle.setFont(boldFont);
22. 
23.HSSFRow row = sheet.createRow(0);
24.HSSFCell cell = row.createCell(0);
25.cell.setCellStyle(headerCellStyle);
26.cell.setCellValue(new HSSFRichTextString("User Name"));
27.cell = row.createCell(1);
28.cell.setCellStyle(headerCellStyle);
29.cell.setCellValue(new HSSFRichTextString("Email Id"));
30.cell = row.createCell(2);
31.cell.setCellStyle(headerCellStyle);
32.cell.setCellValue(new HSSFRichTextString("Location"));
33. 
34.for (int index = 1; index < userList.size(); index++) {
35.row = sheet.createRow(index);
36.cell = row.createCell(0);
37.UserData userData = (UserData) userList.get(index);
38.HSSFRichTextString userName = newHSSFRichTextString(userData.getUserName());
39.cell.setCellValue(userName);
40.cell = row.createCell(1);
41.HSSFRichTextString emailId = newHSSFRichTextString(userData.getEmailId());
42.cell.setCellValue(emailId);
43.cell = row.createCell(2);
44.HSSFRichTextString location = newHSSFRichTextString(userData.getLocation());
45.cell.setCellValue(location);
46.}
47.return wb;
48.}
49.}
The ExcelCreator class contains the createWorkbook method which takes an ArrayList as the argument and returns a HSSFWorkbook .The ArrayList contains a list of UserData. The ArrayList is iterated using a for loop and each row in the excel is created.
In our example the UserAction class extends DispatchAction. The UserAction class contains an exportExcel method, which is used to export the workbook to excel. The UserAction class contains the following code.
01.public class UserAction extends DispatchAction {
02. 
03.private final static String SUCCESS = "success";
04. 
05.public ActionForward populate(ActionMapping mapping, ActionForm form,
06.HttpServletRequest request, HttpServletResponse response)
07.throws Exception {
08.UserForm userForm = (UserForm) form;
09.UserData userData = new UserData();
10.userForm.setUserList(userData.loadData());
11.return mapping.findForward(SUCCESS);
12.}
13. 
14.public ActionForward exportExcel(ActionMapping mapping, ActionForm form,
15.HttpServletRequest request, HttpServletResponse response)
16.throws Exception {
17.UserForm userForm = (UserForm) form;
18.ExcelCreator excelCreator = new ExcelCreator();
19.HSSFWorkbook workbook = excelCreator.createWorkbook(userForm.getUserList());
20.response.setHeader("Content-Disposition""attachment; filename=UserDetails.xls");
21.ServletOutputStream out = response.getOutputStream();
22.workbook.write(out);
23.out.flush();
24.out.close();
25.return mapping.findForward(SUCCESS);
26.}
27.}
Run the example. The following user details will be displayed.

On clicking the Excel link the workbook is exported to excel. The following excel sheet will be displayed.