Sunday, July 24, 2011

Struts 2 Hello world Example

Hello World Appliction

In this tutorial, we will explain you how to create a simpler Struts 2 application and what are configurations are required before start your application. First we have to follow some fundamental configuration for Struts 2 application. The type of configuration is known as Declarative Architecture.

Declarative architecture is a specialized type of configuration that allows a developer to create an application’s architecture through description rather than programmatic intervention. The developer describes the architectural components in high level artifacts, such as XML files or Java annotations, from which the system will create the run time instance of the application.

Two mechanisms for declaring your architecture
1. XML based declaration architecture
2. Java Annotation based declaration architecture

Lets start with XML architecture :-
The following files are needed for this application.

  1. web.xml
  2. struts.xml
  3. HelloWorld.java
  4. index.jsp
  5. success.jsp
  6. error.jsp

The following picture shows the directory structure of the Hello World application.

















Open your eclipse, create a new Dynamic Web Project with name Struts2HelloWorld




















click on the finish button, Now press Ctrl + R and type web.xml
In the web.xml, use the code of figure in your workspace file

web.xml












struts.xml






HelloWorld.java








index.jsp










success.jsp








error.jsp





Saturday, July 23, 2011

Introduction to Struts 2 Framework

Firstly I will tell you about framework, What exactly it is? A web application framework is a piece of structural software that provides automation of common tasks of the domain as well as providing a built in architectural solution that can be easily inherited by applications implemented on the framework.

The Struts 2 Framework

Struts 2 is a new release of the older Struts1 web application framework. It is a completely new framework, based on the architecturally esteemed WebWork framework. Struts 2 is a second generation web application framework that implements the Model-View-Controller (MVC) design pattern. From the previous version of struts now we have certainly new things to learn, interceptors & OGNL (Object-Graph Navigation Language) in particular. The whole point of design patterns such as MVC is the reuse of solutions to common problems. Reusing solutions at the architectural level provides an easy transferal of experience and knowledge.

The MVC Pattern


The MVC pattern provides a separation of concerns that applies well to the domain of web applications. Separation of concerns allows us to manage the complexity of large software systems by dividing them into high level components. The MVC design pattern identifies three distinct concerns: model, view and controller. In Struts 2 these concerns are implemented by the action, result and FilterDispatcher, respectively.

How Struts 2 Works

The framework has more than just its MVC components. Struts 2 provides a cleaner implementation of MVC. These clean lines are only possible with the help of a few other key architectural components that participate in the processing of each and every request. The most important are Interceptor, OGNL and the ValueStack. In Struts 2, FilterDispatcher has already done its controller work. In this, framework has already selected an action and has initiated the invocation process. This workflow in this figure is simply flows the MVC. An action has been selected by the controller, it will execute, and then select the appropriate result. The rest of the stuff mostly serves to make that basic MVC workflow cleaner. In Struts 2 framework, interceptor is the component that execute both before and after the rest of the request processing. Interceptors provide an architectural component in which to define various workflow and other crosscutting tasks so that they can be easily reused as well as separated from other architectural concerns.
In the framework,ValueStack is simply a storage area that holds all of the application domain data associated with the processing of a request. and last one OGNL, is a powerful expression language that allows you to reference and manipulate the data on the ValueStack.

Monday, July 18, 2011

Working with MyBatis 3

The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.

To use the MyBatis data mapper, you rely on your own objects, XML, and SQL. There is little to learn that you don't already know. With the MyBatis data mapper, you have the full power of both SQL and stored procedures at your fingertips.

The MyBatis project is developed and maintained by a team that includes the original creators of the "iBATIS" data mapper.

In this section we will download MyBatis, required JdbC driver jar, create new project in Eclipse IDE and then write some code to get member detail from a member table in database. We will finally run the application in the Eclipse IDE.

In this section you will learn how to download, create a new project in Eclipse IDE, add required jars files , the write simple program. Finally we will test the example code in Eclipse IDE.

Step 1:

Download all the required jars to run a simple MyBatis application
http://www.mediafire.com/?cnpr0nfwa45vr

Step 2:
Now we will create a new project in Eclipse IDE and then add the library files.

Click next. Give any name to the project, say "myBatisDummy" and then click on the "Finish" button.

Eclipse will create a new project.

Step 3:

Create a new folder "lib" in the project space to hold the myBatis 3 required libraries. Right click on the "myBatisDummy" in the project explorer and then select new folder option as shown below:


Then in the next screen enter "lib" next to the "Folder name" text field and click on the "Finish" button.
Step 4:
Now we will add the mybatis 3 libraries to the project. Select all the jars and then copy all the jar files (Ctrl+C) and paste on the lib directory (of our project) in the Eclipse IDE.

Step 5:
Now add all the libraries to "Java Build Path". Right click on the "myBatisDummy" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.
Step 6:
Create a new package to the src folder named as com.vaibhav.mybatis.xml to hold the xml files. Right click on the src folder of "myBatisDummy" project and then select New --> Package. Then provide the package name as com.vaibahv.mybatis.xml and click on the "Finish" button. Add two more packages in the same src folder named as
  • com.vaibhav.mybatis.action
  • com.vaibhav.mybatis.dao
Step 7:

