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"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        
        <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" />
        </html:form>
    </body>
</html>

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"
 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">
 <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>
 <session-config>
  <session-timeout>30</session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>Login.jsp</welcome-file>
 </welcome-file-list>
 <jsp-config>

  <taglib>
   <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
 </jsp-config>
</web-app>

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"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

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

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

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

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

 </action-mappings>

</struts-config>

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

  try{
   //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);

   if(i>0){
    key="success";
   }
   else
   {
    key="failure";
   }
  }
  catch(Exception e){
   e.printStackTrace();

  }
  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();
  System.out.println("Connection"+con);

  try{
   //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 {
    ps.close();
    con.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   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://192.168.1.101:3306/";
  String dbName = "TEST";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "test"; 
  String password = "test";
  try {
   Class.forName(driver).newInstance();
   conn = DriverManager.getConnection(url+dbName,userName,password);
   System.out.println("Connected to the database");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }
}

#8). 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>Insert title here</title>
</head>
<body>
<h2><font color="green">Successfully done..!</font></h2>
</body>
</html>

#9). failure.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>Insert title here</title>
</head>
<body>
<h2><font color="red">Please try again..!</font></h2>
</body>
</html>

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

Struts-JDBC_Output001
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.

Struts-JDBC_Output002

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

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


Download SOURCE 

                 StrutsLib 
Reference Books:

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