MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to read a JSP form data using Servlet Class and insert the data to MySQL database

In this article, we will learn about MVC architecture, JSP, Servlet. We will learn how to get data from a JSP form to our Servlet class.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Java Server Pages (JSP) is a technology to create dynamic web pages. JSP is primarily based on HTML. JSP can also be defined as Java Codes inside HTML. JSP primarily contains tags like HTML.

Servlets, are server side java programs. Servlets are mainly used as a controller to transfer a data from JSP form to Database. In terms of java, servlets are nothing but classes which extends HTTPServlet class (or) Generic Servlet class from javax.servlet package (or) from any other servlet api.

MVC architecture, or Model View Controller architecture, is a software architecture pattern which separates the business logic and presentation logic. The entire program can be divided into layers such as presentation layer, presentation logic layer, business layer, data layer and data manipulation layer.

In this tutorial JSP is used for view (or) presentation layer and Servlet is used as controller and data manipulation layer. This program is basically having two layers. The advantage is, any changes which we want to do as for the front end (or) presentation layer is concerned, it does not affect the business logic (or) in other words we are not going to touch the data manipulation layer code.

MySQL is an open source relational database management system (RDBMS), which we are going to use as back end.

Servlets Overview in Java

Figure 1: Servlets Overview in Java

Now we will create a simple application which will get user name and password from a JSP form and prints the values in console by means of a servlet class. Later we will see how to insert those values in database.

Step 1: In this step, we will learn to create a JSP page.

Listing 1: Shows the code to perform step 1

<html>
<body>
<form name=”registration” action="SaveUser" method="Post">
First Name: <input type="text" name="user_name">
<br />
Password: <input type="password" name="pass_word" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

On looking at the above JSP page we can say it’s exactly the same as any HTML page.

The main difference between a JSP Page and HTML page is

  • JSP page is dynamic and HTML page is static.
  • In JSP we can use Java codes by means of scriplets and some other special tags. In HTML it’s not possible.

JSP should be named have ‘.jsp’ as extension. So we will call the above file as registrationpage.jsp.

In the JSP page we can include anything that we can include in an HTML page. For example we can have CSS, we can have Java Script, we can use all HTML tags without any constraints. Javascripts are mainly used for validations, and CSS is used for designing purpose.

In the above JSP page we have a form named as ‘registration’. In the form tag we have an attribute ‘action’ which tells the form where it needs to go next (or) which servlet class needs to be used for further process. The value ‘SaveUser’ for the ‘action’ attribute is nothing but the name of the servlet class which we are going to create next. This servlet class is responsible for connecting with the database and inserting the values.

Step 2: In this step, we will learn to create a Servlet which get the values from JSP form.

Listing 2: Shows the code to perform step 2.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

 //Get user_name and pass_word from the JSP page


String username=request.getParameter("user_name");
String password=request.getParameter("pass_word");

//Print the above got values in console

System.out.println("The username is" +username);

System.out.println("\nand the password is" +password);
    }
}

Step 3: In this step, we will learn how to create a database and table in MySQL.

In order to execute this step you should have MySQL server installed in your machine.

You can download the MySQL server in the below URL: http://dev.mysql.com/downloads/

You can also download MySQL Workbench from the above URL. MySQL workbench is a GUI using which you can manipulate your MySQL databases more efficiently and easily.

While installing the MySQL server, it will prompt for username and password. Make a note of the username and password. It will be used for further process.

After installing MySQL server the steps you need to follow are:

  • Create a database in MySQL and name it as userdb.
  • Create a table in the database and name it as usertable.
  • Create three fields serial_no, user_name and password.

Listing 3: Shows the code to perform step 3.

Query to create a database.

 create database userdb;

Here are the complete details of the above query:

  • Create database, commands the server to create a database.
  • userdb, is the name that is given to the database.

Query to create a table with specified fields.

 create table usertable 
 (serial_no int not null primary key auto_increment,
 user_name varchar(30),
Pass_word varchar(10) );

Here are the complete details of the above query:

  • serial_no, is the name of the field.
  • int, is the data type meaning integer.
  • not null, meaning the field should never be empty. In other words for each and every record it should hold a value.
  • primary key, is the key which uniquely identifies each record of the table. Here serial_no is the primary key.
  • auto_increment, meaning , serial_no will start with 1 and for each entry serial_no will increment by 1.
  • user_name, is the field in which we are going to capture the ‘user_name’ coming from JSP page.
  • varchar, is another datatype, declared for user_name meaning user_name is going to be some textual imformation.
  • (30),states the size of the textual imformation. The size can be changed to any other number according to our needs.
  • pass_word, is the field in which we are going to capture the ‘pass_word ‘ coming from JSP page.
  • varchar, is the same datatype, declared for user_name meaning ‘pass_word’ is going to be some textual imformation.
  • (10),states the size of the password imformation. As we know size can be changed to any other number and so the password size is set to 10, since password is something which should be small and easy to remember.

Step 4: In this step, we will learn how to populate the user_name and pass_word fields in the table we have created, from our JSP form.

Listing 4: Shows the code to perform step 4.

  //Declaring all the import statements required for the program to execute

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class  SaveUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{



 //Getting user_name and pass_word from the JSP page

String username=request.getParameter("user_name");
String password=request.getParameter("pass_word");

//Printing the above got values in console

System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);



//Setting connection Parameters

String connectionparams=”jdbc:mysql://localhost:3306/”;

// database name

String db=” userdb”;       
   
// Mysql user name and password   whichever  you have given during installation 
                   
String uname=”username”                    
String psword=”password”                  

// Declaring classes required for Database support

Connection connection=null;
  ResultSet rs;
try {
  // Loading the available driver for a Database communication
  
Class.forName("org.gjt.mm.mysql.Driver");

  //Creating a connection to the required database

  connection = DriverManager.getConnection
  (connectionURL, uname, psword); 

  //Add the data into the database

  String sql = "insert into usertable values (?,?)";
 

  PreparedStatement prep = 
  connection.prepareStatement(sql);

// Setting the values which we got from JSP form

  prep.setString(1, username);
  prep.setString(2, password);
  prep.executeUpdate();
  prep.close();
    }catch(Exception E){

//Any Exceptions will be caught here 

System.out.println(“The error is==”+E.getMessage()); 

}
finally{

//After the entire execution this block will execute and the connection with database gets closed

connection.close();


}
}

Conclusion

In this article, we have learnt about MVC pattern, JSP, Servlet. We learnt how to get data from a JSP form to our Servlet class, we learnt how to create database and tables in Mysql and we learnt how to insert the values to the MySQL database from JSP form.



I am well versed with Computer Programming languages and possess good working knowledge on software languages such as C, Java, PHP, HTML and CSS

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login