RSS

Category Archives: Sample Project in ECLIPSE

Sample Projects in Eclipse

A)Create Web-Project(Eclipse,Tomcat&Database)

Dynamic Web Project is used to develop, debug and deploy dynamic web applications in eclipse. For this project

1.you need to have Eclipse IDE for Java EE developers which can be downloaded from here.

2.Download Tomcat 5.5 from here http://tomcat.apache.org/download-55.cgi and install.

Steps to create Dynamic Web Project in Eclipse  Helios. Step 1: Launch Dynamic Web Project Wizard.

  • If you are in the Java EE perspective then you can simply do it form File menu by going to File -> New -> Dynamic Web Project
  • If you are in any other perspective and there is no direct option in File menu to create Dynamic Web Project then go to File -> New -> Project that will launch project selection wizard.
  • In this wizard select Dynamic Web Project under Web category and Click Next.
  • That will show the Dynamic Web Project wizard as follows:
  • Enter the Project Name “SampleWebProject“.
  • Select the Target Runtime from the list if does not exist then add new target runtime by clicking New Runtime… button. Here from the list of the list of Runtime select your server’s runtime e.g. I selected Apache Tomcat v5.5
  • Click next to specify the server configuration, where you can specify the name, location and JRE for the server runtime and click on Finish button
  • Now you will come back to first page of the Dynamic Web Project wizard. Here select Dynamic Web module version  to 2.4 or higher and leave all the other parameters as default values though you can change them as per your need
  •  Click on the Next button to configure source location and Default output folder similar to Java Project
  • By default source location would be src change that to WebContent/WEB-INF/src and by default the Default output folder would be build/classes change that to WebContent/WEB-INF/classes
  • Then click on Next button to configure Web Module for Dynamic Web Project. Here you can configure Context root, Context Directory and select check box to Generate web.xml deployment descriptor
  • Now hit the finish button and Dynamic Web Project gets created with following structure.
  • And the auto generated web.xml looks as follows:
  • Create a jsp as  Rightclick on WebContent ->New->JSP File
  • Type “mypge” in File name:
  • Then Click Next->Finish
  • Right Click on WebContent/WEB-INF/src Create a Package “dbconnection” inside WebContent/WEB-INF/src folder and then click Finish

  • Right Click on dbconnection folder ->New-Class
  • Type MyDBConnection in Name then Finish.

  • In MyDBConnection class file write a method getLocalConnection for database connection.
  • package dbconnection;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class MyDBConnection{
    Connection con = null;
    public Connection getLocalConnection()
    //for oracle
    {
    try
    {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:XE”,”mydb”,”mydb”);
    }
    catch (ClassNotFoundException e)
    {
    System.err.println(“ClassNotFoundException in getConnection, ” + e.getMessage());
    }
    catch (SQLException e)
    {
    System.err.println(“SQLException in getConnection, ” + e.getMessage());
    }
    return con;
    }
    //for mysql
    /*{
    try
    {
    Class.forName(“com.mysql.jdbc.Driver”);
    con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/XE”,”mydb”,”mydb”);
    }
    catch (ClassNotFoundException e)
    {
    System.err.println(“ClassNotFoundException in getConnection, ” + e.getMessage());
    }
    catch (SQLException e)
    {
    System.err.println(“SQLException in getConnection, ” + e.getMessage());
    }
    return con;
    }*/
    public void setConnectionClose() throws SQLException
    {
    con.close();
    }
    }
  • If you are using oracle then copy ojdbc.14.jar file from oracle installed lib folder for example:  C:oraclexeapporacleproduct10.2.0serverjdbclib and paste in to tomcat installed lib folder for example: C:Program FilesApache Software FoundationTomcat 5.5commonlib folder
  • Right Click on SampleWebProject ->Properties->Java Build Path    ->Libraries Tab->Add External JARs

  • Then browse ojdb14.jar file ->Ok.
  • Then write
    <%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
    pageEncoding=”ISO-8859-1″ import=”java.sql.*,dbconnection.*”%>
    <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
    <html>
    <head>
    <%
    Connection conn = null;
    MyDBConnection dbcon=new MyDBConnection();
    conn=dbcon.getLocalConnection();
    Statement stmt = conn.createStatement();
    String sqlstring = “select * from mytab”;
    ResultSet rset = stmt.executeQuery (sqlstring);
    while (rset.next ())
    System.out.println (rset.getString (1));
    %><meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
    <title>Jdbc-Connection-Testing</title>
    </head>
    <body>
    DB Connection
    </body>
    </html>in mypge.jsp file.
  • Then Create a table

