Difference between revisions of "Java-Business-Application/C2/Database-and-validation/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 120: Line 120:
  
 
|-
 
|-
| style="border:1pt solid #000000;padding:0.097cm;"| Type the '''username '''as '''arya '''and '''password '''as '''arya123*.'''
+
| style="border:1pt solid #000000;padding:0.097cm;"| Type the '''username '''as '''arya '''and '''password '''as '''arya*123.'''
| style="border:1pt solid #000000;padding:0.097cm;"| Let me type the '''username '''as '''arya '''and '''password '''as '''arya123*.'''
+
| style="border:1pt solid #000000;padding:0.097cm;"| Let me type the '''username '''as '''arya '''and '''password '''as '''arya*123.'''
  
 
|-
 
|-
Line 478: Line 478:
  
 
|-
 
|-
| style="border:1pt solid #000000;padding:0.097cm;"| Highlight '''public User(String firstName, String surname, int age,String gender,String email,String username,String password){'''
+
| style="border:1pt solid #000000;padding:0.097cm;"| Highlight '''public User(String firstName, '''
 +
 
 +
'''String surname, int age, String gender, '''
 +
 
 +
'''String email,String username,String password){'''
  
 
'''this.firstName<nowiki>=</nowiki>firstName<nowiki>;</nowiki>'''
 
'''this.firstName<nowiki>=</nowiki>firstName<nowiki>;</nowiki>'''
Line 660: Line 664:
  
 
|-
 
|-
| style="border:1pt solid #000000;padding:0.097cm;"| Highlight '''User user =new User(firstName,surname,ageUser,gender,email,userName,password);'''
+
| style="border:1pt solid #000000;padding:0.097cm;"| Highlight '''User user =new User(firstName,surname,ageUser,'''
 +
 
 +
'''gender,email,userName,password);'''
 
| style="border:1pt solid #000000;padding:0.097cm;"| We initialize variable '''user '''as '''instance '''of '''User Model '''with individual '''attributes.'''
 
| style="border:1pt solid #000000;padding:0.097cm;"| We initialize variable '''user '''as '''instance '''of '''User Model '''with individual '''attributes.'''
  

Latest revision as of 14:27, 13 April 2015

Title of script: Database and validation

Author: arya

Keywords: servlets, video tutorial, database,validation


Visual Cue
Narration
Slide 1 Welcome to the spoken-tutorial on Database and validation.
Slide 2 In this tutorial we will learn to:
  • Interact with database
  • Validate the fields


Slide 3

Software Requirements

Here we are using
  • Ubuntu Version 12.04
  • Netbeans IDE 7.3
  • JDK 1.7
  • Firefox web-browser 21.0

You can use any web-browser of your choice.

Slide 4

Prerequisites

To follow this tutorial you must have knowledge of
  • Basics of Java Servlets and JSPs
  • MySQL Database connection in Netbeans IDE
  • Creating database and tables

If not, for relevant tutorials please visit our website.

Go to Netbeans IDE. Let us go to Netbeans IDE.
Highlight MySQL Server. I have started the MySQL server.
Highlight library. I have created a database named library.
Highlight users. I have created a table in it named Users.
I have already inserted some values into this table.
I will show them now.
Right click on Users. For that, right click on Users and click on View Data.

Click on the Output button at the bottom.

Scroll down. We can see that we have 10 users here.
Point to all the columns. Here, we can see the FirstName, Surname, Age, Gender, Email, Username and Password.
Now, let us load the JDBC driver that is Java Database Connectivity Driver.
Click on the Projects tab. Click on the Projects tab.
Right click on Libraries tab. Right click on Libraries tab.
Click on Add Library. Click on Add Library.
Click on MySQL JDBC Driver. Click on MySQL JDBC Driver.
Click on Add Library. Then click on Add Library.
This will load the JDBC Driver.
Now, let us run the Project as we had done earlier.
Type the username as arya and password as arya*123. Let me type the username as arya and password as arya*123.
Click on Sign In. Then click on Sign In.
We can see the successGreeting page.
Click on here to logout. Click on here to logout.
Switch back to the IDE. Now, let us switch back to the IDE.
Go to GreetingServlet dot java. We will go to GreetingServlet dot java.
Highlight

