Ajax with jsp : simple example

HTML Page
<
html>
    <head><title>welcome</title>
    <script language="javascript">
        reqObj=null;
        function varify(){
            document.getElementById("res").innerHTML="Checking";
            if(window.XMLHttpRequest){
                reqObj=new XMLHttpRequest();
            }else {
                reqObj=new ActiveXObject("Microsoft.XMLHTTP");
            }
            
            reqObj.onreadystatechange=process;
            reqObj.open("POST","./a.jsp?id="+document.getElementById("username").value,true);
            reqObj.send(null);
        }
        function process(){
            if(reqObj.readyState==4){
                document.getElementById("res").innerHTML=reqObj.responseText;
            }
        }
        </script>
    
    </head>
    <body>
        <h1>welcome to this application</h1>
    <form method="get" action="first">
        User Name<input type="text" name="t1" id="username" onblur="varify();"><span id="res"></span><br/>
        Password<input type="text" name="t2"><br/>
        <input type ="submit" value="Press"/>
    </form>
    </body>
</html
>


JSP Page
<%
String user=request.getParameter("id");
try{Thread.sleep(5000);}catch(Exception e){}
if(user.equals("abc")){
%>
<font color="red" ><strong>User already exists</strong></font>
<%
}else{
%>
<font color="green" ><strong>User  name available</strong></font>
<%
}
%>

Diffrences between forward and sendRedirect, MCS-051, June 2009, 5a(i)

forward() sendRedirect()
it is used to invoke another server from one servlet with is same server it can send request to page on another server
It forward the same request and response object from one servlet to another servlet. It does not send request and response object to another servlet.
Redirection occures within server. it sends response code to client side application to send the request to another serlver or resoures.
this method is availabe through RequestDispatcher Object. This is method of response object.
It transfer control to another servlet for further processing It send response to browser and then browser agian sends request for second servlet or resource
Data submitted to first servlet will be availble for second servlet. Data of first servlet is not availble for secind servlet.

Diffrences between Servlet config and servlet context, MCS-051, June 2009, 5a(i)

Servlet context Servlet config
It is an Object to be shared by all servlets and JSPs. this object is associated to specific servlet
unlimited store of data as per as server capability limited support for data handling
can be used to collaboration between multiple servlet. It is for single servlet
Data stored here can be access from any servlet and JSP Data stored here can be access from the servlet for which this object is associated
It is created using getServletContext() method of Servlet class Created using getServletConfig() method
Only Single instance available within web application Multiple instances for each servlet.
contains global properties like classpath, context path etc Only contains property related to specific servlet.

Differences between Session and cookie, MCS-051, June-2008-4b

Session Cookie
Data on server-side data on client side
unlimited side of data as per as server capability limited support for data data handling
It can store any type of data only text
age of data is not fixed . fixed
destroy after session timeout or logout remains on client machine
less data traveling over the network All cookie need to travel each time client sends request to server.
More secure mechanism to session tracking less secure

Using SSL in java program

import java.net.*;
import java.security.cert.Certificate;
import java.io.*;

import javax.net.ssl.*;

public class SSLTest {

    public static void main(String[] args) throws Exception {
        String https_url = "https://www.google.com/";
        URL url;
        url = new URL(https_url);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        if (con != null) {
                System.out.println("Response Code : " + con.getResponseCode());
                System.out.println("Cipher Suite : " + con.getCipherSuite());
                System.out.println("\n");
                Certificate[] certs = con.getServerCertificates();
                int i=0;
                for (Certificate cert : certs) {
                    System.out.println("Cert NO : "+i++);
                    System.out.println("Cert Type : " + cert.getType());
                    System.out.println("Cert Hash Code : " + cert.hashCode());
                    System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
                    System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
                    System.out.println("\n");
                }
                System.out.println("****** Content of the URL ********");
                BufferedReader br =new BufferedReader(new InputStreamReader(con.getInputStream()));
                String input;
                while ((input = br.readLine()) != null) {
                    System.out.println(input);
                }
                br.close();
        }
    }
}

Write a program to create a XML document from a telephone directory database. Dec08_4a

