NEWS: Total Picture Views: 147068 | Total Article Views: 155678 | Top 5 Most Popular Article: 1. Am I Stuck Algorithm with Becker Robot | 2. How to read a JSON and work with it | 3. PickUpThings with Becker Robot | 4. Encrypted Data GUI (Download .Zip) | 5. Create Wall and Things with Becker

Website using MVC Java

Description:

In this example I will be showing a website I did using the MVC model.

Code:

/***** content.xml *****/
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/dental"/>

/***** web.xml ******/
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>Validate</servlet-name>
        <servlet-class>web.Validate</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Submit</servlet-name>
        <servlet-class>web.Submit</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Validate</servlet-name>
        <url-pattern>/Validate</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Submit</servlet-name>
        <url-pattern>/Submit</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>mylogin.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>dentist</param-name>
        <param-value>Dr.Jean-Mathieu Emond</param-value>
    </context-param>
    <init-param>
        <param-name>url</param-name>
        <param-value>hello</param-value>
    </init-param>
</web-app>

/**** confirm.jsp ****/
<%-- 
    Document   : confirm.jsp
    Created on : Dec 11, 2014, 3:08:51 PM
    Author     : Jean-Mathieu
--%>

<%@page import="java.util.Date"%>
<%@page import="java.text.DateFormat"%>
<%@page import="java.util.Locale"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>
<%
Locale locale = request.getLocale( );
String date = DateFormat.getDateTimeInstance(
                              DateFormat.FULL, 
                              DateFormat.SHORT, 
                              locale).format(new Date( ));

String path=application.getRealPath("header.jsp");
%>

        <h1>Thank you!</h1>
        <p>Your dental history is submitted successfully</p>
        <p><% out.println(date);%></p>
    </body>
</html>

/***** error.jsp ******/
<%-- 
    Document   : error
    Created on : Dec 11, 2014, 4:18:06 PM
    Author     : Jean-Mathieu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>
        <h1>We could not insert your data. Please try again.</h1>
    </body>
</html>


/**** header.jsp *****/
<%-- 
    Document   : header.jsp
    Created on : Dec 11, 2014, 3:08:32 PM
    Author     : Jean-Mathieu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    String dentist =application.getInitParameter("dentist"); 
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Dentist</title>
    </head>
    <body>
        <h1>My Dental Park</h1>
        <h3><% out.println(dentist); %></h3>

/***** historyFrm.jsp ******/
<%-- 
    Document   : historyFrm
    Created on : Dec 11, 2014, 3:08:42 PM
    Author     : Jean-Mathieu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>
        <form method="post" action="Submit">
            <h3>Select yes or no to indicate if you have had any of the following</h3>
            Name: <input type="text" name="name" required=""><br>
            Bad breath <input type="radio" name="breath" value="Yes" required=""> Yes <input type="radio" name="breath" value="No" required=""> No<br>
            Bleeding gums <input type="radio" name="gums" value="Yes" required=""> Yes <input type="radio" name="gums" value="No" required=""> No<br>
            Loose teeth or broken filling <input type="radio" name="teeth" value="Yes" required=""> Yes <input type="radio" name="teeth" value="No" required=""> No<br>
            Burning sensation on tonque <input type="radio" name="tonque" value="Yes" required=""> Yes <input type="radio" name="tonque" value="No" required=""> No<br>
            Sensitivity when bitting <input type="radio" name="bitting" value="Yes" required=""> Yes <input type="radio" name="bitting" value="No" required=""> No<br>
            How often do you floss? <select name="floss"  required="">
                                        <option></option>
                                        <option value="daily">Once a day</option>
                                        <option value="daily2">Twice a day</option>
                                        <option value="weekly">Once a week</option>
                                    </select><br>
           <button type="submit">Submit</button>
       </form>
    </body>
</html>


/****** mylogin.jsp *****/
<%-- 
    Document   : mylogin.jsp
    Created on : Dec 11, 2014, 3:08:22 PM
    Author     : Jean-Mathieu
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>
<form action="Validate" method="post">
            <label>Username: </label>
            <input type="text" id="username" name="username">
            <br>
            <label>Password: </label>
            <input type="password" id="password" name="password">
            <br>
            <button type="submit">Login</button>
        </form> 
    </body>
</html>

/***** business/History.java ****/
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package business;

/**
 *
 * @author Jean-Mathieu
 */
public class History {
    private String bitting;
    private String bleeding;
    private String breath;
    private String floss;
    private String name;
    private String teeth;
    private String tonque;
    public History() {
    }
    
    public History(String bitting,String bleeding,String breath, String floss,String name,String teeth,String tonque){
        this.bitting = bitting;
        this.bleeding = bleeding;
        this.breath = breath;
        this.floss = floss;
        this.name = name;
        this.teeth = teeth;
        this.tonque = tonque;
    }

