Database Connection in Struts

In this example, we are going to create a Registration Form using struts Framework and store these information into the mysql database. You can use other database also such as oracle, DB2 etc. according to your requirement.

Tools Used:

  • Eclipse
  • Struts 1.2
  • Tomcat 6 Server
  • MYSQL Database


Steps to create the registration application in struts are as follows:

  1. Create Table in DB
  2. Create input page (login.jsp)
  3. Create the action class (UserRegisterAction.java)
  4. Create the class to store data (UserRegisterDao.java)
  5. Map the request in (struts-config.xml) file and define the view components
  6. Create view components

In this example, we are going to create a Registration Form using struts Framework and store these information into the mysql database. You can use other database also such as oracle, DB2 etc. according to your requirement.

Tools Used:

  • Eclipse
  • Struts 1.2
  • Tomcat 6 Server
  • MYSQL Database


Steps to create the registration application in struts are as follows:

  1. Create Table in DB
  2. Create input page (login.jsp)
  3. Create the action class (UserRegisterAction.java)
  4. Create the class to store data (UserRegisterDao.java)
  5. Map the request in (struts-config.xml) file and define the view components
  6. Create view components



Steps to be followed :

Steps for the complete Project is given below.

Step 1 : Create table USER_DETAILS in MYSQL

create table USER_DETAILS 
(FIRST_NAME varchar(50),
 LAST_NAME varchar(50),
 USER_NAME varchar(50),
 PASSWORD varchar(50),
 EMAIL varchar(50),
 PHONE varchar(15));


Step 2 : Create Dynamic Web Project

Open Eclipse and click on File -> New -> Project and select Dynamic Web Project in the New Project wizard screen as shown below.

Struts Application in Eclipse

After selecting Dynamic Web Project, press Next, in next screen provide the name of the project. Enter the name of the project as StrutsDBExample and click on Finish as shown below.

Struts datbase Application in Eclipse


Step 3 : Add jar files to the classpath of Project

Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder.Following jar files should be added to the project build path for successful deployment of struts project :

Struts datbase Application in Eclipse

Copy all the tld files to WEB-INF folder and make the entry of these tld files in web.xml file.

Now we have to configure ActionServlet of struts with web.xml.The first page that will be called in the login application is the login.jsp page. This configuration should be done in web.xml as <welcome-file-list> .

Following xml shows how to configure struts in web.xml.

web.xml

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>

		<init-param>
			<param-name>debug</param-name>
			<param-value>2</param-value>
		</init-param>
		<init-param>
			<param-name>detail</param-name>
			<param-value>2</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

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

	<taglib>
		<taglib-uri>/struts-html</taglib-uri>
		<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
	</taglib>

</web-app>


Step 4 : Create JSPs for UI of the application :

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-html" prefix="html" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
</head>
<body bgcolor="silver">
<br></br>
<body>
<html:html>
    <div style="color:red">
    <html:errors />
    </div>
	<html:form action="/register" method="get">

		Enter your First Name:
		<html:text property="firstName" size="50" /><br><br>
		Enter your Last Name:
		<html:text property="lastName" size="50" /><br><br>
		Enter your username:
		<html:text property="userName" size="50" /><br><br>
		Enter your password:
		<html:text property="password" size="30" /><br><br>
		Enter your Email:
		<html:text property="email" size="30" /><br><br>
		Enter your Phone No:
		<html:text property="phone" size="15" /><br><br>
		<html:submit>Submit</html:submit>
		<br><br>
	</html:form>
</html:html>
</body>
</html>

In login.jsp, We used Struts HTML Tags to create login page. The form has six text field to get the user details. The form has one submit button,when this button is clicked it will call register action.

success.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success page</title>
</head>
<body bgcolor="silver">
<table><tr>
sucessfully added</tr><br><br>
<%=session.getAttribute("firstName") %><br><br>
<%=session.getAttribute("lastName") %><br><br>
<%=session.getAttribute("userName") %><br><br>
<%=session.getAttribute("email") %><br><br>
<%=session.getAttribute("phone") %><br><br>
</table>
</body>
</html>

User will navigate to success.jsp page after successful registration.



Step 5 : Create Form Beans :

Create a package com.jwt.struts.form and in that package create a java class UserRegisterForm and copy following code into this class.

UserRegisterForm.java

package com.jwt.struts.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class UserRegisterForm extends ActionForm {

	private static final long serialVersionUID = 1L;
	private String firstName;
	private String lastName;
	private String userName;
	private String password;
	private String email;
	private String phone;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		if (firstName == null || firstName.length() < 1) {
			errors.add("firstName", new ActionMessage(
					"error.firstName.required"));

		}
		if (lastName == null || lastName.length() < 1) {
			errors.add("lastName", new ActionMessage("error.lastName.required"));

		}
		if (userName == null || userName.length() < 1) {
			errors.add("userName", new ActionMessage("error.userName.required"));

		}
		if (password == null || password.length() < 1) {
			errors.add("password", new ActionMessage("error.password.required"));

		}
		if (email == null || email.length() < 1) {
			errors.add("email", new ActionMessage("error.email.required"));

		}
		if (phone == null || phone.length() < 1) {
			errors.add("phone", new ActionMessage("error.phone.required"));

		}
		return errors;
	}

	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;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

}

