Showing posts with label servlet. Show all posts
Showing posts with label servlet. Show all posts

Saturday, 25 June 2011

Setting Tomcat Heap Size (JVM Heap) in Eclipse

Recently while running Tomcat under Eclipse for one of the web application I was getting Java Heap memory related error java.lang.OutOfMemoryError.
What needs to be done here basically is to increase the jvm heap size. So for increasing the JVM Heap Size of Tomcat in Eclipse we have to set few VM arguments of the tomcat.
Follow the simple steps to change the Heap Size of Tomcat under Eclipse.
1. Open the Server tab in Eclipse and double click the Tomcat server to open Server Configuration.
Double click on the Apache Tomcat under server.
2. In Server Configuration, click on the Launch Configuration link under General Information.

3. Under Arguments tab, add following values in VM arguments.
As you can see just add the VM arguments:

To know more about -Xm options read this article.

Tuesday, 21 June 2011

Database Connection Pooling in Tomcat using Eclipse

atabase Connection Pooling is a great technique used by lot of application servers to optimize the performance. Database Connection creation is a costly task thus it impacts the performance of application. Hence lot of application server creates a database connection pool which are pre initiated db connections that can be leverage to increase performance.
Apache Tomcat also provide a way of creating DB Connection Pool. Let us see an example to implement DB Connection Pooling in Apache Tomcat server. We will create a sample web application with a servlet that will get the db connection from tomcat db connection pool and fetch the data using a query. We will use Eclipse as our development environment. This is not a prerequisite i.e. you may want to use any IDE to create this example.

Step 1: Create Dynamic Web Project in Eclipse

Create a Dynamic Web Project in Eclipse by selecting:
File -> New -> Project… ->Dynamic Web Project.

Step 2: Create context.xml

Apache Tomcat allow the applications to define the resource used by the web application in a file called context.xml (from Tomcat 5.x version onwards). We will create a file context.xml under META-INF directory.

Copy following content in the context.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<Context>

<!-- Specify a JDBC datasource -->

<Resource name="jdbc/testdb" auth="Container"

type="javax.sql.DataSource" username="DB_USERNAME" password="DB_PASSWORD"

driverClassName="oracle.jdbc.driver.OracleDriver"

url="jdbc:oracle:thin:@xxx:1525:dbname"

maxActive="10" maxIdle="4" />



</Context>

In above code snippet, we have specify a database connection pool. The name of the resource is jdbc/testdb. We will use this name in our application to get the data connection. Also we specify db username and password and connection URL of database. Note that I am using Oracle as the database for this example. You may want to change this Driver class with any of other DB Providers (like MySQL Driver Class).

Step 3: Create Test Servlet and WEB xml entry

Create a file called TestServlet.java. I have created this file under package: com.vaani.servlet. Copy following code into it.

import java.io.IOException;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;

public class TestServlet extends HttpServlet {

private DataSource dataSource;

private Connection connection;

private Statement statement;

public void init() throws ServletException {

try {

// Get DataSource

Context initContext = new InitialContext();

Context envContext = (Context)initContext.lookup("java:/comp/env");

dataSource = (DataSource)envContext.lookup("jdbc/testdb");

} catch (NamingException e) {

e.printStackTrace();

}

}

public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

ResultSet resultSet = null;

try {

// Get Connection and Statement

connection = dataSource.getConnection();

statement = connection.createStatement();

String query = "SELECT * FROM STUDENT";

resultSet = statement.executeQuery(query);

while (resultSet.next()) {

System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3));

}

} catch (SQLException e) {

e.printStackTrace();

}finally {

try { if(null!=resultSet)resultSet.close();} catch (SQLException e)

{e.printStackTrace();}

try { if(null!=statement)statement.close();} catch (SQLException e)

{e.printStackTrace();}

try { if(null!=connection)connection.close();} catch (SQLException e)

{e.printStackTrace();}

}

}

}

In the above code we initiated the datasource using InitialContext lookup:

Context initContext  = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/testdb");

Create test servlet mapping in the web.xml file (deployment descriptor) of the web application. The web.xml file will look like:

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>TomcatConnectionPooling</display-name>

<welcome-file-list>

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

</welcome-file-list>

<servlet>

<servlet-name>TestServlet</servlet-name>

<servlet-class>

com.vaani.servlet.TestServlet

</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>TestServlet</servlet-name>

<url-pattern>/servlet/test</url-pattern>

</servlet-mapping>

</web-app>


Now Run the web application in Tomcat using Eclipse (Alt + Shift + X, R). You will be able to see the result of the query executed.

Thus this way we can create a database pool in Tomcat and get the connections from it.

Sunday, 8 May 2011

Spring can inject Servlets too!

In this article, I will show you that Spring dependency injection mechanism is not restricted solely to Spring-managed beans, that is Spring can inject its beans in objects created by the new keywords, servlets instantiated in the servlet container, and pretty anything you like. Spring classical mode is to be an object factory. That is, Spring creates anything in your application, using the provided constructor. Yet, some of the objects you use are outer Spring’s perimeter. Two simple examples:

  • servlets are instantiated by the servlet container. As such, they cannot be injected out-of-the-box
  • some business objects are not parameterized in Spring but rather created by your own code with the new keyword

Both these examples show you can’t delegate to Spring every object instantiation.

There was a time when I foolishly thought Spring was a closed container. Either your beans were managed by Spring, or they didn’t: if they were, you could inject them with other Spring-managed beans. If they weren’t, tough luck! Well, this is dead wrong. Spring can inject its beans into pretty much anything provided you’re okay to use AOP.

In order to do this, there are only 2 steps to take:

  • Use AOP
  • Configure object creation interception

Use AOP

It is done in your Spring configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>

<This does the magic />
<context:spring-configured />

<-- These are for classical annotation configuration -->
<context:annotation-config />
<context:component-scan base-package="com.vaani.spring.outcontainer" />

</beans>


You need also configure which aspect engine to use to weave the compiled bytecode. In this case, it is AspectJ, which is the AOP component used by Spring. Since i’m using Maven as my build tool of choice, this is easily done in my POM. Ant users will have to do it in their build.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd"
>
...
<properties>
<spring-version>2.5.6.SEC01</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<configuration>
<complianceLevel>1.5</complianceLevel>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

 


Configure which object creation to intercept


This is done with the @org.springframework.beans.factory.annotation.Configurable annotation on your injectable object.



@Configurable
public class DomainObject {

/** The object to be injected by Spring. */
private Injectable injectable;

public Injectable getInjectable() {

return injectable;
}

@Autowired
public void setInjectable(Injectable injectable) {

this.injectable = injectable;
}
}

Now with only these few lines of configuration (no code!), I’m able to inject Spring-managed beans into my domain object. I leave to you to implement the same with regular servlets (which are much harder to display as unit test).

You can find the Maven project used for this article here. The unit test packaged shows the process described above.

To go further: