Wednesday, June 22, 2011

Error instantiating servlet 'action'.


Error instantiating servlet 'action'. Servlet class org.apache.struts.action.ActionServlet not found

The error might mislead you to think that it is not able to find struts.jar and you might start struggling on finding why it is not able to find struts.jar. If you have started looking on this path, then just wait.... Lets make sure that the reason is missing struts.jar or something else?

This happened with me while working on my project, during a new deployment, i started getting this exception and three people of my team including me spent around 8 hours without any output and without being able to figure out the root cause of the problem.

Then I searched on internet and found a solution, which I thought is not worth devoting time and trying it out. But actually i was wrong. i could have saved 4-5 hours if I would have tried that option when I first found it.

The approach to tackle such an error is

The error message might be misleading in some cases. Let us verify whether it is correct. Can you try removing all servlet-class and servlet-mapping in your web.xml ? Then add a jsp that has

<% Class.forName("org.apache.struts.action.ActionServlet"); %>
   Class "org.apache.struts.action.ActionServlet" is loaded. 

deploy your application and access the jsp. Please tell me what happens.

In many cases, it will fail with an error message in the application.log of the enclosing application that shows the root cause: another missing class that is needed in order to loade the servlet class. To remove the problem, include the missing classes into your web application classpath.

Note : If you find missing ActionServlet.class then rather than jumping to conclusion that struts.jar is missing, just think about this possible way to find out the solution

Source : http://forums.oracle.com/forums/thread.jspa?messageID=1352351

Monday, June 20, 2011

NoClassDefFoundError Vs ClassNotFoundException

Source : http://javafanatics.blogspot.com/2007/03/noclassdeffounderror-vs.html


What..When...?


I always wonder, why Java is not intelligent enough to fix problems in the code when it knows something goes wrong; rather than throwing just exceptions? May be Gosling wants it that way, saving donuts for him!

Now read on...

  public class A{

  public static void main(String []s) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
    B obj = new B(); 
    // Class.forName("B").newInstance(); 
   }
 
  }

1 public class B{
2 }


javac A.java
java A

This would throw a NoClassDefFoundError. Comment out line 4 and uncomment line 5. Now it would throw ClassNotFoundException.

ClassNotFoundexception is thrown when an application tries to load in a class through its string name using:

The forName method in class Class.

The findSystemClass method in class ClassLoader .

The loadClass method in class ClassLoader.

Otherwise NoClassDefFoundError is thrown.

The interesting fact is that, this behaves differently when your application runs in OC4j Oracle application server. i.e. your application would throw a NoClassDefFoundError to ClassNotFoundException.

