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.
Step 2 : Create an input jsp form.
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.
Description of the code:
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.
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.
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
This method establishes a connection to specified database url. It takes three string types of arguments like:
- Database url to link with
userName: - User name of database
password: -Password of database
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.
When entered the correct data in the text field the user gets the insertSuccess.jsp page displaying the entered data.
When this application executes the user gets the following:
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 :
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:
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial