Showing posts with label webserver. Show all posts
Showing posts with label webserver. Show all posts

Tuesday, July 19, 2016

Java : Create html table using JSP

Create html table using JSP

Libraries required :
  1.  commons-dbutils
  2. my-sqlconnector
Added to project path and WebContent/lib folder

Below method retreieves data from the DB into List of Maps
public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
      
        try {
            Class.forName("com.mysql.jdbc.Driver");  
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);          
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();          
              
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }      
        return resList;
    }


 Output : [{iditem=1, item_name=ketchup, price_kg=100}, {iditem=2, item_name=Beverages, price_kg=140}]

Below method converts the input List of Maps to html
    public <E> String List_MaptoHtml_TableRows(ArrayList l){   
        StringBuffer sb=new StringBuffer() ;
        //String s=null;
        String[] stemp;
       
        int flag=0;
       
        for(Iterator<E> i=l.iterator();i.hasNext();){
            Map<String,Object> m=(Map<String, Object>) i.next();
            if(flag==0)
            {
                stemp=m.keySet().toString().split(" ");
                sb.append("\n<tr>");
                for(int i2=0;i2<stemp.length;i2++)
                    sb.append("\n    <td><strong>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</strong></td>");
                sb.append("\n</tr>\n");
                flag=1;
            }
           
            stemp=m.values().toString().split(" ");
            sb.append("\n<tr>");
            for(int i2=0;i2<stemp.length;i2++)
                sb.append("\n    <td>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</td>");
            sb.append("\n</tr>\n");

        }               
            return sb.toString();
        }
       


Create a new Servelet and add below code to Doget method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DBHelper DBHelp=new DBHelper();
        PrintWriter out=response.getWriter();
        ArrayList<Object> oList;


        if(LRes.isEmpty()==false){
            oList=(ArrayList<Object>) DBHelp.SelectQuery(sURL,sUsername,sPassword,"SELECT * FROM mydb.item;"); 
             Helper helper=new Helper();
             out.println("<html>");
                out.println("<head><title>Page name</title></head>");
                out.println("<body>");
                out.println(oList);
                out.println("<center><h1> List of Items </h1>");
                out.println("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:500px\">");
                out.println("<tbody>");
                out.println(helper.List_MaptoHtml_TableRows(oList));
                out.println("</tbody></table><p>&nbsp;</p>");
             out.println("</center>");
                out.println("</body>");
                out.println("</html>");
        }
        HttpSession session=request.getSession(); 
            session.setAttribute("name",username); 
}

Java : Print Query data from table directly into html file in Servelet itself

Print Query data from table directly into html file in Servelet itself

Libraries required :
  1.  commons-dbutils
  2. my-sqlconnector
Added to project path and WebContent/lib folder

Below method retreieves data from the DB into List of Maps
public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
      
        try {
            Class.forName("com.mysql.jdbc.Driver");  
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);          
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();          
              
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }      
        return resList;
    }


 Output : [{iditem=1, item_name=ketchup, price_kg=100}, {iditem=2, item_name=Beverages, price_kg=140}]

Below method converts the input List of Maps to html
    public <E> String List_MaptoHtml_TableRows(ArrayList l){   
        StringBuffer sb=new StringBuffer() ;
        //String s=null;
        String[] stemp;
       
        int flag=0;
       
        for(Iterator<E> i=l.iterator();i.hasNext();){
            Map<String,Object> m=(Map<String, Object>) i.next();
            if(flag==0)
            {
                stemp=m.keySet().toString().split(" ");
                sb.append("\n<tr>");
                for(int i2=0;i2<stemp.length;i2++)
                    sb.append("\n    <td><strong>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</strong></td>");
                sb.append("\n</tr>\n");
                flag=1;
            }
           
            stemp=m.values().toString().split(" ");
            sb.append("\n<tr>");
            for(int i2=0;i2<stemp.length;i2++)
                sb.append("\n    <td>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</td>");
            sb.append("\n</tr>\n");

        }               
            return sb.toString();
        }
       