CREATE TABLE “MYTAB”
(“NAME” VARCHAR2(40 BYTE),
“AGE” VARCHAR2(40 BYTE))

  • Insert five records in above table
    INSERT INTO “ANSHU”.”MYTAB” (NAME, AGE) VALUES (‘a’, ’12′)
    INSERT INTO “ANSHU”.”MYTAB” (NAME, AGE) VALUES (‘b’, ’13′)
    INSERT INTO “ANSHU”.”MYTAB” (NAME, AGE) VALUES (‘c’, ’14′)
    INSERT INTO “ANSHU”.”MYTAB” (NAME, AGE) VALUES (‘d’, ’15′)
    INSERT INTO “ANSHU”.”MYTAB” (NAME, AGE) VALUES (‘e’, ’16′)
  • Right Click on mypage.jsp ->Run As->Run on Server->Finish
  • Output will come in console.

B)

i.Sample Web Application With Struts & Eclipse

Before we starts with our first Hello World Struts 2 Example, we will need few tools.

  1. JDK 1.5 above (download)
  2. Tomcat 5.x above  (download)
  3. Eclipse 3.2.x above (download)
  4. Apache Struts2 JAR files:(download). Following are the list of JAR files required for this application.
    • commons-logging-1.0.4.jar
    • freemarker-2.3.8.jar
    • ognl-2.6.11.jar
    • struts2-core-2.0.12.jar
    • xwork-2.0.6.jar

    Note that depending on the current version of Struts2, the version number of above jar files may change.

Our Goal

Our goal is to create a basic Struts2 application with a Login page. User will enter login credential and if authenticated successfully she will be redirected to a Welcome page which will display message ” Howdy, <username>…!“. If user is not authenticated, she will be redirected back to the login page.

Getting Started

Let us start with our first Struts2 based application.
Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

After selecting Dynamic Web Project, press Next.

Write the name of the project. For example StrutsHelloWorld. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer.

Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.

Mapping Struts2 in WEB.xml

Hence we will define an entry of org.apache.struts2.dispatcher.FilterDispatcherclass in web.xml.

Open web.xml file which is under WEB-INF folder and copy paste following code.

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

<web-app id="WebApp_9" 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>Struts2 Application</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>

			org.apache.struts2.dispatcher.FilterDispatcher
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>

	</filter-mapping>
	<welcome-file-list>
		<welcome-file>Login.jsp</welcome-file>
	</welcome-file-list>

</web-app>