String username = request.getParameter("userName");

String password = request.getParameter("password");


We get the Username and Password from the request using getParameter method.
Next we will see the code for JDBC connection.
Highlight Connection con = null;

PreparedStatement stmt = null;

ResultSet rs = null;


We have initialized the Connection object, PreparedStatement object and Resultset object to null.
Highlight Class.forName("com.mysql.jdbc.Driver"); Then we register the driver in our program.
Highlight con = DriverManager.getConnection("jdbc:mysql:

//127.0.0.1:3306/library", "root", "root");

Then we create a connection to the database.
Highlight stmt = con.prepareStatement("select * from Users

where username = ? and password = ?");

Here, we execute the prepareStatement method on the Connection object.


We give the query to get the user details from Users table.


We check if username and password is same as that which is entered in the form.

Highlight question mark. The question mark denotes each field in the database.
Highlight stmt.setString(1, username);

stmt.setString(2, password);


To supply values in place of question mark, we execute the setString method.


We do this using the PreparedStatement object.

Highlight rs=stmt.executeQuery(); Then we execute the executeQuery method on the ResultSet object.
Highlight RequestDispatcher view = request.getRequestDispatcher("successGreeting.jsp");

view.forward(request, response);

return;

}


For successful login, we display the successGreeting page.
Highlight RequestDispatcher. For this, we use the RequestDispatcher interface.
Slide 5

RequestDispatcher Interface

* This interface provides the facility of dispatching the request to another resource.
  • The resource can be html, servlet or jsp.


Highlight RequestDispatcher view = request.getRequestDispatcher("successGreeting.jsp"); We use the getRequestDispatcher method on the request to obtain the RequestDispatcher object.
Highlight view.forward(request, response);

return;

}

We then invoke the forward method on RequestDispatcher.

In this way, we forward to successGreeting dot jsp.



Come to successGreeting dot jsp. Let us come to successGreeting dot jsp.
Highlight <p> You have successfully logged in!!!</p> Here, we are displaying the success message You have successfully logged in.
Come back to the browser. Now, come back to the browser.
Again type a username and password that we have not included in the database.
Type Jai as the username and jai123* as the password. So, let me type abc as the username and abc123* as the password.
click on Sign In. Again click on Sign In.
Highlight the error message. We can see that we get the error message on the same page itself.
Now, let us see the code for this.
Go to GreetingServlet dot java. Go to GreetingServlet dot java.
If the validation fails, then we should display the error messages.
Highlight List<String> errorMsgs = new ArrayList<String>(); We have first initialized a List of errorMsgs.
Highlight request.setAttribute("errorMsgs", errorMsgs); We set the variable errorMsgs into the request scope using setAttribute method.
Highlight errorMsgs. Here, errorMsgs is the attribute name.
Highlight String id = null; We have initialized a String variable id to null.
Highlight if(rs.next()){

id= rs.getString(1);


}

Here, we check if the user exists in the database.


If yes, we store the value in the variable id.

Highlight else{

errorMsgs.add("Invalid username or password");

//return;

}

Else, we add the error Invalid username or password to errorMsgs list.
Highlight if (!errorMsgs.isEmpty()) {

RequestDispatcher view = request.getRequestDispatcher("index.jsp");

view.forward(request, response);

return;

}


If the errorMsgs list is not empty, we display the error messages on index dot jsp.


So, we have to redirect to index dot jsp.


We have already seen how to redirect to another page using RequestDispatcher.

Highlight the try catch block. Note that we have included this code in the try catch block to handle exception scenarios.
Now, we will see how to fetch errorMsgs variable in index dot jsp.
Highlight <%