Create a new Servelet and add below code to Doget method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DBHelper DBHelp=new DBHelper();
        PrintWriter out=response.getWriter();
        ArrayList<Object> oList;


        if(LRes.isEmpty()==false){
            oList=(ArrayList<Object>) DBHelp.SelectQuery(sURL,sUsername,sPassword,"SELECT * FROM mydb.item;"); 
             Helper helper=new Helper();
             out.println("<html>");
                out.println("<head><title>Page name</title></head>");
                out.println("<body>");
                out.println(oList);
                out.println("<center><h1> List of Items </h1>");
                out.println("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:500px\">");
                out.println("<tbody>");
                out.println(helper.List_MaptoHtml_TableRows(oList));
                out.println("</tbody></table><p>&nbsp;</p>");
             out.println("</center>");
                out.println("</body>");
                out.println("</html>");
        }
        HttpSession session=request.getSession(); 
            session.setAttribute("name",username); 
}

Friday, July 1, 2016

WebServer : Login Screen

WebServer : Login Screen

http://docs.oracle.com/javaee/6/tutorial/doc/gjiie.html
http://www.tutorialspoint.com/servlets/servlets-form-data.htm  (All sorts of form elements)
http://mrbool.com/using-html-forms-with-servlets/28335
http://www.javatpoint.com/servlet-http-session-login-and-logout-
http://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://tutorials.jenkov.com/java-servlets/index.html

doGet()
  1.  small amount of data
  2.  insensitive data like a query has to be sent as a request.

doPost()
  1.  large amount of  has to be sent.
  2.  sensitive data (Examples are sending data after filling up a form or sending login id and password.)

Note :
Following methods of the HttpServletRequest interface that enable you to authenticate users for a web application programmatically:

    login-An alternative to specifying form-based authentication in an application deployment descriptor.
    logout- which allows an application to reset the caller identity of a request.

Forward():
  1.     Executed in the server side.
  2.     The request is transfer to other resource within same server.
  3.     Any Client
  4.     The request is shared by the target resource.
  5.     It can be used within server.
  6.     We cannot see forwarded message
  7.      faster
  8.     It is declared in RequestDispatcher interface.
  9.     Only Response from Server

sendRedirect():
  1.     Executed in the client side.
  2.     The request is transfer to other resource to different server.
  3.     Only with HTTP clients.
  4.     New request is created for the destination resource.
  5.     It can be used within and outside the server.
  6.     We can see redirected address, it is not transparent.
  7.     slower
  8.     It is declared in HttpServletResponse.
   
Include()
    Forward() + Client Side info()


Application Overview:
Index.html > Login.html > (Pass)Welcome.html or (fail) Login.html

@WebServlet("/Login")
public class MyServerlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String sURL="jdbc:mysql://localhost:3306/mydb";
    private static final String sUsername="root";
    private static final String sPassword="password";
   
    public MyServerlet1() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List LRes=null;
        RequestDispatcher rd = null;
        DBHelper DBHelp=new DBHelper();
        PrintWriter out=response.getWriter();
       
        String username = request.getParameter("Usn");
        String password = request.getParameter("Password");
        LRes=DBHelp.SelectQuery(sURL,sUsername,sPassword,"SELECT * FROM mydb.login where UserID ='"+username+"' and Password='"+password+"';");
       
        if(LRes.isEmpty()==false){
            out.print("Login Successful");
            HttpSession session=request.getSession(); 
            session.setAttribute("name",username); 
           // response.sendRedirect(request.getContextPath() + "/WelcomeServlet.jsp");
            rd = request.getRequestDispatcher("/WelcomeServlet.html");
            rd.include(request, response);
            //rd.forward(request, response);  -- This can be used as well
            LRes=null;
        }
        else{
            out.print("Login failed");
        response.sendRedirect(request.getContextPath() + "/Login.html");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);

    }
}


Database helper Class :
public class DBHelper {   
    public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
       
        try {
            Class.forName("com.mysql.jdbc.Driver");   
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);           
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();           
               
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }       
        return resList;
    }
}