Powered by Blogger.

Storing username and password using Struts and JDBC

>> Monday, June 13, 2011

Integrating Struts with JDBC is pretty much simple. In real time most of the people work with Hibernate instead of JDBC. Here we can understand using a simple program, how to work using Struts and JDBC.

This is the application to persist the data into database from jsp pages using JDBC and struts.
The required components to develop Struts with JDBC:

Project Structure:

Project Strcture_Struts-JDBC
From the beginning the end user submits the request from JSP form(Login.jsp) to struts based web application.Using struts-html.tld file we generate the html tags in jsp page to read username and password and for submit button.
Before that  we should create a table 'login ' in mysql database as:

create table login (username varchar(10),password varchar(10));

In the Login page the logical path is login to send the action path to Controller in web.xml.

#1). Login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <html:form action="/login" >
            User Name : <html:text name="LoginForm" property="uName" /> <br>
            Password  : <html:password name="LoginForm" property="pWd" /> <br>
            <html:submit value="Login" />

In web.xml the The struts-config.xml will read by the ActionServlet which is configured in init-params.

#2). web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


Based on configurations Action Servlet forwards to struts-config.xml to check the LoginForm name and ActionMappings name to create the LoginForm instance.And the LoginForm object will be created by using form object.Then read the form values keep it in string variables.

#3). struts-config.xml

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

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"


 <!-- ========== Form Bean Definitions ================= -->

  <form-bean name="LoginForm" type="com.javabynataraj.login.LoginForm" />

 <!-- ========== Action Mapping Definitions ============ -->

  <action name="LoginForm" path="/login" scope="session"
   <forward name="success" path="/success.jsp" />
   <forward name="failure" path="/failure.jsp" />



#4). LoginForm.java

package com.javabynataraj.login;

import org.apache.struts.action.ActionForm;

public class LoginForm extends ActionForm{
 private String uName;
 private String pWd;
 public String getuName() {
  return uName;
 public void setuName(String uName) {
  this.uName = uName;
 public String getpWd() {
  return pWd;
 public void setpWd(String pWd) {
  this.pWd = pWd;

#5). LoginAction.java

package com.javabynataraj.login;

import java.sql.Connection;

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

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.javabynataraj.dao.LoginDao;

public class LoginAction extends Action {

 public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
  Connection con = null;
  String key = null;

   //get the values from LoginForm by creating an object
   LoginForm lf = (LoginForm)form;
   String un = lf.getuName();
   String pw = lf.getpWd();
   LoginDao dao=new LoginDao();
   //pass the un,pw values to the LoginDao class of insert method
   int i=dao.insert(un,pw);

  catch(Exception e){

  return mapping.findForward(key);

By creating the Connection object we can connect with database (MySql).

#6). LoginDao.java

package com.javabynataraj.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.javabynataraj.dbcon.DBConnection;

public class LoginDao {

 public int insert(String un,String pw){
  int r=0;
  PreparedStatement ps = null;
  //get connection object from DBConnection class
  Connection con = DBConnection.dbConn();

   //use PreparedStatement to insert the values of username and password
   ps=con.prepareStatement("insert into login(username,password) values(?,?)"); 
   ps.setString(1, un);
   ps.setString(2, pw);
   r = ps.executeUpdate(); 
  catch(SQLException ex) {
   try {
   } catch (SQLException e) {
    // TODO Auto-generated catch block
   System.err.println("SQLException: " + ex.getMessage());
  return r;


#7). DBConnection.java

package com.javabynataraj.dbcon;

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

public class DBConnection {

 public static Connection dbConn(){

  Connection conn = null;
  String url = "jdbc:mysql://";
  String dbName = "TEST";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "test"; 
  String password = "test";
  try {
   conn = DriverManager.getConnection(url+dbName,userName,password);
   System.out.println("Connected to the database");
  } catch (Exception e) {
  return conn;

#8). success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<h2><font color="green">Successfully done..!</font></h2>

#9). failure.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<h2><font color="red">Please try again..!</font></h2>

By running this code in Tomcat5.5 we can see the page Login.jsp as configured in web.xml welcome-file-list.

After entering the values in the fields of username and password the details can be saved in the table named login in mysql.The inserting the values will be done successfully the success.jsp will shown.


If any connection problems and some error will occurred in processing then the failure.jsp will displayed.

if all are done perfectly the values in login table as shown below

Download SOURCE 

Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.