    public String getBitting() {
        return bitting;
    }

    public void setBitting(String bitting) {
        this.bitting = bitting;
    }

    public String getBleeding() {
        return bleeding;
    }

    public void setBleeding(String bleeding) {
        this.bleeding = bleeding;
    }

    public String getBreath() {
        return breath;
    }

    public void setBreath(String breath) {
        this.breath = breath;
    }

    public String getFloss() {
        return floss;
    }

    public void setFloss(String floss) {
        this.floss = floss;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTeeth() {
        return teeth;
    }

    public void setTeeth(String teeth) {
        this.teeth = teeth;
    }

    public String getTonque() {
        return tonque;
    }

    public void setTonque(String tonque) {
        this.tonque = tonque;
    }

}

/******* data/ConnControl.java *******/
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package data;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Jean-Mathieu
 */
public class ConnControl {
    public ConnControl() {
    }
    public Connection connect() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
        Connection connection = null;
        //Define the connection data 
        String driverName="com.mysql.jdbc.Driver";
        String dbUrl="jdbc:mysql://localhost:3306/mydb";
        String userName="root";
        String password="sesame";
        
        //open connection
        try {
            Class.forName(driverName).newInstance();
            connection = DriverManager.getConnection(dbUrl, userName, password);
            return connection;
        } catch (SQLException e) {
            return null;
        }
            
    }
    
    public void freeConnection(Connection con) throws SQLException{
        if (con!=null){
            con.close();
        }
        
    }
    
}

/***** data/DBUtil.java  ******/
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package data;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Jean-Mathieu
 */
public class DBUtil {
    public static void closeStatement(Statement s) throws SQLException{
        if(s!=null)
            s.close();
    }
    
    public static void closePreparedStatement(PreparedStatement ps) throws SQLException{
        if(ps!=null)
            ps.close();
    }
    
    public static void closeStatement(ResultSet r) throws SQLException{
        if(r!=null)
            r.close();
    }
}

/******* data/HistoryDB.java *******/
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package data;

import business.History;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Jean-Mathieu
 */
public class HistoryDB {

    private Connection connection;
    private Statement stm;
    boolean connect;
    private ResultSet res;
    private PreparedStatement ps;

    public int insert(History h) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        Connection myCon = null;
        ConnControl conManager = null;
        PreparedStatement ps = null;
        try {
            conManager = new ConnControl();
            myCon = conManager.connect();
            
           

            String pstm = "INSERT INTO history (name, breath, bleeding, teeth, tonque, biting, floss) VALUES (?,?,?,?,?,?,?);";
            ps = myCon.prepareStatement(pstm);

            // set parameters
            ps.setString(1, h.getName());
            ps.setString(2, h.getBreath());
            ps.setString(3, h.getBleeding());
            ps.setString(4, h.getTeeth());
            ps.setString(5, h.getTonque());
            ps.setString(6, h.getBitting());
            ps.setString(7, h.getFloss());
            
            System.out.println("PS: " + ps);
            return ps.executeUpdate();

        } catch (SQLException e) {
            return 0;
        } finally {
            DBUtil.closePreparedStatement(ps);
            conManager.freeConnection(myCon);
        }

    }     
}


/***** web/Submit.java ****/
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import business.History;
import data.HistoryDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jean-Mathieu
 */
public class Submit extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String bitting = request.getParameter("bitting");
        String bleeding = request.getParameter("gums");
        String breath = request.getParameter("breath");
        String floss = request.getParameter("floss");
        String name = request.getParameter("name");
        String teeth = request.getParameter("teeth");
        String tonque = request.getParameter("tonque");
        
        History h = new History(bitting, bleeding, breath, floss, name, teeth, tonque);
        
        //request.setAttribute("history", h);
        
        HistoryDB myHistoryDB = new HistoryDB();
        
        try {
            if(myHistoryDB.insert(h) >= 1){
                response.sendRedirect("confirm.jsp");
            }else{
                response.sendRedirect("error.jsp");
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Submit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Submit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Submit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Submit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

/**** web/Validate.java *****/
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

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

/**
 *
 * @author Jean-Mathieu
 */
public class Validate extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        if(username.equals("srv") && password.equals("Sheridan")){
            response.sendRedirect("historyFrm.jsp");
        }else{
            response.sendRedirect("mylogin.jsp");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}






Attachments:

Tags: JSTL MySQL Session MVC JSP

Total Views: 1170

My name is Jean-Mathieu

I created this website so other people could enjoy finding useful stuff easier. If you have any question do not hesitate to contact me.

jean8mathieuCreated on 01/07/15


affiliate_link

Disclosure: We are a website that needs compensation to operate like any other website on the internet.
We may receive consideration for our reviews but we are totally unbiased and do not accept paid reviews or fake reviews claiming to be something they are not.