If you dont want to miss your donut, add two catch blocks in your code...I already missed one..:(

try{
   
   //...
   
    }catch(ClassNotFoundexception e1){
    }catch(NoClassDefFoundError e2){
   }

Sunday, June 19, 2011

Common pitfalls in JDBC Prepared Statement

DO NOT USE single quotes when using setString method.

Usually we tend to forget this when using like statement as in

select projectId from t_project where projectName like ?

// Setting the value
// The following is incorrect and will not work
pstmt.setString(1,"'%abc%'");

// This is correct
// Remember we are using setString method that will automatically add single quotes around it.
// The developer need not add it explicitly.
pstmt.setString(1, "%abc%");




Thursday, June 16, 2011

Best practices in JDBC Connection



JDBC Connection Scope

How should your application manage the life cycle of JDBC connections? Asked another way, this question really asks - what is the scope of the JDBC connection object within your application? Let's consider a servlet that performs JDBC access. One possibility is to define the connection with servlet scope as follows.

import java.sql.*;

public class JDBCServlet extends HttpServlet {

    private Connection connection;

    public void init(ServletConfig c) throws ServletException {
      //Open the connection here
    }

    public void destroy() {
     //Close the connection here
    }

    public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException { 
      //Use the connection here
      Statement stmt = connection.createStatement();
      //do JDBC work.
  }
}
Using this approach the servlet creates a JDBC connection when it is loaded and destroys it when it is unloaded. The doGet() method has immediate access to the connection since it has servlet scope. However the database connection is kept open for the entire lifetime of the servlet and that the database will have to retain an open connection for every user that is connected to your application. If your application supports a large number of concurrent users its scalability will be severely limited!

Method Scope Connections


To avoid the long life time of the JDBC connection in the above example we can change the connection to have method scope as follows.

public class JDBCServlet extends HttpServlet {

  private Connection getConnection() throws SQLException {
    // create a JDBC connection
  }

  public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException { 
    try {
      Connection connection = getConnection();
      //<do JDBC work>..
      connection.close();
    }
    catch (SQLException sqlException) {
      sqlException.printStackTrace();
    }
  }
}

This approach represents a significant improvement over our first example because now the connection's life time is reduced to the time it takes to execute doGet(). The number of connections to the back end database at any instant is reduced to the number of users who are concurrently executing doGet(). However this example will create and destroy a lot more connections than the first example and this could easily become a performance problem.

In order to retain the advantages of a method scoped connection but reduce the performance hit of creating and destroying a large number of connections we now utilize connection pooling to arrive at our finished example that illustrates the best practices of connecting pool usage.

import java.sql.*;
import javax.sql.*;

public class JDBCServlet extends HttpServlet {

  private DataSource datasource;

  public void init(ServletConfig config) throws ServletException {
    try {
      // Look up the JNDI data source only once at init time
      Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
      datasource = (DataSource) envCtx.lookup("jdbc/MyDataSource");
    }
    catch (NamingException e) {
      e.printStackTrace();
    }
  }

  private Connection getConnection() throws SQLException {
    return datasource.getConnection();
  }

  public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
    Connection connection=null;
    try {
      connection = getConnection();
      ....
    } 
    catch (SQLException sqlException) {
      sqlException.printStackTrace();
    }
    finally {
      if (connection != null) 
        try {connection.close();} catch (SQLException e) {}
      }
    }
  }
}
 

This approach uses the connection only for the minimum time the servlet requires it and also avoids creating and destroying a large number of physical database connections. The connection best practices that we have used are:

A JNDI datasource is used as a factory for connections. The JNDI datasource is instantiated only once in init() since JNDI lookup can also be slow. JNDI should be configured so that the bound datasource implements connecting pooling. Connections issued from the pooling datasource will be returned to the pool when closed.

We have moved the connection.close() into a finally block to ensure that the connection is closed even if an exception occurs during the doGet() JDBC processing. This practice is essential when using a connection pool. If a connection is not closed it will never be returned to the connection pool and become available for reuse. A finally block can also guarantee the closure of resources attached to JDBC statements and result sets when unexpected exceptions occur. Just call close() on these objects also.

For More details :
http://www.javaranch.com/journal/200601/JDBCConnectionPooling.html

Saturday, June 11, 2011

10 Java Regular Expression Examples You Should Know

Regular expression is an art of the programing, it’s hard to debug , learn and understand, but the powerful features are still attract many developers to code regular expression. Let’s explore the following 10 practical regular expression ~ enjoy

1. Username Regular Expression Pattern


^[a-z0-9_-]{3,15}$

For the remaining 9, please do visit :

10-java-regular-expression-examples-you-should-know

Dangling meta character '?' near index 0

Problem

String str = "testing??"; 

str = str.replaceAll("?", ""); 
// Please note that the problem is only with replaceAll and not with replace.
str = str.replace("?", "");


When you use the above pattern you get an exception as "Dangling meta character '?' near index 0"


Solution
String str = "testing??"; 

str = str.replaceAll("\\?", ""); 

You can use the above solution when you are replacing * and + symbols
String str = "testing??*+"; 

str = str.replaceAll("\\*", ""); //"Dangling meta character '*' near index 0" 
str = str.replaceAll("\\+", ""); //"Dangling meta character '+' near index 0"