Saturday, May 22, 2010

Simple MVC using jsp and servlets.



MVC (Model, View , Controller)

Here I am going to create 4 files. 
1)Test1.jsp will simpley containg a link that will transfet control to controller servlet testBeanServlet.java
2)testBeanServlet.java will create an object of testBean class and set private member x by calling setX() method.
3)Then it will put this oblect to session variable and then forward the request to Test.jsp file.
4)Test.jsp file will use the getProperty method to display the value.

Here is the code : 


Test1.jsp
----------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>                              
<a href="testBeanServlet">hiii</a>
</body>
----------------------------------------------------------------------------------




testBeanServlet.java

----------------------------------------------------------------------------------
package org.javatrainer;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class testBeanServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
testBean b=new testBean();
b.setX(10);
HttpSession s=request.getSession();
s.setAttribute("value", b);
RequestDispatcher dispatcher =
      request.getRequestDispatcher("test.jsp");
      dispatcher.forward(request, response);
}
}         
-------------------------------------------------------------------------------------------------------------




testBean.java
----------------------------------------------------------------------------------
package org.javatrainer;

public class testBean {
     
      private int x;
     
      public void setX(int x)
      {
            System.out.println("hi");
       this.x=x;
       System.out.println(x);
      }
      public int getX()
      {
            return x;

}
}
-----------------------------------------------------------------------------------------------------------------------------------





Test.jsp


----------------------------------------------------------------------------------
<html>
<head>

<title>Insert title here</title>
</head>
<body>

<jsp:useBean id="value" type="org.javatrainer.testBean" scope="session" />

<jsp:getProperty name="value" property="x"/>

</body>
</html>
-----------------------------------------------------------------------------------------------------------------------------------





java/mysql database connection in eclipse

1 ) download mysql/j connector and extract it in c:/ drive.

2)create a new project in eclipse. Right click it and select Build Path/configure build path.

3) Select add library and the select connectivity driver definition and then select next.

4) select new driver definition : 

5)
select Generic JDBC driver

6) select Jar List from the tab
7)
click on add jar/zip and find out the jar file from the extracted directory.

8)click on property tab and select driver class and then select browse for class and select 
com.mysql.jdbc.Driver:
click ok and finish.


Now create a simple program : 

-------------------------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class logincheck {

                public static void main(String[] args) {
                                // TODO Auto-generated method stub
                                Connection con=null;
                                System.out.println("hi");
                                try
                                {
                                System.out.println("hi111");
                                con=DriverManager.getConnection("jdbc:mysql://localhost/store","root", "");
                                System.out.println("successful");
                               
                                Statement statement=con.createStatement();
                                String query="SELECT email,password from user";
                                ResultSet result=statement.executeQuery(query);
                               
                                while(result.next())
                                {
                                                System.out.print(result.getString("email"));
                                                System.out.print(result.getString("password"));
                                }
                                con.close();
                                }
                                catch(Exception e)
                                {
                                       System.out.println(e);         
                                }finally
                                  { con.close();
                                   }
}
}
-------------------------------------------------------------------------------------------------------------




jstl tags in jsp....

To run JSTL tag :
Download Jakarta-taglibs-standard-1.0.6 and put standared.jar and jstl.jar into web-inf/lib directory. Also put those two file in apache lib folder.
Add this to jsp file….--à
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Or
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> for new version.

Configuring eclipse to run Servlet and JSP

CONFIGURE ECLIPSE TO RUN SERVLET AND JSP:
1)      Download apache server  from www. Tomcat.apache.org  that is version Tomcat 6.x
2)      Extract that and put at the top level directory in C drive.
3)      Now set the environment variable classpath
d:\javadev> SET CLASSPATH=.;d:\Program Files\Apache Group\   
jakarta-tomcat-3.2.3\lib\servlet-api.jar
4)      Same thing with jsp
d:\javadev> SET CLASSPATH=.;d:\Program Files\Apache Group\   
jakarta-tomcat-3.2.3\lib\jsp-api.jar


if u want to connect to mysql database while using eclipse : 

DATABASE CONNECTION WITH MYSQL
1)  For database connection with mysql download mysql/j connector and extract it put it in top level c directory.
2)  Copy mysql-connector-java.jar file into  tomcat’s lib directory.




My First Hibernate Program.....

This is my first Hibernate program...... using ECLIPSE IDE

I will be using Mysql as my database engine......

Database Name : student 
Table : user


user will have two fields id(varchar and it is primary key) and name(varchar).

Now lets start
Steps:
1) Create a Dynamic Web Project.Name it firstHibernate
2) Copy required jar files into lib directory of the project folder.

lib directory : WebContent/WEB-INF/lib


3) after that create directory structure like this : 

creat resource folder which will hold hibernate configuration(hibernate.cfg.xml) and mapping file(student.hbm.xml).



4)Copy and paste this code in hibernate.cfg.xml file: 
-------------------------------------------------------------------------------------------------------------
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/student
</property>
<property name="connection.username">root</property>
<property name="connection.password">mitesh</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache  -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
-------------------------------------------------------------------------------------------------------------


Note : 
three thing you need to change according to the system :
1)Database name : if you have created database other than student then change it with 
jdbc:mysql://localhost:3306/YourDatabaseName
2) root that is default username and mitesh that is password for username root. I haven't changed if you have changed it then change it with 
userName
password


5) Now Create a mapping file student.hbm.xml

-------------------------------------------------------------------------------------------------------------
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="mitesh.first.Student" table="user">
   <id name="id" type="long" column="id" >
   <generator class="assigned"/>
  </id>
  <property name="name">
     <column name="name" />
  </property>
 </class>
</hibernate-mapping>
-------------------------------------------------------------------------------------------------------------

here table specifies table that we have created in database student that is user. and mitesh.first.Student specifies the fully qualified location of the bean class Student.

column name specifies name of the column in user table. 


6) Now creat a package named mitesh.first under src folder and after that create a class named Student.java.
copy and paster this code into Student.java class

-------------------------------------------------------------------------------------------------------------
package mitesh.first;
public class Student {
  private String name;
  private long id;
  public String getName() {
    return name;
  }
  public void setName(String string) {
    name = string;
  }
  public long getId() {
    return id;
  }
  public void setId(long l) {
    id = l;
  }
}
-------------------------------------------------------------------------------------------------------------

6)
after that create a java file in mitesh.first package containing main method lets give name FirstHibernate.java
copy and paste the following code :

-------------------------------------------------------------------------------------------------------------
package mitesh.first;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class FirstHibernate {
  public static void main(String[] args) {
    Session session = null;
    try{      
      SessionFactory sessionFactory = new 
Configuration().configure().buildSessionFactory();
       session =sessionFactory.openSession();
         System.out.println("Inserting Record");
        Student student = new Student();
        student.setId(31);
        student.setName("Mitesh");
        session.save(student);
        System.out.println("Done");
    }catch(Exception e){
      System.out.println(e.getMessage());
    }finally{
      // Actual contact insertion will happen at this step
      session.flush();
      session.close();
      }
  }
}

we are all set.................





First Hello World Program.......

First Java Program
public class HelloWorld { 
   public static void main(String[] args) { 
      System.out.println("Hello, World");
   }
}
Goto the command prompt......type
c:/> javac HelloWorld.java
c:/>java HelloWorld
O/P:
Hello,World