Inside the validate method, we will check whether all field is entered, If not the corresponding error message is displayed to the user. The error messages are configured in the ApplicationResource.properties file.

The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the control is returned back to the input page where the errors are displayed to the user. The input page is configured in the action tag of struts-configuration file. <html:errors/> tag is used to display the errors in the jsp page.


Step 6 : Create DAO Class :

Create a package com.jwt.struts.dao and in that package create a java class UserRegisterDAO and copy following code into this class. This is a simple database access class.In this class we have defined one business method insertData() which will insert user details into database.

This class gets information from the object of UserRegisterAction class and stores these information into USER_DETAILS table.

UserRegisterDao.java

package com.jwt.struts.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UserRegisterDAO {
	public void insertData(String firstName, String lastName, String userName,
			String password, String email, String phone) throws Exception {
		System.out.println("jdbc connection");
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost/strutsdb", "root", "mukesh");

		try {

			try {
				Statement st = con.createStatement();
				int value = st
						.executeUpdate("INSERT INTO USER_DETAILS(FIRST_NAME,LAST_NAME,USER_NAME,PASSWORD,EMAIL,PHONE) "
								+ "VALUES('"
								+ firstName
								+ "','"
								+ lastName
								+ "','"
								+ userName
								+ "','"
								+ password
								+ "','"
								+ email + "','" + phone + "')");
				System.out.println("1 row affected" + value);
			} catch (SQLException ex) {
				System.out.println("SQL statement is not executed!" + ex);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


Step 7 : Create Action Class :

Create a package com.jwt.struts.action and in this package create a java class UserRegisterAction and copy following code into this class

UserRegisterAction.java

package com.jwt.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jwt.struts.dao.UserRegisterDAO;
import com.jwt.struts.form.UserRegisterForm;

public class UserRegisterAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession ses = request.getSession(true);

		UserRegisterForm registerForm = (UserRegisterForm) form;
		String firstName = registerForm.getFirstName();
		String lastName = registerForm.getLastName();
		String userName = registerForm.getUserName();
		String password = registerForm.getPassword();
		String email = registerForm.getEmail();
		String phone = registerForm.getPhone();
		UserRegisterDAO dao = new UserRegisterDAO();
		dao.insertData(firstName, lastName, userName, password, email, phone);
		ses.setAttribute("firstName", firstName);
		ses.setAttribute("lastName", lastName);
		ses.setAttribute("userName", userName);
		ses.setAttribute("email", email);
		ses.setAttribute("phone", phone);
		if (firstName.equals("") || lastName.equals("") || userName.equals("")
				|| password.equals("") || email.equals("") || phone.equals("")) {
			return mapping.findForward("error");
		}
		return mapping.findForward("success");

	}
}

The execute() method contains the business logic of the application. Here first we typecast the ActionForm object to UserRegisterForm, so that we can access the form variables using the getter and setter methods. If all fields are saved to database then we forward the user to the success.jsp page.

These configuration has been done in struts-config.xml file which is given below.


Step 8 : Create struts-config.xml file :

Create struts-config.xml file inside WEB-INF folder of the project.

struts-config.xml

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

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">


<struts-config>
	<form-beans>
		<form-bean name="registerForm" type="com.jwt.struts.form.UserRegisterForm" />
	</form-beans>

	<action-mappings>
		<action input="/login.jsp" name="registerForm" path="/register"
			type="com.jwt.struts.action.UserRegisterAction">
			<forward name="success" path="/success.jsp" />
		</action>
	</action-mappings>

	<message-resources parameter="com/jwt/struts/action/ApplicationResource" />

</struts-config>

Step 9 : Create properties file :

The ApplicationResource.properties file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a separate properties file they can be changed any time without making any changes to the java files or the jsp pages.So no need to restart server if we are changing any values to these keys.

ApplicationResource.properties

error.userName.required = User Name is required.
error.password.required = Password is required.
error.firstName.required = First Name is Required.
error.lastName.required = Last Name is Required.
error.email.required = email is Required.
error.phone.required = Phone is Required.


Directory Structure of the Project :

Final directory Structure of the Project is given below.

Struts database Application in Eclipse

Run the application :

To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R).

Login Page :

Struts database Application in Eclipse

Validation Error :

Struts database Application in Eclipse

Enter all the field value as shown below and click Submit button.

Struts database Application in Eclipse

After successful insertion of data you will be redirected to success.jsp page as shown below.

Struts database Application in Eclipse

Check the table either data is inserted or not ?.

Struts database Application in Eclipse

Download this example(src+lib) developed in eclipse





comments powered by Disqus