Developing Simple MVC Web Application using JSP Servlet


MVC Design Pattern

MVC stands for Model View and Controller.It is a design pattern that separates the concerns. It is suitable for large applications.

Model - States of application ie domain specific representation of data. It also contains business logic
View - Use for user interaction, and render the model
Controller - Control request and response and responsible for communication between model and view

we are going to create a simple CRUD (Create Read Update Delete) MVC Web Application for Student using Jsp, Servlet and MySQL.

Step 1 : Create new database "testDb" .


create database testDb;
use testDb;
grant all on testDb.* to 'root'@'localhost' identified by ''; 

CREATE TABLE testDb.`student` (
`studentId` int(11) NOT NULL AUTO_INCREMENT,
`studentName` varchar(100) DEFAULT NULL,
`studentAddress` varchar(100) DEFAULT NULL,
PRIMARY KEY (`studentId`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
You can also use IDE such as XAMP, WAMP, SQlyog etc to create database and table.

Step 2 : Create new Dynamic Web Project named "SimpleMVCTut" using eclipse


Step 3 : Create four package

com.stosh.controller
com.stosh.model
com.stosh.dao
com.stosh.utils

Step 4 : Create studentForm.jsp page

 <%@page import="com.stosh.model.Student"%>  
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Insert title here</title>  
 </head>  
 <body>  
 <%  
 Student student = (Student)request.getAttribute("student");  
 if(student==null){  
      student = new Student();  
      student.setStudentId(0);  
      student.setStudentName("");  
      student.setStudentAddress("");  
 }  
 %>  
      <h1>Student Form</h1>  
      <form action="StudentServlet" method="post">  
      <input type="hidden" value="<%=student.getStudentId() %>" name="studentId">  
      Student Name <input type="text" value="<%=student.getStudentName() %>" name="studentName">  
      Student Address <input type="text" value="<%=student.getStudentAddress() %>" name="studentAddress">  
      <input type="submit" value="<%=student.getStudentId()==0?"Add":"Update" %>" name="<%=student.getStudentId()==0?"add":"update" %>">  
      </form>  
 </body>  
 </html>  

Step 5 : Create servlet for controller called "StudentServlet" in com.stosh.controller package

 package com.stosh.controller;  
 import java.io.IOException;  
 import javax.servlet.RequestDispatcher;  
 import javax.servlet.ServletException;  
 import javax.servlet.annotation.WebServlet;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import com.stosh.dao.StudentDao;  
 import com.stosh.model.Student;  
 @WebServlet("/StudentServlet")  
 public class StudentServlet extends HttpServlet {  
      private static final long serialVersionUID = 1L;  
      public StudentServlet() {  
           super();  
      }  
      protected void doGet(HttpServletRequest request,  
                HttpServletResponse response) throws ServletException, IOException {  
           doPost(request, response);  
      }  
      protected void doPost(HttpServletRequest request,  
                HttpServletResponse response) throws ServletException, IOException {  
           try {  
                StudentDao sd = new StudentDao();  
                Student student = new Student();  
                if(request.getParameter("studentId")!=null)  
                student.setStudentId(Integer.parseInt(request.getParameter("studentId")));  
                student.setStudentName(request.getParameter("studentName"));  
                student.setStudentAddress(request.getParameter("studentAddress"));  
                if (request.getParameter("add") != null) {  
                     sd.insertStudent(student);  
                     request.setAttribute("studentList", sd.getStudentList());  
                } else if (request.getParameter("update") != null) {  
                     sd.updateStudent(student);  
                     request.setAttribute("studentList", sd.getStudentList());  
                } else if (request.getParameter("studentIdForDelete") != null) {  
                     sd.deleteStudent(Integer.parseInt(request  
                               .getParameter("studentIdForDelete")));  
                     request.setAttribute("studentList", sd.getStudentList());  
                } else if (request.getParameter("studentIdForEdit") != null) {  
                     student = sd.getStudent(Integer.parseInt(request  
                               .getParameter("studentIdForEdit")));  
                     request.setAttribute("student", student);  
                     RequestDispatcher rs = request  
                               .getRequestDispatcher("studentForm.jsp");  
                     rs.forward(request, response);  
                     return;  
                }  
                RequestDispatcher rs = request.getRequestDispatcher("studentList.jsp");  
                rs.forward(request, response);  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
 }  

Step 6 : Create class Student with all of its properties that hold information in com.stosh.model package

 package com.stosh.model;  
 public class Student {  
      private int studentId;  
      private String studentName;  
      private String studentAddress;  
      public int getStudentId() {  
           return studentId;  
      }  
      public void setStudentId(int studentId) {  
           this.studentId = studentId;  
      }  
      public String getStudentName() {  
           return studentName;  
      }  
      public void setStudentName(String studentName) {  
           this.studentName = studentName;  
      }  
      public String getStudentAddress() {  
           return studentAddress;  
      }  
      public void setStudentAddress(String studentAddress) {  
           this.studentAddress = studentAddress;  
      }  
 }  

Step 7 : Create class DBConnection in com.info.utils package. It is used to establish the connection with database

 package com.stosh.utils;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 public class DBConnection {  
      public static Connection getConnection(){  
           try{  
                Class.forName("com.mysql.jdbc.Driver");  
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDb", "root", "");  
                return con;  
           }catch(Exception e){  
                e.printStackTrace();  
           }  
           return null;  
      }       
 }  

Step 8 : Create class StudentDao in com.stosh.dao package. Dao means "Data Access Object" and exist to provide communication with database

 package com.stosh.dao;  
 import java.sql.Connection;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.util.ArrayList;  
 import java.util.List;  
 import com.stosh.model.Student;  
 import com.stosh.utils.DBConnection;  
 public class StudentDao {  

        Connection con;
 
 public StudentDao(){
  con = DBConnection.getConnection();
 }

      public void insertStudent(Student student) {  
           try {               
                String qry = "insert into student(studentName, studentAddress) values(?,?)";  
                PreparedStatement pst = con.prepareStatement(qry);  
                pst.setString(1, student.getStudentName());  
                pst.setString(2, student.getStudentAddress());  
                pst.execute();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
      public List<Student> getStudentList() {  
           try {  
                List<Student> studentList = new ArrayList<Student>();  
                String qry = "select * from student";  
                PreparedStatement pst = con.prepareStatement(qry);  
                ResultSet rs = pst.executeQuery();  
                while (rs.next()) {  
                     Student student = new Student();  
                     student.setStudentId(rs.getInt("studentId"));  
                     student.setStudentName(rs.getString("studentName"));  
                     student.setStudentAddress(rs.getString("studentAddress"));  
                     studentList.add(student);  
                }  
                return studentList;  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           return null;  
      }  
      public Student getStudent(int studentId) {  
           try {  
                String qry = "Select * from student where studentId=?";  
                PreparedStatement pst = con.prepareStatement(qry);  
                pst.setInt(1, studentId);  
                ResultSet rs = pst.executeQuery();  
                while (rs.next()) {  
                     Student student = new Student();  
                     student.setStudentId(rs.getInt("studentId"));  
                     student.setStudentName(rs.getString("studentName"));  
                     student.setStudentAddress(rs.getString("studentAddress"));  
                     return student;  
                }  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           return null;  
      }  
      public void deleteStudent(int studentId) {  
           try {  
                String qry = "delete from student where studentId=?";  
                PreparedStatement pst = con.prepareStatement(qry);  
                pst.setInt(1, studentId);  
                pst.executeUpdate();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
      public void updateStudent(Student student) {  
           try {  
                String qry = "update student set studentName=?, studentAddress=? where studentId=?";  
                PreparedStatement pst = con.prepareStatement(qry);  
                pst.setString(1, student.getStudentName());  
                pst.setString(2, student.getStudentAddress());  
                pst.setInt(3, student.getStudentId());  
                pst.executeUpdate();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
 }  

Step 9 : Create studentList.jsp page

 <%@page import="java.util.*"%>  
 <%@page import="com.stosh.model.Student"%>  
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Insert title here</title>  
 </head>  
 <body>  
           <h1>Student List</h1>  
           <%  
           List<Student> studentList = (ArrayList<Student>)request.getAttribute("studentList");  
           %>  
           <table>  
           <tr>  
           <td>Id</td>  
           <td>Student Name</td>  
           <td>Student Address</td>  
           <td>Edit</td>  
           <td>Delete</td>  
           </tr>  
           <% for(Student student:studentList){ %>  
           <tr>  
           <td><%= student.getStudentId()%></td>  
           <td><%= student.getStudentName()%></td>  
           <td><%= student.getStudentAddress()%></td>  
           <td><a href="StudentServlet?studentIdForEdit=<%=student.getStudentId()%>">Edit</a></td>  
           <td><a href="StudentServlet?studentIdForDelete=<%=student.getStudentId()%>">Delete</a></td>  
           </tr>  
           <%} %>  
           </table>  
 </body>  
 </html>  

Step 10 : Finally the project directory structure will be


Step 11 : Run the application.

Output
Note: Like our facebook page to get updated of free classes and tutorials.