import java.sql.*;
public class Dec08_4a
{
  public static void main(String ar[])throws Exception
  {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=database.mdb");
    //Connection con = DriverManager.getConnection("jdbc:odbc:mydsn");
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from phoneDirectory");
   System.out.println("<phone-directory>");
   while (rs.next())
   {
    System.out.println("    <customer>");
    String s1 = rs.getString(1);
    System.out.println("          <customer-name>"+s1+"</customer-name>");
    String s2 = rs.getString(2);
    System.out.println("          <address>"+s2+"</address>");
    String s3 = rs.getString(3);
    System.out.println("          <phone-number>"+s3+"</phone-number>");
    String s4 = rs.getString(4);
    System.out.println("          <bill-summary>"+s4+"</bill-summary>");
    System.out.println("    </customer>");
   }
   System.out.println("</phone-directory>");
  }
}



OUTPUT

<phone-directory>
    <customer>
          <customer-name>abc</customer-name>
          <address>sdfsad</address>
          <phone-number>234243</phone-number>
          <bill-summary>343</bill-summary>
    </customer>
    <customer>
          <customer-name>sdf</customer-name>
          <address>sdfsdf</address>
          <phone-number>2345234</phone-number>
          <bill-summary>345</bill-summary>
    </customer>
    <customer>
          <customer-name>hhhhhhhh</customer-name>
          <address>dddd</address>
          <phone-number>44444</phone-number>
          <bill-summary>333</bill-summary>
    </customer>
    <customer>
          <customer-name>sssss</customer-name>
          <address>3333fff</address>
          <phone-number>3333</phone-number>
          <bill-summary>444</bill-summary>
    </customer>
</phone-directory>

Write a code for servlet which will display all the fields of Employee table in tabular form.MCS-051,Dec09-3a

import javax.servlet.*;
import java.io.*;
import java.sql.*;
  import javax.servlet.http.*;
  public class Employee extends HttpServlet
  {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,      ServletException
  {
  res.setContentType("text/Html");
  PrintWriter pw = res.getWriter();
  try
  {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection con=DriverManager.getConnection("jdbc:odbc:dsn");
  Statement st=con.createStatement();
  ResultSet rs=st.executeQuery("select emp_id,emp_name,emp_dob,mob_no,email from employee");
  String tr="";
  while(rs.next()){
  tr=tr+"<tr>";
  tr=tr+"<td>"+rs.getString(1)+"</td>";
  tr=tr+"<td>"+rs.getString(2)+"</td>";
  tr=tr+"<td>"+rs.getString(3)+"</td>";
  tr=tr+"<td>"+rs.getString(4)+"</td>";
  tr=tr+"<td>"+rs.getString(5)+"</td>";
  tr=tr+"</tr>";
  }
  String table="<table border='1'>"+tr+"</table>";
  pw.write(table);
  pw.close();
  con.close();
  }catch(Exception e)
  {
  pw.write(""+e);
  }
  }
  }

Web application for student registration, where student can register online with enrollment number. ther registered students should be able to log on after getting registered. you are required to use JSP, servlet, and JDBC. . MCS-051, Dec2009-1b.

StudentRegistration
│   index.html
│   login.html
│
└───WEB-INF
    │   web.xml
    │
    └───classes
            login.class
            login.java
            regform.class
            regform.java



Index.html

<html>
<head>
<title>registration</title>
</head>
<body>
<form method="post" action="reg">
NAME:<input type="text"name="t1"/><br>
ENROLLMENT:<input type="text"name="t2"/><br>
PASSWORD:<input type="password"name="t3"/><br>
<input type="submit"value="send"/><br>
</form>
<a href='login.html'>if already registered plz login</a>
</body>
</html>



login.html

<html>
<head>
<title>login</title>
</head>
<body>
<form method="post" action="login">
  <h2>ENTER VALID USER NAME AND PASSWORD</h2>
  <p><strong>USER NAME:</strong>
<input type="text"name="t1"/><br>
    <strong>PASSWORD:</strong>
    <input type="password"name="t2"/><br>
  <input type="submit"value="Login"/><br>
  </p>
</form>
<a href='index.html'>new user create account</a>
</body>
</html>



web.xml