if( request.getAttribute("errorMsgs") != null){

%>


First, we obtain the value of the attribute errorMsgs.

This is done using the getAttribute method on the request.

Highlight <% and %> Note that we have included the Java code within the opening tag less than sign percentage sign and the closing tag percentage sign and greater than sign.
Highlight <%

if( request.getAttribute("errorMsgs") != null){

%>

This block of code is known as scriptlet.


It contains Java code which is executed every time JSP is invoked.

Highlight <div>

<%="Please correct the following errors!!!!" %>

</div>


If the value of errorMsgs is not null, we first display this message.


Please correct the following errors.

Highlight <%

java.util.List<String> errorMsgs = (java.util.List<String>)request.getAttribute("errorMsgs");

for(String errorMsg: errorMsgs){

%>

We then iterate through the errorMsgs.
Highlight <li> <%= errorMsg%></li> We then display the error messages as a list.
This is how we display the error messages on the index dot jsp.
Now, let us see how to add a user into the database.
Before adding a user into the database, we have to create a model for the User table.


Let us see what a model is.

Slide 6

Model

A model :
  • Represents the underlying, logical structure of data in a software application.
  • A Java class with attributes and setters and getters for them.
  • In this way, we can consider model as a whole instead of the individual attributes.


Switch to Netbeans IDE. Switch back to Netbeans IDE.


I have already created the model User dot java.

Highlight package org.spokentutorial.model; Note that we have created this Java class inside the package org dot spokentutorial dot model.
Highlight

private String firstName=" ";

private String surname="";

private int age=0;

private String gender="";

private String email="";

private String username="";

private String password="";

We have the following attributes firstName, surname, age, gender, email, username, password.


We have initialized them to empty values.

Highlight public User(String firstName,

String surname, int age, String gender,

String email,String username,String password){

this.firstName=firstName;

this.surname=surname;

this.age=age;

this.gender=gender;

this.email=email;

this.username=username;

this.password=password;

}

We have a parameterized constructor.
Highlight public User() {


}

We also have the default constructor.
Highlight public String getFirstName() {

return firstName;

}

We define the getFirstName method.
Highlight public void setFirstName(String firstName) {

this.firstName = firstName;

}


We also define the setFirstName method.
Highlight public String getSurname() {

return surname;

}

public void setSurname(String surname) {

this.surname = surname;

}

public void setAge(int age) {

this.age = age;

}

public int getAge() {

return age;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email= email;

}


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;

}


}


Similary we define the set and get methods on each of the attributes.
Come back to the browser. Come back to the browser.
Click on here to register. Now, let us click on here link to register.
Type all the fields in the Registration Page.
Click on Add User. Then click on Add User.
We get a Add User Success Page.
Now, let us see how this is done.
Switch back to the IDE. Switch back to the IDE.
Open AddUserServlet dot java. Open AddUserServlet dot java.
The steps are similar to that we had followed in GreetingServlet dot java.
Highlight String firstName=request.getParameter("firstname").trim();

String surname=request.getParameter("surname").trim();

String age=request.getParameter("age").trim();

String gender=request.getParameter("gender").trim();

String email=request.getParameter("email").trim();

String userName=request.getParameter("username").trim();

String password=request.getParameter("password").trim();


We get the form parameters using the getParameter method.
Highlight User user =new User(firstName,surname,ageUser,

gender,email,userName,password);

We initialize variable user as instance of User Model with individual attributes.
Highlight request.setAttribute("user", user); We set the variable user into the request scope using setAttribute method.
Then we insert the values into the User table.
Highlight RequestDispatcher view = request.getRequestDispatcher("successUser.jsp");

view.forward(request, response);

return;


}


If there are no errors while filling up the form, we forward to the successUser page.
Go to successUser dot jsp. Now, let us come to successUser dot jsp.
Highlight <%@page import="org.spokentutorial.model.User"%> First, we have imported User dot java.


This line of code is called directive in JSP.

Highlight <%@ and %> A JSP directive starts with opening tag less than sign percentage sign and at the rate sign and ends with percentage sign and greater than sign.
Highlight <%@page import="org.spokentutorial.model.User"%> This one is a page directive.


The page directive contains a list of all imported packages.

Highlight <%User user = (User)request.getAttribute("user");

%>

We get the value of the attribute user and store it as the User object.
Highlight Your request to add <i> <%=user.getUsername() %></i> was successful. We have the success message here.
Highlight <%=user.getUsername() %> Here, we have retrieved the Username.

We have used the getUsername() method on the request object.

We have done this using scriptlet tags.
Now, let us come back to the browser.
We will try to add a user already present in the database.
Type the fields for nisha again. I will add nisha again.
Highlight Duplicate entry for key username. We can see that we get the error message Duplicate entry for key username.
Let us register for a user once again.
Show the registration form filled up. Here, I have filled up the form now.
Highlight the Age textbox. I have created a mistake in the Age field.
I have typed ab instead of a valid number.
Click on Add User. Now, click on Add User.
Highlight the error message. We see we get the error message The age must be a positive integer.
Switch back to the IDE. Now, let us see how this is done.


