Order Entry System 3: JSP, Servlet, Session Bean, JQuery

This is the final part of the series:

OrderSaveServlet.java

The OrderSaveServlet is the controller to save the CustomerBean from the session memory to a table “customer” in MySQL database via JNDI connection pool on GlassFish Application Server. It obtains the generated customer id from the database. Then, it saves the OrderBean and customer id into a another table “orders” in the database, and obtains the order id generated by the database insertion. It finally generates a html page to display the order number back to user. And our Order Entry Web System will end here.

import java.io.IOException;
import java.io.PrintWriter;
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.servlet.http.HttpSession;
import javax.sql.DataSource;
import mybean.CustomerBean;
import mybean.OrderBean;

@WebServlet(name = "OrderSaveServlet", urlPatterns = {"/OrderSaveServlet"})
public class OrderSaveServlet 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");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            CustomerBean CustomerBean = (CustomerBean)session.getAttribute("CustomerBean");

            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("jdbc/MySQLPool");

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

            String query1 = "INSERT INTO customer (name, address, tel, email) VALUES ( '" +
                    CustomerBean.getName() +"','"+
                    CustomerBean.getAddress()+"','"+
                    CustomerBean.getTel()+"','"+
                    CustomerBean.getEmail()+"') ";

            stmt.executeUpdate(query1);

            int customerid = -1;

//            ResultSet rs = stmt.getGeneratedKeys();
            ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");

            if (rs.next()) {
                customerid = rs.getInt(1);
            } else {

                // throw an exception from here
            }

            OrderBean OrderBean = (OrderBean)session.getAttribute("OrderBean");

            String query2 = "INSERT INTO orders (itemid, saleprice, gst, qty, customerid) VALUES ( " +
                    OrderBean.getItemid() +","+
                    OrderBean.getSaleprice()+","+
                    OrderBean.getGst()+","+
                    OrderBean.getQty()+","+
                    customerid+") ";

            stmt.executeUpdate(query2);

            int orderid = -1;

//            ResultSet rs = stmt.getGeneratedKeys();
            rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");

            if (rs.next()) {
                orderid = rs.getInt(1);
            } else {

                // throw an exception from here
            }

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet OrderSaveServlet</title>");            
            out.println("</head>");
            out.println("<body>");
//            out.println("<p>query: " + query2 + "</p>");
            out.println("<h1>Thank you. Your Order Number: " + orderid + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } catch (Exception e) {
          //  e.printStackTrace();
        } finally {                        
            out.close();
        }
    }

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

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