<web-app>
 <servlet>
  <servlet-name>s1</servlet-name>
  <servlet-class>regform</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>s1</servlet-name>
  <url-pattern>/reg</url-pattern>
 </servlet-mapping>
 
 <servlet>
  <servlet-name>s2</servlet-name>
  <servlet-class>login</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>s2</servlet-name>
  <url-pattern>/login</url-pattern>
 </servlet-mapping>
</web-app>



regform.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class regform extends HttpServlet{
 public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  String n=req.getParameter("t1");
  String e=req.getParameter("t2");
  String p=req.getParameter("t3");
  try{
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con=DriverManager.getConnection("jdbc:odbc:school");
   PreparedStatement st=con.prepareStatement("insert into student values(?,?,?)");
   st.clearParameters();
   st.setString(1,n);
   st.setInt(2,Integer.parseInt(e));
   st.setString(3,p);
   st.executeUpdate();
   con.close();
   
  }catch(Exception ex){
   ex.printStackTrace(System.out);
  }
  out.write("ur account has been created, <a href='login.html'>u can login now</a>");
  
 }
}



login.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet{
 public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  String n=req.getParameter("t1");
  String p=req.getParameter("t2");
  
  try{
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con=DriverManager.getConnection("jdbc:odbc:school");
   PreparedStatement st=con.prepareStatement("select * from student where name=? and pass=?");
   st.clearParameters();
   st.setString(1,n);
   st.setString(2,p);
   ResultSet rs=st.executeQuery();
   boolean b=rs.next();
   if(b==true){
    out.write("WELCOME");
    
   }
   else{
    out.write("Login failed <a href='login.html'>TRY AGAIN</a>");
    
   }
   con.close();
   
  }catch(Exception ex){
   ex.printStackTrace(System.out);
  }
 }
}

Write a code in JSP to insert a record in product table with fields: prod_d id, prod_name, quantity, price. Assuming that product table is create in MS-Access database. MCS51-june09-1b



JSP code

<%@page import="java.sql.*"%>
<%!
int prod_id=1;
String prod_name="Laptop";
int qty=2;
float price=22000.30f;
%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:NaveenRahul");
Statement st=con.createStatement();
String query="insert into product values("+prod_id+",'"+prod_name+"',"+qty+","+price+")";
if(st.executeUpdate(query)>0){
out.write("Records inserted");
}else{
out.write("insertion faild");
}
}catch(Exception e){
out.write("Exception : "+e);
}
%>



JAVA Codes

import java.sql.*;
class Insert2{
public static void main(String ar[]){
int prod_id=2;
String prod_name="Laptop";
int qty=2;
float price=22000.30f;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:NaveenRahul");
Statement st=con.createStatement();
String query="insert into product values("+prod_id+",'"+prod_name+"',"+qty+","+price+")";
if(st.executeUpdate(query)>0){
System.out.println("Records inserted");
}else{
System.out.println("insertion faild");
}
con.close();
}catch(Exception e){
System.out.println("Exception : "+e);
}
}
}

Compare and contrast, SSL and TLS, MCS51-dec2007-1(g)

SSL TLS
SSL stands for Secure Sockets Layer. TLS stands for Transport Layer Security.
Netscape originally developed this protocol. The Internet Engineering Task Force (IETF) created TLS as the successor to SSL.TLS as the successor to SSL.
SSL works mainly through using public/private key encryption on data. TLS uses stronger encryption algorithms and has the ability to work on different ports
It is commonly used on web browsers It is most often used as a setting in email programs
SSL connections begin with security and proceed directly to secured communications TLS connections first begin with an insecure “hello” to the server and only switch to secured communications after the handshake between the client and the server is successful

Example of Message Driven Bean, MCS51-june2007-3(ii)

Simple example for the MDB without configuration file. 
package mdb;

import javax.ejb.*;
import javax.jms.*;
import javax.naming.*;

public class MyMDB implements MessageDrivenBean, MessageListener
{

  public MyMDB()
  {

  }
//invoked first after ejbCreate() of MDB

  public void setMessageDrivenContext(MessageDrivenContext mdc)
  {
  }

//invoked first after just object creation of MDB
  public void ejbCreate()
  {
    System.out.println("ejbCreate(): " + this);
  }
//this method is invoked when any message arrives on the destination for which this MDB has been configured. 