Switch back to the IDE.

Open AddUserServlet dot java. Open AddUserServlet dot java.
Highlight List<String> errorMsgs=new ArrayList<String>(); Here also, we have created a list for errorMsgs.
Highlight request.setAttribute("errorMsgs", errorMsgs); Then we set the variable errorMsgs into the request scope using setAttribute method.
Highlight int ageUser=-1; Here, we have declared ageUser of type integer.
Highlight try {

ageUser=Integer.parseInt(age);

}


Inside the try catch block we have used parseInt method.


This will return an integer, given a string representation of number as input.

Highlight catch(NumberFormatException nfe) {

errorMsgs.add("The age must be a positive integer");

}


So here we validate that the age field contains a valid positive integer.


If the validation fails, then we add error message to errorMsgs attribute.

Highlight if(firstName.length()==0) {

errorMsgs.add("Please enter the first name");

}

if(surname.length()==0) {

errorMsgs.add("Please enter the surname");

}

if(age.length()==0) {

errorMsgs.add("Please enter the age");

}

if(userName.length()==0) {

errorMsgs.add("Please enter the username");

}

if(password.length()==0) {

errorMsgs.add("Please enter the password");

}


Similarly, we have to validate that all the other fields too have valid data.
Highlight if(!errorMsgs.isEmpty()) {

RequestDispatcher view = request.getRequestDispatcher("addUser.jsp");

view.forward(request, response);

return;

}


If there are no errors, then we will display the errorMsgs on addUser dot jsp.

We have already seen how to do this using the RequestDispatcher.

Now, let us come to the addUser dot jsp.
Highlight <%@page import="org.spokentutorial.model.User"%> Here also, we have imported User dot java.
Highlight <%

User user = new User();


Inside the scriptlet tags we have created an object of type User.
Highlight if(request.getAttribute("errorMsgs") != null){ Then we get the value of attribute errorMsgs using getAttribute method.
Highlight if(request.getAttribute("errorMsgs") != null){ We check if this value is null.
Highlight java.util.List<String> errorMsgs = (java.util.List<String>)request.getAttribute("errorMsgs");

for(String errorMsg: errorMsgs){

%>

<li> <%= errorMsg%></li>

<%


If yes, we display the error message just as we had done for index dot jsp.
Highlight user = (User)request.getAttribute("user");


If not, we will get the value of the attribute user from request using the User model.
Then we have the form.
Highlight the form tag. The form tag has action as AddUserServlet and method as POST.
Highlight First Name:<input type='text' name='firstname' value="<%=user.getFirstName()%>"> The first field is First Name of input type as text ,name as firstName and value as user dot getFirstName.


Here, we are initializing the value of firstName to empty string.

Highlight the other fields. Similarly you have to do for other fields.
Highlight the submit button. We also have a button of type submit and name Add User.
Highlight the link to index dot jsp. We also have a link to index dot jsp which allows you to log out.
This is how we validate the fields in addUser.jsp.
You can try out different errors on the Add User page.
Show in database We can see that the user nisha has been added to the database.
Slide 6

Summary

Let us summarize.

In this tutorial we have learnt:

  • Database connectivity
  • Field validation


Slide 7

About slide


Watch the video available at the following link.
  • It summarizes the Spoken Tutorial Project
  • If you do not have good bandwidth you can download and watch it


Slide 8

About slide

The Spoken Tutorial Project Team
  • Conducts workshops using spoken tutorials
  • Gives certificates for those who pass an online test
  • For more details please write to contact at spoken hyphen tutorial dot org


Slide 9

Acknowledgement

Spoken Tutorial Project is a part of the Talk to a Teacher Project


Slide 10

Contributor Slide

The Library Management System has been contributed by a leading software MNC, through their Corporate Social Responsibility Programme.


They have also validated the content for this spoken tutorial.


This is Arya Ratish from IIT Bombay signing off.


Thank you for joining.

Contributors and Content Editors

Arya Ratish, Nancyvarkey