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

 

     

Tutorials

  1. Validations using Struts 2 Annotations
  2. Struts 2 Features
  3. Struts 2 - History of Struts 2
  4. Struts 2 Architecture - Detail information on Struts 2 Architecture
  5. Download and Installing Struts 2
  6. Struts 2 Hello World Application Example, Learn how to develop Hello World application in struts 2.
  7. Developing JSP, Java and Configuration for Hello World Application
  8. Struts Configuration file - struts.xml
  9. Introduction to Struts 2 Tags
  10. Struts2 Actions
  11. Static Parameter
  12. Accessing Session Object
  13. Access Request and Response
  14. Control Tags-If / Else If / Else
  15. Append Tag (Control Tags) Example
  16. Generator Tag (Control Tags) Example
  17. Generator Tag (Control Tags) Using Count Attributes
  18. Generator Tag (Control Tags) Using an Iterator with Id Attributes
  19. Iterator Tag (Control Tags) Example
  20. Merge Tag (Control Tags) Example
  21. Subset Tag (Control Tags) Example
  22. Subset Tag (Control Tags) Example Using Count
  23. Subset Tag (Control Tags) Example Using Start
  24. Action Tag (Data Tag) Example
  25. Bean Tag (Data Tag) Example
  26. Date Tag (Data Tag) Example
  27. Include Tag (Data Tag) Example
  28. Param Tag (Data Tag) Example
  29. Set Tag (Data Tag) Example
  30. Text Tag (Data Tag) Example
  31. Property Tag (Data Tag) Example
  32. Checkbox Tag (Form Tag) Example
  33. Checkboxlist Tag (Form Tag) Example
  34. Datetimepicker Tag (Form Tag) Example
  35. Doubleselect Tag (Form Tag) Example
  36. File Tag (Form Tag) Example
  37. Form Tag Example
  38. Label Tag (Form Tag) Example
  39. Optiontransferselect Tag (Form Tag) Example
  40. Optgroup Tag (Form Tag) Example