Java Servlet and JSP Web Application 2

Glassfish Configuration

1. Admin Console: http://localhost:4848/common/index.jsf
2. Resources->JDBC->JDBC Connection Pools
3. Add a pool called MySQLPool

  • Resource Type: javax.sql.DataSource
  • Datasource classname: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
  • Additional Property: your server name, port number, database name, user name, password.

4. Resource->JDBC->JDBC Resources

5. Add JNDI: jdbc/MySQLPool

6. copy mysql-connector-java-5.1.13-bin.jar to your glassfish lib, or on linux create a  symbolic link (shortcut in MS SQL Widnows)  from the glasshfish lib directory to mysql-connector-java-5.1.13-bin.jar

7. Restart Glassfish, and test JNDI.

Netbean IDE

Just create a web application project (called any name. I called it ServletTest) and make sure choose the Glassfish as your server and Java EE 6 Web as Java EE Version.

All the Servlet java code will be created in src->java folder.

All the JSP and HTML code will be created in web folder.

The Design Pattern (MVC)

  1. All the database interactions are coded in Java Servlet 3.0 by using JNDI “jdbc/MySQLPool’, ds (javax.sql.DataSource), conn ( java.sql.Connection), stmt(java.sql.Statement ), rs(java.sql.ResultSet). All these are classified as Model (Command / Data Bean).
  2. Using request.setAttribute(“rs”, rs) to set attributes in a session and the attributes are available through out the session (classifed as View Bean). Forward the request to other servlets or jsps using requestDispatcher and make the attributes available there.
  3. All the GUI (View) are coded in JSP, and using rs.getString(?) to obtain the data from the servlet session attributes. The  form actions are done through another Java Servlet (Control). The Servlet can are obtained the data from JSP by using request.getParameter(“para”).

Function: Inventory List

This function include two programs:

ListServlet.java: connect to MySQL DB to retrieve all items and activate List.jsp.

List.jsp: render rowsets from ListServlet.java onto web page:

Try it: http://localhost:8080/ServletTest/ListServlet

Inventory Item List

Inventory Item List

ListServlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.InitialContext;
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 javax.sql.DataSource;

@WebServlet(name = "ListServlet", urlPatterns = {"/ListServlet"})
    /**
     * 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 {
        try {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("jdbc/MySQLPool");

            Connection conn = ds.getConnection();
            Statement stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery("select * from item");
            request.setAttribute("rs", rs);
            // activate List.jsp
            getServletContext().getRequestDispatcher("/List.jsp").
            forward(request, response);

            stmt.close();
            conn.close();

        } catch (Exception e) {
            //e.printStackTrace();
        } finally {            
        }
    }

    // <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>
}

List.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="rs" scope="request" type="java.sql.ResultSet" />
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Inventory - List</title>
    </head>
     <body style="font-family:verdana;font-size:10pt;">
        <table cellpadding="5" style="font-family:verdana;font-size:10pt;">
          <tr>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th>Stock</th>
            <th></th>
            <th></th>
          </tr>
           <%
             while(rs.next()) {
           %>
           <tr>
             <td><%= rs.getString(2) %></td>
             <td><%= rs.getString(3) %></td>
             <td><%= rs.getString(4) %></td>
             <td><%= rs.getString(5) %></td>
             <td>
               <a href="DeleteServlet?id=<%= rs.getString(1) %>">
                 Delete
               </a>
             </td>
             <td>
               <a href="EditServlet?id=<%= rs.getString(1) %>">
                 Edit
               </a>
             </td>
           </tr>
           <%
             }
           %>
         </table>
         <a href="New.html">New Item</a>
        </body>
</html>


About henry416
I am a computer technology explorer and an university student based on Toronto. If you have any question, please feel free to discuss and comment here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.