Thursday, May 3, 2012

MVC application in JSP


Model View Controller is a architectural design pattern.
  • Model is business logic.
  • View is user interface.
  • Controller handles the user input.
Why MVC?
  • View is free of any business logic. So looks simple and readable.
  • Business logic within the Model can be reused for more than one views.

This is the small application using MVC architecture.The following are what I have done for this application.
  • Writing an HTML form page (index.jsp)
  • Creating a Servlet controller - (Controller.java)
  • Creating the Model) -(StudentDetails.java)
  • Creating an XML deployment descriptor
  • Creating an JSP View - (response.jsp)
The web application is a Student marks entered application. These are considered here:
  • Students marks entered in the following way. Student Name (StudentName loaded in ComboBox), Grade (1-13 ComboBox), Subject, Marks
  • User can enter these value and click "Add".
  • Here all these fields are mandatory fields and marks can not be more than 100.
  • System would validate those fields and show it in the response page.
Below is the users input screen.


After fill this form and click "Add", the following page will be display.


Bellow is error pages.

  1. This error page will be display when we didn't fill all fields.



2. This error page will be display when we enter the marks in more than 100 or less than 0



3. This error page will be display when we enter the marks in text.


The HTML form page
This is the simple HTML form (index.jsp).

<%-- 
    Document   : index
    Created on : May 2, 2012, 2:01:45 PM
    Author     : Vanaja
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        
    </head>
    <body>
        <center>
        <h1>Add Student Marks</h1>
        <form action="Controller" method="Post" > 
            <table border="0">
                <tbody>
                    <tr>
                        <td width="100">Student Name:</td>
                        <td><select name="studentName">
                                <option>Lukshica</option>
                                <option>Mayooran</option>
                                <option>Vijay</option>
                                <option>Nilash</option>
                                <option>Thenu</option>
                                <option>Ramanan</option>
                                <option>Tharo</option>
                                <option>Keerthika</option>
                                <option>Meera</option>
                            </select></td>
                    </tr>
                    <tr>
                        <td> Grade:</td>
                        <td><select name="grade">
                                <option>1</option>
                                <option>2</option>
                                <option>3</option>
                                <option>4</option>
                                <option>5</option>
                                <option>6</option>
                                <option>7</option>
                                <option>8</option>
                                <option>9</option>
                                <option>10</option>
                                <option>11</option>
                                <option>12</option>
                                <option>13</option>
                            </select></td>
                    </tr>
                    <tr>
                        <td>Subject:</td>
                        <td><input type="text" name="subject"/></td>
                    </tr>
                    <tr>
                        <td> Marks:</td>
                        <td><input type="text" name="marks"/></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="Add" name="Add" /></td>
                        <td><input type="reset" value="Reset" name="Reset" /></td>
                    </tr>
                </tbody>
            </table> 
            </center>
        </form>
    </body>
</html>

The Deployment Descriptor
First we must create the deployment descriptor which is web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>Controller</servlet-name>
    <servlet-class>ControllerPackage.Controller</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>Controller</servlet-name>
    <url-pattern>/Controller</url-pattern>
  </servlet-mapping>
</web-app>

Here <servlet> tag used to register servlets within this webapp.
<servlet-mapping> tag use to map the url with the servlet.

The Controller Servlet and Model class

Now we must create the model class that will be used by the controller.
Model class:( StudentDetails.java )

package Student;
/**
 *
 * @author Vanaja
 */
public class StudentDetails {
   String studentName;
   String grade;
   String subject;
   int marks;


    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public int getMarks() {
        return marks;
    }
    public void setMarks(int marks) {
        this.marks = marks;
    }
}


Controller class: ( Controller.java)

package ControllerPackage;


import Student.*;
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;
/**
 *
 * @author Vanaja
 */
@WebServlet(name = "Controller", urlPatterns = {"/Controller"})
public class Controller extends HttpServlet {  
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }
  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String studentName;
        String grade;
        String subject;
        String marks;
        
        studentName=request.getParameter("studentName");
        grade=request.getParameter("grade");
        subject=request.getParameter("subject");
        marks=request.getParameter("marks");
        
        Validateclass v=new Validateclass(); 
        boolean result1=v.checkFields(subject,marks);   
         
        if(result1){ 


            boolean result2=v.is_int(marks);
            if(result2){ 


                int marks1=Integer.parseInt(marks);
                boolean result3=v.checkMarks(marks1);
                if(result3){
                    
                    StudentDetails sd=v.setDetails(studentName,grade,subject,marks1);
                    request.setAttribute("Student",sd);
                    RequestDispatcher dispatcher = request.getRequestDispatcher("response.jsp");
                    dispatcher.forward(request,response); 
                }
                else
                    response.sendRedirect("error2.jsp"); 
            }
            else
               response.sendRedirect("error3.jsp"); 
        }
        else
            response.sendRedirect("error.jsp");
    }
    
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


Now we want to create Validate class.
Validate class: (ValidateClass.java)

package ControllerPackage;


import Student.StudentDetails;
/**
 *
 * @author Vanaja
 */
public class Validateclass {
    
    public boolean checkFields(String subject, String marks)
    {
        if("".equals(subject.trim()) || subject==null || "".equals(marks.trim()) || marks==null )
            return false;
        return true;
    }
    
    public boolean checkMarks(int marks)
    {
        if( marks > 100 || marks < 0 )
            return false;
        return true;
    }
    
    public boolean is_int(String marks)
    {
        for (int i = 0 ; i < marks.length() ; i++) { 
              if((marks.charAt(i) < 48 ) || (marks.charAt(i) > 57)) 
                     return false ;
               } 
               return true;
    }
           
    public StudentDetails setDetails( String studentName,String grade,String subject,int marks)
    {
        StudentDetails sd=new StudentDetails();
        sd.setStudentName(studentName);
        sd.setSubject(subject);
        sd.setGrade(grade);
        sd.setMarks(marks);
        return sd;
    }
}

The JSP View
Now we create must create the JSP view page that will display the successfully added student marks (response.jsp).

<jsp:useBean id="Student" scope="session" class="Student.StudentDetails" />


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <center>
        <h2>You successfully add the marks </h2>
       <table border="0">
<tr>
<td width="100">Student Name:</td>
        <td><jsp:getProperty name="Student" property="studentName" /></td>
        </tr> 
        
        <tr>
        <td>Grade:</td>
        <td><jsp:getProperty name="Student" property="grade" /></td>
        </tr>
        
        <tr>
        <td>Subject:</td>
        <td><jsp:getProperty name="Student" property="subject" /></td>
        </tr>
        
        <tr>
        <td>Marks:</td>
        <td><jsp:getProperty name="Student" property="marks" /></td>
</tr> 
    </table>
    </center>  
        
    </body>
</html>

Bean has the setter and getter methods.
-the setter: used to note the value in a certain property.
-the getter: used to show the value of a certain property.

The advantage of using getters and setters is that an object of the class is always responsible for its values. With the setter, the class can control the values it is supposed to write down in its property. In certain cases, the class can refuse to write down an illegal value. The same goes for the getters  : the class can decide to show the value in a certain format.



No comments:

Post a Comment