The above code in web.xml will map Struts2 filter with url /*. The default url mapping for struts2 application will be /*.action. Also note that we have define Login.jsp as welcome file.

The Action Class

We will need an Action class that will authenticate our user and holds the value for username and password. For this we will create a package net.viralpatel.struts2 in the source folder. This package will contain the action file.

Create a class called LoginAction in net.viralpatel.struts2 package with following content.

package net.viralpatel.struts2;

public class LoginAction {
	private String username;
	private String password;

	public String execute() {

		if (this.username.equals("admin")
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			return "error";
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

Note that, above action class contains two fields, username and password which will hold the values from form and also contains an execute() method that will authenticate the user. In this simple example, we are checking if username is admin and password is admin123.

Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method.

The execute() method returns a String value which will determine the result page. Also, in Struts2 the name of the method is not fixed. In this example we have define method execute(). You may want to define a method authenticate() instead.

The ResourceBundle

ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.

ResourceBundle comes handy when we want to add Internationalization (I18N) support to an application.

We will define an ApplicationResources.properties file for our application. This property file should be present in WEB-INF/classes folders when the source is compiled. Thus we will create a source folder called resources and put the ApplicationResources.properties file in it.

To create a source folder, right click on your project in Project Explorer and select New -> Source Folder.


Specify folder name resources and press Finish.

Create a file ApplicationResources.properties under resources folder.

Copy following content in ApplicationResources.properties.

label.username= Username
label.password= Password
label.login= Login

The JSP

We will create two JSP files to render the output to user. Login.jsp will be the starting point of our application which will contain a simple login form with username and password. On successful authentication, user will be redirected toWelcome.jsp which will display a simple welcome message.

Create two JSP files Login.jsp and Welcome.jsp in WebContent folder of your project. Copy following content into it.

Login.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>

<title>Struts 2 - Login Application | ViralPatel.net</title>
</head>

<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="login.action" method="post">

	<s:textfield name="username" key="label.username" size="20" />
	<s:password name="password" key="label.password" size="20" />

	<s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

Welcome.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>

<head>
<title>Welcome</title>
</head>

<body>
	<h2>Howdy, <s:property value="username" />...!</h2>

</body>
</html>

Note that we have used struts2 <s:> tag to render the textboxes and labels. Struts2 comes with a powerful built-in tag library to render UI elements more efficiently.

The struts.xml file

Struts2 reads the configuration and class definition from an xml file called struts.xml. This file is loaded from the classpath of the project. We will define struts.xml file in the resources folder. Create file struts.xml in resources folder.

Copy following content into struts.xml.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.enable.DynamicMethodInvocation"
		value="false" />
	<constant name="struts.devMode" value="false" />

	<constant name="struts.custom.i18n.resources"
		value="ApplicationResources" />

	<package name="default" extends="struts-default" namespace="/">

		<action name="login"
			class="net.viralpatel.struts2.LoginAction">
			<result name="success">Welcome.jsp</result>
			<result name="error">Login.jsp</result>

		</action>
	</package>
</struts>

Note that in above configuration file, we have defined Login action of our application. Two result paths are mapped with LoginAction depending on the outcome of execute() method. If execute() method returns success, user will be redirected to Welcome.jsp else to Login.jsp.

Also note that a constant is specified with name struts.custom.i18n.resources. This constant specify the resource bundle file that we created in above steps. We just have to specify name of resource bundle file without extension (ApplicationResources without .properties).

Our LoginAction contains the method execute() which is the default method getting called by Sturts2. If the name of method is different, e.g. authenticate(); then we should specify the method name in <action> tag.

<action name="login" method="authenticate"
	class="net.viralpatel.struts2.LoginAction">

Almost Done

We are almost done with the application. You may want to run the application now and see the result yourself. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows -> Show View -> Server. Right click in this view and select New -> Server and add your server details.
To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)

But there is one small problem. Our application runs perfectly fine at this point. But when user enters wrong credential, she is redirected to Login page. But no error message is displayed. User does not know what just happened. A good application always show proper error messages to user. So we must display an error message Invalid Username/Password. Please try again when user authentication is failed.

Final Touch

To add this functionality first we will add the error message in our ResourceBundle file.
Open ApplicationResources.properties and add an entry for error.login in it. The final ApplicationResources.properties will look like:

label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.

Also we need to add logic in LoginAction to add error message if user is not authenticated. But there is one problem. Our error message is specified in ApplicationResources.properties file. We must specify key error.login in LoginAction and the message should be displayed on JSP page.

For this we must implement com.opensymphony.xwork2.TextProvider interface which provides method getText(). This method returns String value from resource bundle file. We just have to pass the key value as argument to getText() method. The TextProvider interface defines several method that we must implement in order to get hold on getText() method. But we don’t want to spoil our code by adding all those methods which we do not intend to use. There is a good way of dealing with this problem.

Struts2 comes with a very useful class com.opensymphony.xwork2.ActionSupport. We just have to extend our LoginAction class with this class and directly use methods such as getText(), addActionErrors() etc. Thus we will extend the LoginAction class with ActionSupport class and add the logic for error reporting into it. The final code in LoginAction must look like:

package net.viralpatel.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	private String username;
	private String password;

	public String execute() {

		if (this.username.equals("admin")
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			addActionError(getText("error.login"));
			return "error";
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

And that’s it. Our first Hello World Struts2 Application is now ready.

That’s All

Execute the application in Eclipse and run it in your favorite browser.
Login page


Welcome page


Login page with error

ii.Sample Web Application (Struts,Eclipse & Database)

Create a sample web application as above.

Struts2.0 insert data in database table

Introduction:-In struts 2.0 framework insert data in database table through the JDBC API.

Class/Library File  Descriptions:-

Require tools to run this application

1. Struts2.0 jar file
2. Tomcat server
3. Database Oracle10g
Source Code:-

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping></web-app>

index.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<s:actionerror/>
<s:form action="insert">
<s:textfield name="name" label="Name"/>
<s:textfield name="address" label="Address"/>
<s:textfield name="city" label="City"/>
<s:textfield name="state" label="State"/>
<s:submit value="Submit"></s:submit>
</s:form>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration
2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="demo" extends="struts-default">
<action name="insert" class="org.r4r.UserListInsertAction">
<result name="success">/index.jsp</result>
<result name="input">/index.jsp</result>
<result name="error">/index.jsp</result>
</action>
</package>
</struts>

UserListInsertAction.java

package org.r4r;

import com.opensymphony.xwork2.ActionSupport;

public class UserListInsertAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	String name;
	String address;
	String city;
	String state;
	DAO dao=new DAO();

	public String execute(){
		if(dao.insert(name, address, city, state)){
			this.addActionError("You are successfully insert data.");
			return "success";}
		else
			this.addActionError("Data is not successfully insert");
			return "error";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}

}

DAO.java

package org.r4r;

import java.sql.Connection;
import java.sql.PreparedStatement;

public class DAO {
	public boolean insert(String name,String address,String city,String state){
		try{
			Connection con=ConnectionProvider.getConnection();
			PreparedStatement stmt=con.prepareStatement
("insert into userlist values(?,?,?,?)");
			stmt.setString(1,name);
			stmt.setString(2,address);
			stmt.setString(3,city);
			stmt.setString(4,state);
			stmt.executeQuery();
			return true;

		}catch(Exception e){
			System.out.println(e);
		}
		return false;
	}

}

ConnectionProvider.java

package org.r4r;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionProvider {
	public static Connection getConnection(){
		Connection con=null;
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","system");
		}catch(Exception e){
			System.out.println(e);
		}
		return con;
	}

}

 
1 Comment

Posted by on 04/08/2011 in Sample Project in ECLIPSE

 
 
Follow

Get every new post delivered to your Inbox.