Jsp servlet with data base communication we are going to learn in this tutorial.Basically we are just taking values from JSP controls and passing it to the controller we call them servlet.
These servlet will pass this to the DAO layer.Dao layer in very simple terms implies a java file which contains method to communicate with databases like oracle,h2,mysql.
This tutorial will teach you
  1. How to take input from user using JSP and pass it to servlet.
  2. How to extract values from request object in servlet.
  3. How to save the user input in the database.
  4. How to display all saved records on jsp.

 

STEP1: How to take input from user using JSP and pass it to servlet.

Have a look at the below line of code.

AppointementController is the mapped url which takes care of data you passed in the text box with input name=”patientName” and name=”patientAge”.

index.jsp

STEP2: How to extract values from request object in servlet.

How to get value from text box with name=”patientName” in controller’s POST method.
As we have learned to get value passed in textbox we use instance of HttpServletRequest.
 
To retrieve values from html textbox we use request.getParameter(“patientName”)
to convert patientAge from string to integer we used wrapper method Integer.parseInt().
 
We created Patient object and set name and age to it and pass it to save() method of PatientDao.

 

AppointmentController.java

Patient.java

STEP3: How to save the user input in the database.

How to save the records in database in AppointementController we retrieve value from jsp page now its time to save values in database.
H2 database we are using for saving records and it does not need any kind of installations we simply import jar of h2 and we are done.
 
Methods i created to save records.
  • geConnection()
    gets the connection to the database.
  • checkIfTablePresent()
    This method first checks if table is created using getMetaData method.
getMetaMethod is provided table name as parameter it checks whether specified table is present using rs.next() .
  • createTable()
simply creates table if table is not present over there
  • save(Patient patientObj)
save method first obtains connection using getConnection().
Creates PreparedStatement reference by executing prepareStatement method pass query as parameter.

 

 

See the detail code of PatientDaoImpl.

PatientDaoImpl.java

STEP4: How to display all saved records on jsp.

 

patientlist.jsp

For further reading i would recommend you to read  http://prourls.co/pLTd

ListControlller.java

If you loved our efforts please support by sharing this article.Please feel free to provide feedback in comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *