Struts 2 Database Access

shape Description

Struts 2 Database Access, While working on web based projects developer will take the help of the database connection to store the data and to retrieve the data. Struts 2 is an MVC Framework and not a database framework, but it supports the JPA/Hibernate integration. When connected to JDBC (Java database connectivity) API. For example, let’s take the login page. Whenever, username and password is entered and clicked on the submit button, then Struts container goes to the database, and check whether This user exists or not.

shape Steps

In application, by using Oracle database. Install Oracle Database and create the tables.

shape Step 1

Create a table in Oracle database with name Struts2table and make the username as a primary key and after creating the table, insert one-row data in Strut2table like.

shape Step 2

Create the project directory structure.

shape Step 3

Create the view pages and forward the request to Action class from View page.

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
   <body>
     <s:form action="login">
      <s:textfield name="username" label="Username"></s:textfield>
      <s:password name="password" label="Password"></s:password>
      <s:submit value="Login"></s:submit>
     </s:form>
   </body>
</html>

Here the developer created two text boxes to enter the data such as Username and Password and also created a submit button.
success.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
  <head>
    <title>Successful Login</title>
  </head>
  <body>
     <font color="green"><h1>Welcome to SPLessons</h1></font>
     <h2> Hai <s:property value="name"/></h2>
  </body>
</html>
To display the success message.

error.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
   <head>
      <title>Invalid User Name or Password</title>
   </head>
   <body>
     <font color="red">
         <h3>User name or password is wrong, please try again.<h3>
     </font>
   </body>
</html>

To display the error message.

shape Step 4

To write the database connection logic in Action class execute() method.

DatabaseConnection.java


package com.splessons;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.opensymphony.xwork2.ActionSupport;

public class DataBaseAction extends ActionSupport
{

  private String username;
  private String password;
  private String name;
  public String getName()
  {
    return name;
   }
  public void setName(String name)
  {
   this.name = name;
   }
  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 execute()
  {
    String result="error";
    Connection connection=null;
   try
   {
    String URL = "jdbc:oracle:thin:@localhost:1521:xe";
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection = DriverManager.getConnection(URL, "system", "system");
    String sql = "SELECT name FROM struts2table WHERE username = ? AND password = ? ";
    
    PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);

    ResultSet resultset = preparedStatement.executeQuery();
    while(resultset.next())
      {
     name = resultset.getString(1);
      result="success";
      }//while
     } //try
     catch (Exception e)
     {
      result ="error";
      } //catch
    finally
    {
     if (conn != null)
      {
       try
        {
         conn.close();
          } //try
       catch (Exception e)
       {
        System.out.println(e);
        }//catch
      }//if
    }//finally
   return result;
  }//execute()
}

Here created the data members and also performed SET and GET methods and make sure that database connector needs to be imported.
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.devMode" value="true" />
   <package name="helloworld" extends="struts-default">
     <action name="login"  class="com.splessons.DataBaseAction" method="execute">
        <result name="success">success.jsp</result>
        <result name="error">error.jsp</result>
     </action>
   </package>
</struts>

Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <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>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

shape Output

Run the application in browser.

Enter the username and password, click login button.

If entered the wrong values then the output is as shown in the below image.

shape Programming
Tips

  • The database connector should be added to the lib folder.
  • The prepared statement is utilized to push queries to the database.
  • struts.devmode is utilized to find huge debug alerts in the logging file.


Summary

shape Key Points

  • Data base connector jar file needs to be imported.
  • DevMode is nothing but Development Mode.