  public void onMessage(Message inMessage)
  {

    try
    {
      System.out.println("Message received: " + inMessage);
    } catch (Exception e)
    {
      e.printStackTrace();
    }
  }
//this method invoked when MDB object being destroyed by EJB server

  public void ejbRemove()
  {
    System.out.println("ejbRemove(): " + this);
  }
}

MCs-051, June2007,1(iv), Three type of entities

Internal Entities :
If entities stored in declaration tag within same document, it is called internal entity. for example
<!ENTITY BCA "Bachelor of Computer Application" >
It is internal entity and we can use it as &bca; anywhere in the document. When XML parser process these entities, it replaces them to their corresponding values.
 
External Entities :
Entities those point external source of contents like pointing external xml file are referred as External entities. for example;
<ENTITY course SYSTEM "/location/course.xml">
this entity is pointing external document course.xml. where XML parser interpret this entity, contents of course.xml document are inserted at the location of entity.
 
Parameter Entities.
Parameter are entites those are used to hold the DTD's declarations as a parameters. Using parameter entities (prefixed with a %), a type entity can be created. Then this entity can replace the parameter list. The % type; entity needs to be declared as follows:

<!ENTITY %type "(retail | food )">

The store element declaration now returns to a somewhat more readable list like this:

<!ELEMENT store (%type;, name,phone,promo,image)>

MCA - June, 2007 - 1(i)

Write a servlet program that takes your name and address from an HTML form and display it.





Application

index.html







WEB-INF

web.xml







classes

Display.java


 

web.xml


<web-app>

      <servlet>
<servlet-name>Display</servlet-name>
<servlet-class>Display</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Display</servlet-name>
<url-pattern>/Display</url-pattern>
</servlet-mapping>
</web-app>



Disply.java


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Display extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
String name=request.getParameter("name");
String address=request.getParameter("address");
pw.write("<br>Name : "+name);
pw.write("<br>Address : "+address);
pw.close();
}
}




index.html



<html>
<head>
<title>Display</title>
</head>
<body>
<form method="post" action="Display">
Name : <input type="text" name="name" value="" /><br/>
Address : <input type="text" name="address" value="" /><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>

Returns a view of a Deque as a Last-in-first-out (Lifo) Queue

Returns a view of a Deque as a Last-in-first-out (Lifo) Queue. Method add is mapped to push, remove is mapped to pop and so on. This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering.

package collection.demos;

import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.Queue;

public class LifoQueue {

    public static void main(String[] args) {
        Deque<String> chars = new ArrayDeque<String>();
        chars.add("A");
        chars.add("B");
        chars.add("C");
        chars.add("D");
        Queue<String> q = Collections.asLifoQueue(chars);
        System.out.println("Queue : " + q);
    }
}

/*
 OUTPUT
 Queue : [A, B, C, D]
 */

Adding all of the specified elements to the specified collection.

Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

package collection.demos;


import java.util.ArrayList;

import java.util.Collections;



public class AddingElementsToCollection{



    public static void main(String[] args) {

        ArrayList<String> list1 = new ArrayList<String>();

        list1.add("A");

        list1.add("B");

        list1.add("C");

        System.out.println("All elements have been added : "+Collections.addAll(list1, "D","E","F"));

        System.out.println("List Items : "+list1);

    }

}

/*

OUTPUT : 

All elements have been added : true

List Items : [A, B, C, D, E, F]

 */

Testing whether specified collections have no elements in common.

package collection.demos;



import java.util.ArrayList;

import java.util.Collections;



public class TestingDisjointInCollections{



    public static void main(String[] args) {

        ArrayList<String> list1 = new ArrayList<String>();

        list1.add("A");

        list1.add("B");

        list1.add("C");



        ArrayList<String> list2 = new ArrayList<String>();

        list2.add("D");

        list2.add("E");

        list2.add("F");



        ArrayList<String> list3 = new ArrayList<String>();

        list3.add("A");

        list3.add("B");

        list3.add("C");

        

        System.out.println("List1 and list2 have no common elements in collection : "+Collections.disjoint(list1, list2));

        System.out.println("List1 and list3 have no common elements in collection : "+Collections.disjoint(list1, list3));

    }

}

/*

OUTPUT : 

List1 and list2 have no common elements in collection : true

List1 and list3 have no common elements in collection : false

 */

