SIMPLE J2EE


J2EE MADE SIMPLE

Simple J2EE Reference for newbies!!!


Note:
If you are at intermediate or expert level, I suggest you not to spend much time on this page.
If you are a novice and couldn't understand anything below dont worry, you will get a clear idea after seeing examples

INTRODUCTION
Click here to find out difference between Java and J2EE

Have You ever heard that J2EE is difficult?
If so, you heard wrong.Let us the basics with clean step by step examples.
To start,all you have to know is the basics of HTML and the basic of JAVA.

HTML AND JAVA
HTML is pretty simple.Now many WYSIWYG(What You See is What You Get) editors are there lightening your burden for remembering many tags.
But my personal advice is use a notepad for learning purpose.
And coming to JAVA, its not much complicated as you think.
All I did was a few declarations (int a; String str....),a while loop,a do while loop,a if-else statement etc..for my first couple of projects.
If you know the above things you sure can develop a fair application.
For beginning these concepts are enough.

JSP AND SERVLET
JSP(Java Server Pages) is a server side scripting language.

Before going to examples, let me put the difference between JSP and Servlet in a layman's slang.
JSP is nothing but HTML pages with java code inside.
These Java codes are given within a Scriptlet( <% %>)
Just give your own java code within the scriptlet say for example int a=10; etc..

Servlet is nothing but .java files with HTML codes inside.
Every JSP page will become Servlet at the server side and then only it is processed.

JAVA BEAN
Dont be fooled by the name.Java Bean is quite simple.
It is nothing but Simple Java files.
As usual it will contain class with data and methods.
All you have to do is call the method in your JSP page.
I hope you will understand clearly by seeing the example below.


MVC PATTERN
M-Model (Bean files-->Business Logic)
V-View (JSP-->Presentation Logic)
C-Control(Servlet-->Control)
  • Business logic is the actual logic of the system.It is the purpose why we built our system
  • Presentation logic is nothing but how we want the users to view our web page.
  • Controlling is redirecting and transferring control from one page to another.
We can do our business logic and control in JSP. Similarly we can use servlet for Presentation and Business logic.
Then what is the purpose of following this pattern?
Why are we forced to follow these?
The answer is quite simple.These are the existing standard and it will easy for everyone to understand your project if you follow this. Plus if you want to make periodic changes in your project it will be always better if you use this because once you want to change your logic its enough if you edit the bean file and nothing other than that. once you begin your project you will get a clear idea why exactly we are following these.


EXAMPLES

1)A simple Hello World program.
2)Getting Form elements in next page
3)Database Connection.
4)Managing sessions.



1)A Simple Hello World Program

Go to Examples
<html>
<head>
<title>Hello Word </title>
</head>
<body>
<%
out.print("Hello World");
%>
</body>
</html>

NOTE
//-->SINGLE LINE COMMENT
  • out.println() and out.print() do same function.If you want new line go for BR tag
  • You can give html tags inside the print()/println() method
  • For example, out.println("<br>"); will print a new line
  • out.println("<h1>Hello World"); will print Hello World as Heading1
  • <% %> is called as scriptlet.You can give your Java coding here.This is your server side script.
    For example
    <%
    int a=10;
    out.println("The value of a ="+a);
    %>


2)GETTING FORM ELEMENTS IN NEXT PAGE

Go to Examples
1)one.html
<html>
<head>
<title>DEMO FORM </title>
</head>
<body>
<form action="two.jsp" method="POST">
Enter Your Name: <input type="text" name="name"/>
<input type="submit" value="GO"/>
</form>
</body>
</html>

2)two.jsp
<html>
<head>
<title>GETING FORM ELEMENTS </title>
</head>
<body>
<%
String nameString=request.getParameter("name");
%>
Welcome, <%out.println("nameString");%>
</body>
</html>

NOTE

  • form's action attribute refers to the page you want the form elements and control to go after pressing submit button.It can be either a JSP page or a servlet.
  • form's method attribute can be either GET or POST.
    Click here to know difference Between them.
  • In simple words, if we use GET attribute the form elements(names along with the values) that we send are appended in the URL and so everyone can see.
    If you use POST attribute we cant see them in URL.
  • The form elements are actually stored in request object.We use the getParameter("Parameter name") method of request object in second page to get the value of form elements from first page in string format.
  • Now we can manipulate with the element anyhow as we please.
    We can compare with other objects,store it in database etc.

3)DATABASE CONNECTIVITY USING JDBC

