Struts 2 MySQL

In this section, You will learn to connect the MySQL database with the struts 2 application.

Struts 2 MySQL

Struts 2 MySQL

     

In this section, You will learn to connect the MySQL database with the struts 2 application.

Follow the following steps to connect with MySQL database:

 

 

 

 

 

 

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

<?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>

  <!-- Rose India Struts Tutorials -->
  <constant name="struts.enable.DynamicMethodInvocation" 
   value=
"false" />

  <constant name="struts.devMode" value="true" />
<include file="struts-default.xml"/>  

  <!-- Add packages here -->


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

<!-- inserting data into data base through JDBC -->

  <action name="insert">
  <result>/pages/insertData.jsp</result>
  </action>

  <action name="insertData" class="net.roseindia.insert">
  <result  name="error">/pages/insertData.jsp</result>
  <result>/pages/insertSuccess.jsp</result>
  </action>
  
  </package>


</struts>

Step 2 : Create an input jsp form.

insertData.jsp

<%taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts Insert Data Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"
type="text/css"/>

</head>
<body>


<s:form action="insertData" method="POST" validate="true">

<tr>
<td colspan="2">
Please enter
</td>

</tr>

<s:actionerror />
<s:fielderror />

<s:textfield name="username" label="User Name"/>
<s:password name="password" label="Password"/>
<s:submit value="Save" align="center"/>

</s:form>

</body>

</html>

Step 3 : Create an Action class.

First, Establish a connection with the MySQL Database with the help of MySQL driver ("org.gjt.mm.mysql.Driver"). 
Now, Make an account in the MySQL database to get connected with the database. 

After establishing a connection,  you can  retrieve, insert and update data to the MySQL database table. 

The following action class establishes a connection with MySQL database with the help of appropriate type of methods and API interfaces. If connection is established then the entered data is added to the MySQL  database table otherwise it displays an error message.

insert.java

package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
import java.sql.*;


/**
 <p> Validate a user login. </p>
 */
public  class insert  extends ActionSupport {
  
  public String execute() throws Exception {
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "taskproject";
  String driverName = "org.gjt.mm.mysql.Driver";
  String userName = "root";
  String password = "root";
  Connection con=null;
  Statement stmt=null;
  try{
  Class.forName(driverName).newInstance();
  con=DriverManager.getConnection(url+dbName, userName, 
  password
);
  stmt=con.createStatement();
  }
  catch(Exception e){
  System.out.println(e.getMessage());
  }
  String uname=getUsername();
  String pws=getPassword();
  stmt = con.createStatement();
  int val = stmt.executeUpdate("INSERT employee VALUES
  ('"
+uname+"','"+pws+"')");

  if(val == 0){
  return ERROR;
  }
  else{
  return SUCCESS;
  }
  }
  // ---- Username property ----

  /**
 <p>Field to store User username.</p>
 <p/>
 */
  private String username = null;


  /**
 <p>Provide User username.</p>
 *
 @return Returns the User username.
 */
  public String getUsername() {
  return username;
  }

  /**
 <p>Store new User username</p>
 *
 @param value The username to set.
 */
  public void setUsername(String value) {
  username = value;
  }

  // ---- Username property ----

  /**
 <p>Field to store User password.</p>
 <p/>
 */
  private String password = null;


  /**
 <p>Provide User password.</p>
 *
 @return Returns the User password.
 */
  public String getPassword() {
  return password;
  }

  /**
 <p>Store new User password</p>
 *
 @param value The password to set.
 */
  public void setPassword(String value) {
  password = value;
  }

}

Description of the code:

Connection:
This is an interface in  java.sql package that specifies establishing connection with the specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class dynamically and returns class instance and takes string type value (driver) when it matches with the class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be registered with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like: 

    url: - Database url to link with
  userName: - User name of database
  password: -Password of database

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.

Step 4 : Create the validator

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

insert-validation.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC 
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN" 
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
  
<validators>
  <field name="username">
  <field-validator type="requiredstring">
  <param name="trim">true</param>
  <message>User name is required</message>
  </field-validator>
  </field>
  <field name="password">
  <field-validator type="requiredstring">
  <param name="trim">true</param>
  <message>Password is required</message>
  </field-validator>
  </field>
</validators>

When entered the correct data in the text field the user gets the insertSuccess.jsp page  displaying the entered data. 

insertSuccess.jsp 0

<html>

<head>

<title>Inserted Data List</title>

</head>

<body>
<b> Inserted Data: </b>
<b>User name = </b><%=request.getParameter("username"%>!
<b>Password = </b><%=request.getParameter("password"%>!
</body>

</html>

Output:

When this application executes the user gets the following:

1

Without filling fields and click "Save" button, you will get  the output page as :

If you fill only the "Password" field and  click "Save" button without filling the next fields, you will get  the output page as : 2

If you fill only the "User Name" field and  click "Save" button without filling the next fields, you will get  the output page as :

If you fill both field:

Then you get: 3