Search

Showing posts with label Struts 2. Show all posts
Showing posts with label Struts 2. 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.


Struts 2 Annotation Example

We will learn annotations in struts 2 using the hello user example. In this example we will get the user name and display a welcome message to the user. There are two versions of this example, in the first one we will see how to do this by using the intelligent defaults provided by the struts 2 framework. We will not do any configuration in this example except the deployment descriptor.
The example is created using ecilpse. The war file of this example is also provided at the end of this tutorial so that you can try it yourself.
So lets start, you need to have the following jar files in the WEB-INF/lib directory.
commons-fileupload-1
commons-io-2
commons-logging-1
freemarker-13
junit-1
ognl-11
spring-test-6
struts2-convention-plugin-6
struts2-core-6
xwork-2
You can definitely save a lot of time by having the correct versions of these jar files in the lib directory. The struts2-convention-plugin-6 jar file is needed if your are using annotations.
This is the directory structure of the hello user example.
Now we will create the index page. This page is simple, we use the struts tags to create the page. Thetextfield tag is used to create the textfiled and the submit tag is used to create the submit button. The index.jsp page contains the following code.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 01 Transitional//EN" "http://www.worg/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<s:form action="welcome-user" >
<s:textfield name="userName" label="User Name" />
<s:submit />
</s:form>
</body>
</html>
Note the URL value of the action attribute in the form tag. In the end we will see how everything relates together.
We compose the welcome message in the execute() method of the WelcomeUser class and we return "success". The WelcomeUser class contains the following code.
package com.vaannila.action;

import com.opensymphony.xworkActionSupport;

public class WelcomeUser extends ActionSupport{
private String userName;
private String message;

public String execute() {
message = "Welcome " + userName;
return SUCCESS;
}

public void setUserName(String userName) {
this.userName = userName;
}

public void setMessage(String message) {
this.message = message;
}

public String getUserName() {
return userName;
}

public String getMessage() {
return message;
}
}
Note the class name, can you find any similarities between the action URL and the class name? if yes got the concept, if no don't worry you will learn what it is in the coming pages.
We display the welcome message to the user using the welcome-user.jsp page. The content of the page is very simple, we just display the message. The important thing to note here is the name of the page.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 01 Transitional//EN" "http://www.worg/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome User</title>
</head>
<body>

<h1>${message}</h1>

</body>
</html>
Now we will configure the web.xml for the struts 2 framework. We need to specify the filter and the filter mapping here. Except this there is no need to have any other XML configuration files.
<?xml version="0" encoding="UTF-8"?>

<display-name>Struts2Example1</display-name>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.strutsdispatcher.ng.filter. StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>
Now the coding part is complete. You can run the example by using the following URL "http://localhost:8080/Struts2Example1/"
Enter a user name and submit the form, you will see the following welcome-user.jsp page.
The example works fine. Now lets see how the example works.
The Convention plug-in is the one which does everything in the background. The Convention plug-in does the following things.
·         By default the Convention plug-in looks for the action classes inside the following packages strut, struts2, action or actions. Here our package name is com.vaannila.action. Any package that matches these names will be considered as the root package for the Convention plug-in.
·         The action class should either implement com.opensymphony.xworkAction interface or the name of the action class should end with Action. Here we extend our WelcomeUser class fromcom.opensymphony.xworkActionSupport which inturn implements com.opensymphony.xworkAction.
·         The Convention plug-in uses the action class name to map the action URL. Here our action class name is WelcomeUser and the URL is welcome-user. The plug-in converts the camel case class name to dashes to get the request URL.
·         Now the Convention plug-in knows which Action class to call for a particular request. The next step is to find which result to forward based on the return value of the execute method. By default the Convention plug-in will look for result pages in WEB-INF/content directory.
·         Now the Convention plug-in knows where to look for results, but it doesn't know which file to display inside the content directory. The Convention plug-in finds this with the help of the result code returned by the Action class. If "success" is returned then the Convention plug-in will look for a file name welcome-user-success.jsp or welcome-user.jsp . It need not be a jsp file it can be even a velocity or freemaker files. If the result value is "input" it will look for a file name welcome-user-input.jsp or welcome-user-input.vm or welcome-user-input.ftl.

Download Struts 2 all examples source code