Java Date - Insert into database

 


your date is finally saved  as "2009-12-31"

So you can solve this problem in two ways:

1. Simply use setString(indexPosition, stringDatevalueInAboveFormat)
 
 2.Convert util.Date in sql.Date as below
 
    java.util.Date myDate = new java.util.Date("10/10/2009");

    PreparedStatement pstmt = connection.prepareStatement(
    "INSERT INTO USERS ( USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE ) " +
    " values (?, ?, ?, ?, ? )");

    pstmt.setString( 1, userId );
    pstmt.setString( 3, myUser.getLastName() ); 
    pstmt.setString( 2, myUser.getFirtName() );  
    pstmt.setString( 4, myUser.getSex() );
    pstmt.setDate( 5, new java.sql.Date( myDate.getTime() ) );
 
As per the format question, using SimpleDateFormat will do:

String s = new SimpleDateFormat("dd/MM/yyyy").format( aDate );
 

 

Why use EJB when we can do the same thing with servlets?



Actually, servlets/JSPs and EJB are complementary, not competing technologies: Servlets provide support for writing web based applications whereas EJBs provide support for writing transactional objects. In larger web systems that require scalability, servlet and JSP or XML/XSL technologies provide support for the front end (UI, client) code, where EJB provides support for the back end (database connection pooling, declaritive transactions, declaritive security, standardized parameterization...)
The most significant difference between a web application using only servlets and one using servlets with EJBs is that the EJB model mandates a separation between display and business logic. This is generally considered a Good Thing in non-trivial applications because it allows for internal reuse, allows flexibility by providing a separation of concerns, gives a logical separation for work, and allows the business logic to be tested separately from the UI (among others).
Some of the hings that servlets and JSPs can do that EJBs cannot are:
  • Respond to http/https protocol requests.
  • (With JSP) provide an easy way to format HTML output.
  • Easily associate a web user with session information
Some of the things that EJBs enable you to do that servlets/JSPs do not are:
  • Declaritively manage transactions. In EJB, you merely specify whether a bean's methods require, disallow, or can be used in the context of a transaction. The EJB container will manage your transaction boundaries appropriately. In a purely servlet architecture, you'll have to write code to manage the transaction, which is difficult if a logical transaction must access multiple datasources.
  • Declaritively manage security. The EJB model allows you to indicate a security role that the user must be assigned to in order to invoke a method on a bean. In Servlets/JSPs you must write code to do this. Note, however that the security model in EJB is sufficient for only 90% to 95% of application code - there are always security scenarios that require reference to values of an entity, etc.

Sockets Example


Sockets Example 


  
This example introduces you to Java socket programming. The server listens for a connection. When a connection is established by a client. The client can send data. In the current example the client sends the message "Hi my server". To terminate the connection, the client sends the message "bye". Then the server sends the message "bye" too. Finally the connection is ended and the server waits for an other connection. The two programs should be runned in the same machine. however if you want to run them in two different machines, you may simply change the adress "localhost" by the IP adress of the machine where you will run the server.
The server
import java.io.*;
import java.net.*;
public class Provider{
 ServerSocket providerSocket;
 Socket connection = null;
 ObjectOutputStream out;
 ObjectInputStream in;
 String message;
 Provider(){}
 void run()
 {
  try{
   //1. creating a server socket
   providerSocket = new ServerSocket(2004, 10);
   //2. Wait for connection
   System.out.println("Waiting for connection");
   connection = providerSocket.accept();
   System.out.println("Connection received from " + connection.getInetAddress().getHostName());
   //3. get Input and Output streams
   out = new ObjectOutputStream(connection.getOutputStream());
   out.flush();
   in = new ObjectInputStream(connection.getInputStream());
   sendMessage("Connection successful");
   //4. The two parts communicate via the input and output streams
   do{
    try{
     message = (String)in.readObject();
     System.out.println("client>" + message);
     if (message.equals("bye"))
      sendMessage("bye");
    }
    catch(ClassNotFoundException classnot){
     System.err.println("Data received in unknown format");
    }
   }while(!message.equals("bye"));
  }
  catch(IOException ioException){
   ioException.printStackTrace();
  }
  finally{
   //4: Closing connection
   try{
    in.close();
    out.close();
    providerSocket.close();
   }
   catch(IOException ioException){
    ioException.printStackTrace();
   }
  }
 }
 void sendMessage(String msg)
 {
  try{
   out.writeObject(msg);
   out.flush();
   System.out.println("server>" + msg);
  }
  catch(IOException ioException){
   ioException.printStackTrace();
  }
 }
 public static void main(String args[])
 {
  Provider server = new Provider();
  while(true){
   server.run();
  }
 }
}
  
The client
import java.io.*;
import java.net.*;
public class Requester{
 Socket requestSocket;
 ObjectOutputStream out;
  ObjectInputStream in;
  String message;
 Requester(){}
 void run()
 {
  try{
   //1. creating a socket to connect to the server
   requestSocket = new Socket("localhost", 2004);
   System.out.println("Connected to localhost in port 2004");
   //2. get Input and Output streams
   out = new ObjectOutputStream(requestSocket.getOutputStream());
   out.flush();
   in = new ObjectInputStream(requestSocket.getInputStream());
   //3: Communicating with the server
   do{
    try{
     message = (String)in.readObject();
     System.out.println("server>" + message);
     sendMessage("Hi my server");
     message = "bye";
     sendMessage(message);
    }
    catch(ClassNotFoundException classNot){
     System.err.println("data received in unknown format");
    }
   }while(!message.equals("bye"));
  }
  catch(UnknownHostException unknownHost){
   System.err.println("You are trying to connect to an unknown host!");
  }
  catch(IOException ioException){
   ioException.printStackTrace();
  }
  finally{
   //4: Closing connection
   try{
    in.close();
    out.close();
    requestSocket.close();
   }
   catch(IOException ioException){
    ioException.printStackTrace();
   }
  }
 }
 void sendMessage(String msg)
 {
  try{
   out.writeObject(msg);
   out.flush();
   System.out.println("client>" + msg);
  }
  catch(IOException ioException){
   ioException.printStackTrace();
  }
 }
 public static void main(String args[])
 {
  Requester client = new Requester();
  client.run();
 }
}
  

How to detect end of file when read serialized object from a file


No way to find EOF, Simply store object in a List (e.g. ArrayList, HashMap etc.) then serialize it and write into a file like below..

public class User implements Serializable{
String name;
String pass;

    public User(String name, String pass) {
        this.name = name;
        this.pass = pass;
    }

    public String getName() {
        return name;
    }

    public String getPass() {
        return pass;
    }
    public void display(){
        System.out.println(name+":"+pass);
    }

}

public class RecordReader {

    public static void main(String as[]) throws Exception{
        ObjectInputStream input=new ObjectInputStream(new FileInputStream("e:/u.txt"));        
        ArrayList u=(ArrayList)input.readObject();      
        Iterator i=u.iterator();
       System.out.println("Records are: ");
        while(i.hasNext()){
            User u1=(User)i.next();
            u1.display();
        }       
     
    }
}
public class RecordSaver {

    public static void main(String as[]) throws Exception{
        ArrayList list=new ArrayList();
        BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
        ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("e:/u.txt"));      
         list.add(new User("raj","kumar"));
         list.add(new User("raju","jha"));
         out.writeObject(list);
         out.close();
        System.out.println("Record save successfully");
    }
}