now add batisConfig.xml file to the package com.vaibhav.mybatis.xml. This is the file which contain the required information to connect with the database and all the mapper.xml entries too.

xml version="1.0" encoding="UTF-8" ?>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver" />
<property name="url" value="url of your database?autoReconnect=true&characterEncoding=UTF-8" />
<property name="username" value="username of db" />
<property name="password" value="password of db" />
dataSource>
environment>
environments>
configuration>


In the above xml file, you have to provide properties like driver of your database, the URL of your database and username password.

Step 8:
Now add another xml file to the com.vaibhav.mybatis.xml package named as demoMapper.xml
which contains the query part of mybatis.

xml version="1.0" encoding="UTF-8" ?>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vaibhav.mybatis.dao.DemoMapper">
<select id="selectMember" parameterType="int" resultType="Member">
select * from Member where MemberId = #{id}
select>
mapper>
Step 9:
Now create an POJO java class which will use as a return type of the query written in xml file or Mapper class.
Create Member.java (as we are having a member table in database, this class name could be anything).

/*
* Copyright 2011 http://java-easy-tutorial.blogspot.com/
*/
package com.vaibhav.mybatis.dao;
/**
* POJO class (refer to a Pojo to Member Table)
*
* @author Vaibhav Bansal
*/
public class Member {
private int gender;
private String firstName;
private String lastName;
private String email1;
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public String getEmail1() {
return email1;
}
public void setEmail1(String email1) {
this.email1 = email1;
}
}
Step 10:
Create an Interface DemoMapper.java in com.vaibhav.mybatis.dao package.
If you want to write query part in xml file then this would be an empty interface but if you would like to do your query part in a java file then this is the class in which you will write your db related queries.

package com.vaibhav.mybatis.dao;
import org.apache.ibatis.annotations.Select;
/**
* @author Vaibhav Bansal
* Mapper interface. where we would write our query and create function
*/
public interface DemoMapper {
@Select("SELECT * FROM Member WHERE MemberID = #{id}")
Member selectMember(int id);// creating a function selectMember which takes an int param and return member. query for this function is written just above the method by @select annotation
}

Step 11:

Now create an action class in com.vaibhav.mybatis.action package named as MyBatisAction.java.
This class would contain the main method to run the project and from here we will call the function defined in either DemoMapper.java or demoMapper.xml to retrieve the data from database.

package com.vaibhav.mybatis.action;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.vaibhav.mybatis.dao.DemoMapper;
import com.vaibhav.mybatis.dao.Member;
public class MyBatisAction {
public static void main(String args[]) {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();// getting the sqlSessionFactory object
// add mappers here
// if you are using .java way to write query then we have to add the Mapper class(the class in which we will write our query) to sqlSessionFactory configuration
sqlSessionFactory.getConfiguration().addMapper(DemoMapper.class);
SqlSession session = sqlSessionFactory.openSession();// open the session
try {
DemoMapper mapper = session.getMapper(DemoMapper.class);// creating a DemoMapper object through session
Member member = mapper.selectMember(123);// calling function defined in DemoMapper class to get the Member data
System.out.println(member.getFirstName());// print member first name
} finally {
session.close(); // session closed
}
}
/** Function to create connection with database and to read the xml files used for mapping.
*/
public static SqlSessionFactory getSqlSessionFactory() {
SqlSessionFactory sqlSessionFactory = null;
try {
String resource = "com/vaibhav/mybatis/xml/batisConfig.xml";// path of the mybatis configuration file.
Reader reader = Resources.getResourceAsReader(resource);// read the mybatis confiuguration xml file
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); //getting the sqlSessionFactory obj
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return sqlSessionFactory;
}
}

Above class will create a sqlsession by the help of batisConfig.xml file and then call the function defined to retrieve the data from database. Please read the comment for more details.

Step 12:

All the configuration of your project are done and now you are able to launch your project.
To run the code in Eclipse open MyBatisAction.java in the editor and then right click and select Run as --> Java Application. This execute the Spring3HelloWorldTest.java file and following output will be displayed in the console.

You can even download the complete project from the link below :
http://www.mediafire.com/?3i78b0m98n9sti9

Please Post comment if you require any

Friday, July 15, 2011

Installing Tomcat 6.0 in Eclipse.

Apache Tomcat (or Jakarta Tomcat or simply Tomcat) is an open source servlet container developed by the Apache Software Foundation (ASF). Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a "pure Java" HTTP web server environment for Java code to run.
Tomcat should not be confused with the Apache web server, which is a C implementation of an HTTP web server; these two web servers are not bundled together. Apache Tomcat includes tools for configuration and management, but can also be configured by editing XML configuration files.

Here is a downloadable link for Tomcat 6.0.32 Version:

after downloading tomcat you have to install your server to your eclipse.

Steps to install tomcat in Eclipse:

Step 1:
In Eclipse Go to Windows Tab>ShowView>Servers
Step 2:
After opening Servers view> right click in servers view> choose new> Server
Step 3:
Select Apache> Tomcat v6.0 Server>Press Next>
Step 4:
Then browse Tomcat installation directory(place where you downloaded your tomcat server )
Step 5:
Press Finish

yeah! your server is now installed in Eclipse. Now you are able to create and run web application :)