Go to Examples
<%@ page import="java.sql.*" %>

<html>
<head>
<title> validation page </title>
</head>
<body>
<table border="1">
<tr>
<th> NAME</th>
<th> AGE</th>
</tr>
<tr>
<%
     //Get the value of name and age got from previous page form.
   String name=request.getParameter("name");
   String ageStr=request.getParameter("age");
   int age=Integer.parseInt(ageStr);

   Connection con;
   String serverName = "127.0.0.1";
   String portNumber = "1521";
   String sid = "orcl";

   String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
   String username = "scott";
   String password = "tiger";

   String driverName = "oracle.jdbc.driver.OracleDriver";

// STEP1: Load the Driver.
        Class.forName(driverName);

// STEP2: Establish Connection
        con=   DriverManager.getConnection(url, username, password);

// STEP 3: Create Statement for that connection
        Statement stm=con.createStatement();

// STEP 4a: For create, Update, insert into DB use this.

             //String query="insert into student values('Madhan',20);
        String query="insert into student values('"+name+"',"+age+")";
        int i=stm.executeUpdate(query);

// STEP 4b(1): For select use the following Statement.

        ResultSet rs=stm.executeQuery(query);

// STEP 4b(2): To view the elements in ResultSet,

     while(rs.next())
      {
          String nameDB=rs.getString("name"); //name is column name in Database.
          String ageDB=rs.getString("age"); //age is coulumn name in Database.
%>
<td> <%out.println(nameDB);%> </td>
<td> <%out.println(ageDB);%> </td>
</tr>
<%
    } //End of while loop
    stm.close();
    con.close();
%>
</table>
</body>
</html>

NOTE
  • rs doesnot point to your first row.First time rs.next() is encountered then only first row of database is retrieved.Next time you give rs.next() second row is got and so on.
  • The sid is for oracle. For DB2 give your database name.
  • URL is given for oracle. For DB2 go for "jdbc:db2://localhost:50000/MYDB" ( where MYDB is your DB name)
  • Database username and password are given above.For DB2 you can also use OS User Accounts.In your OS, user Name is DB2ADMIN and the password is db2admin. This account will be created automatically once you install DB2 in your system.
  • For DB2, driver Name is com.ibm.db2.jcc.DB2Driver
  • Make sure you have the jar files in your project library which has the driver class to be loaded.
  •  Dont think it as big task as the length is big, You can incorporate all declarations above in single line.
    In order for clear understanding only, I have explained the program briefly.
    Otherwise its too simple

4)MANAGING SESSIONS

Go to Examples
1)login.jsp
<html>
<head>
<title> Login page </title>
</head>
<body>
<form action="validate.jsp">
<%
    // By default the method is GET
%>
User Name: <input type="text" name="uname"/> <br/>
Password : <input type="password" name="passwd"/> <br/>
<input type"submit" value="LOGIN"/>
</form>
</body>
</html>  

2)SetSession.jsp
<html>
<head>
<title> Set session </title>
</head> 
<body>
<%
String uname=request.getParameter("uname");
String passwd=request.getParameter("passwd");
//After validating with actual uname and password
//To create a session
session.setAttribute("username",uname);
%>
</body>
</html>

3)home.jsp
<html>
<head>
<title> Home Page </title>
</head> 
<body>
<%
if(session.getAttribute("username")==null)
{
%>
<jsp:forward page="login.jsp">
<jsp:param name="error" value="Login to view this page"/>
</jsp:forward>
<%
}
String name=(String)session.getAttribute("username");
out.println("Hello, "+name+" <a href=invalidate.jsp>LOGOUT</a>");
%>
</body>
</html>

4)invalidate.jsp

<html>
<head>
<title> Home Page </title>
<body>
<%
//To invalidate current session,
session.invalidate();
%>
</body>
</html>

NOTE
  • The class or the interface name of the object session is http.HttpSession. The object session is of type Javax.servlet.http.httpsession.
  • If there is no session , session.setAttribute("attributname",value) creates a new session and sets the attribute and corresponding value in that session object.
  • session.getAttribute("attributename" is used to get session value.
  • session.invalidate() is used to clear the session which is set.

4 comments:

RAMESHKUMAR.R said...

Thanks machi really usefull one keep it up!

♪♪♪мα∂∂у♪♪♪ said...

Thank you!!!

shakthi said...

very simple nd informative post buddy !!

♪♪♪мα∂∂у♪♪♪ said...

Thanks Shakthi..
If Mechanical student can understand then great..
Mission accomplished..