Wednesday, July 20, 2016

Javascript : Basic example of javascript

Basic example of javascript



<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>

<h1>JavaScript in Head</h1>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

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); 
}

Java : Sending and Retreiving data from JSP to Serverlet and visversa

Sending and Retreiving data from JSP to Serverlet and visversa

Note :
  1. UI to Servlet -  html or jsp
  2. Servelet to UI - jsp only


UI to Servlet 

Login.html

<html>
<body>
<form action="MyServerlet1" method="get">
    <p>Username <input name="Usn" type="text" />&nbsp;</p>
    <p>Password <input name="Password" type="text" /></p>
    <p><input name="Submit" type="submit" value="Submit" /></p>
</form>
</body>
</html>


MyServerlet1.java
  1. Project>Javarespurces>src>package>rt ck >new servelet>
  2. Name "MyServerlet1" >Next,next>check doGet and doPost>Finish
  3.  Add below code to retreieve the data from "Usn" and "Password" fields.
@WebServlet("/Login")
public class MyServerlet1 extends HttpServlet {
   
    public MyServerlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String username = request.getParameter("Usn");
        String password = request.getParameter("Password");
        out.println(username+"  "+password);
    }
}

Servlet to UI (jsp file only)

itemlist.jsp (Create new jsp file in Project>WebContent>itemslist.jsp)
<html>
  <body>
    Servlet communicated message to JSP: ${jItem_list}
  </body>
</html>

Serverlet.java
request.setAttribute("jItem_list", json);
            rd = request.getRequestDispatcher("/itemslist.jsp");
            rd.forward(request, response);

 

Tuesday, July 12, 2016

Java : Object to Xml and vis versa

Object to Xml and vis versa


JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :
  1. Marshalling – Convert a Java object into a XML file.
  2. Unmarshalling – Convert XML content into a Java Object.

Required library : https://jaxb.java.net/latest/download.html

Marshalling

@XmlRootElement
public class Customer {
 String name;
 int age;
 int id;
 public String getName() {
  return name;
 }
 @XmlElement
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 @XmlElement
 public void setAge(int age) {
  this.age = age;
 }
}


public class JAXBExample {
 public static void main(String[] args) {

   Customer customer = new Customer();
   customer.setName("John");
   customer.setAge(18);

   try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

  // output pretty printed
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  jaxbMarshaller.marshal(customer, file);
  jaxbMarshaller.marshal(customer, System.out);

       } catch (JAXBException e) {
  e.printStackTrace();
       }

 }
}
 Output:
<customer age="18">
    <name>John</name>
</customer> 

Unmarshalling

public class JAXBExample {
 public static void main(String[] args) {

  try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
  System.out.println(customer);

   } catch (JAXBException e) {
  e.printStackTrace();
   }

 }
} 
Customer [name=John, age=18] 

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