Getting the number of elements in the specified collection equal to the specified object.



package collection.demos;



import java.util.ArrayList;

import java.util.Collections;



public class GettingFrequencyOfElementInCollection{



    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<String>();

        list.add("A");

        list.add("B");

        list.add("C");

        list.add("A");

        list.add("D");

        list.add("A");

        list.add("B");

        System.out.println("Frequency of B in list : "+Collections.frequency(list, "B"));

    }

}

/*

OUTPUT : 

Frequency of B in list : 2

 */

Getting an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.

Getting an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.

package collection.demos;



import java.util.ArrayList;

import java.util.Collections;

import java.util.Enumeration;



public class GettingListOfEnumeration{



    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<String>();

        list.add("A");

        list.add("B");

        list.add("C");

        list.add("D");

        Enumeration<String> e=Collections.enumeration(list);

       ArrayList<String> list2=Collections.list(e);

        System.out.println("List : "+list2);

    }

}

/*

OUTPUT : 

List : [A, B, C, D]

 */

Getting an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.

package collection.demos;


import java.util.ArrayList;

import java.util.Collections;

import java.util.Enumeration;


public class GettingEnumerationOfCollection {



    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<String>();

        list.add("A");

        list.add("B");

        list.add("C");

        list.add("D");

        Enumeration<String> e=Collections.enumeration(list);

        while(e.hasMoreElements()){

            System.out.println(e.nextElement());

        }

    }

}

/*

OUTPUT : 

A

B

C

D

 */

Returning a comparator that imposes the reverse ordering of the specified comparator

Returning a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface).

package collection.demos;



import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;



class Comparator1 implements Comparator<String>{

    public int compare(String o1, String o2) {

        return o1.compareTo(o2);

    }

}

public class GettingReverseOrderCamparator2 {

    public static void main(String[] args) {

        ArrayList<String> list=new ArrayList<String>();

        list.add("A");

        list.add("B");

        list.add("C");

        list.add("D");

        Comparator c=Collections.reverseOrder(new Comparator1());

        //Applying comparator to list

        Collections.sort(list, c);

        System.out.println("List : "+list);

    }

}

/*OUTPUT

 * List : [D, C, B, A]

 */

Returning a comparator that imposes the reverse of the natural ordering

Returning a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. (The natural ordering is the ordering imposed by the objects' own compareTo method.) This enables a simple idiom for sorting (or maintaining) collections (or arrays) of objects that implement the Comparable interface in reverse-natural-order.

package collection.demos;



import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;



public class GettingReverseOrderCamparator {

    public static void main(String[] args) {

        ArrayList<String> list=new ArrayList<String>();

        list.add("A");

        list.add("B");

        list.add("C");

        list.add("D");

        Comparator c=Collections.reverseOrder();

        //Applying comparator to list

        Collections.sort(list, c);

        System.out.println("List : "+list);

    }

}

/*OUTPUT

 * List : [D, C, B, A]

 */

Creating n copies of the specified object

Returning an immutable list consisting of n copies of the specified object. The newly allocated data object is tiny (it contains a single reference to the data object). This method is useful in combination with the List.addAll method to grow lists. The returned list is serializable.

package collection.demos;



import java.util.Collections;

import java.util.List;



public class NewClass {

    public static void main(String[] args) {

        List<String> items=null;

        items=Collections.nCopies(10"test");

        for (String string : items) {

            System.out.println(string);

        }

    }

}

Getting elments from specific postion

Returning the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.

Returning the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.

package collection.demos;



import java.util.ArrayList;

import java.util.Collections;

import java.util.List;



public class GettingIndexOfSubList {



    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<String>();

        names.add("Naveen");

        names.add("Neha");

        names.add("Deepak");

        names.add("Anchal");

        names.add("Nawaz");

        names.add("Avanish");

        names.add("Jai Ram");

        names.add("Kanchan");



        List<String> names1 = names.subList(24);

        System.out.println("Sublist : " + names1);

        int index = Collections.indexOfSubList(names, names1);

        System.out.println("Index Of list names1      : " + index);

        index = Collections.lastIndexOfSubList(names, names1);

        System.out.println("Last Index Of list names1 : " + index);

    }

}

Popular Posts