Friday, January 4, 2008

Diff between calling a start()->run() method AND calling run() method directly without start() method

If the run() method of a Thread is called directly without start() method. It fails to obey properties of Thread. It acts as a normal method.

Example: without using start()

 class ThreadA extends Thread { 
ThreadA() {
}

public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am in run method " + i + " " + this.getName());
try {
this.sleep(500);
} catch (InterruptedException ie) {
System.out.println(ie);
}
}
}
}

public class Threadtest {
public Threadtest() {
}

public static void main(String[] args) {
Thread t1 = new Thread(new ThreadA(), "t1");
Thread t2 = new Thread(new ThreadA(), "t2");
t1.run();
t2.run();
}
}

The output will be:
I am in run method 0 Thread-0
I am in run method 1 Thread-0
I am in run method 2 Thread-0
I am in run method 3 Thread-0
I am in run method 4 Thread-0
I am in run method 0 Thread-1
I am in run method 1 Thread-1
I am in run method 2 Thread-1
I am in run method 3 Thread-1
I am in run method 4 Thread-1

But,
if the lines t1.run() and t2.run() are replaced by t1.start() and t2.start() then the output is,

I am in run method 0 Thread-0
I am in run method 0 Thread-1
I am in run method 1 Thread-1
I am in run method 1 Thread-0
I am in run method 2 Thread-0
I am in run method 2 Thread-1
I am in run method 3 Thread-1
I am in run method 3 Thread-0
I am in run method 4 Thread-0
I am in run method 4 Thread-1

How to handle exceptions in JSP?

You can catch exceptions in a JSP page like you would do in other Java classes. Simply put the code which can throw an exception/s between a try..catch block.

<%
try {
// Code which can throw can exception
} catch(Exception e) {
// Exception handler code here
}
%>


There is yet another useful way of catching exceptions in JSP pages. You can specify error page in the 'page' directive. Then if any exception is thrown, the control will be transferred to that error page where you can display a useful message to the user.

To demonstrate the run-time exception handling feature of JSP pages, we will build three pages.

* Form.html - Display a Form to the user to enter his or her age.
* FormHandler.jsp - A JSP Page which receives this value and prints it on the user screen.
* ExceptionHandler.jsp - An exception handler JSP page which is actually an error page to which control will be
passed when an exception is thrown.


Form.html page
--------------
<html>
<head>

</head>
<body>

<form action="FormHandler.jsp" method="post">
Enter your age ( in years ) :
<input type="text" name="age" />
<input type="submit" value="Submit" />
</form>

</body>
</html>


FormHandler.jsp
---------------
<%@ page errorPage="ExceptionHandler.jsp" %>
<html>
<head>

</head>
<body>

<%-- Form Handler Code --%>
<%
int age;
age = Integer.parseInt(request.getParameter("age"));
%>

<%-- Displaying User Age --%>

<p>Your age is : <%= age %> years.</p>

<p><a href="Form.html">Back</a>.</p>

</body>
</html>


ExceptionHandler.jsp
--------------------
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
<title>Exception Occurred!</title>
</head>
<body>

<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>

</body>
</html>


Conclusion:
-----------
Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing.

Thursday, January 3, 2008

Abstract classes and interfaces

Abstract classes
Abstract classes can have both abstract methods and concrete methods.
The abstract class should be preceded by an "abstract " keyword.
The abstract methods should also be preceded by an "abstract " keyword.
The abstract class may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

 abstract class Test { 
int x;
int y;

abstract void method1();
abstract void method2();

void concretemethod1() {
System.out.println("I am a concrete method");
}
void concretemethod2() {
System.out.println("I am a concrete method");
}
}


Interfaces
Interfaces can have only abstract methods.
The data-fields inside interfaces are 'public static final' by default.
So, the constants are declared inside interfaces (coding convention).
A class can extend only parent class, but an interface can extend many interfaces.

 interface Test { 
int x = 0;
void method1();
void method2();
}

What is MVC?

MVC - Model View Architecture. It is a type of Design pattern, followed extensively.

Model1(MVC1):

Browser -> JSP -> Bean -> DB
Browser <- JSP <- Bean <- DB

Model2(MVC2):

Browser -> Servlet -> JSP -> Bean -> DB
Browser <- JSP <- Bean <- DB

Here, servlet will instantiate the Bean

Sunday, December 2, 2007

JSP - Synchronization

By default JSP pages are Multithreaded(Multi-thread model), ie they are not synchronized.

Normally if we need to make a class synchronized, we implement SingleThreadModel interface.

In JSP, if that page has to be synchronized, we should add

<%@page isThreadSafe="false"%>

Or,

If some code inside the JSP page has to be synchronized, then the Implicit object "page" can be made use of.

<%
synchronized(page)
{
//code that needs to be synchronized
}
%>

Different Names, But same concept

Factory Methods

Factory method is just a fancy name for a method that instantiates objects.

Ex: In Singleton Design Pattern, we use a static synchronized method for instantiating object of that Singleton class.


Marker Interface or Tagged Interface

Interface without data-members and methods are called Marker Interface or Tagged Interface.

Ex: Serializable Interface

Thursday, October 18, 2007

Struts - sample application

Struts is a framework to implement MVC-2 architecture.

Model - Java bean
View - JSP
Controller - Struts (with servlets)

The main components of Struts are,

1. Action class - servlet
2. Action Form - bean
3. struts-config.xml

Example: "To validate a registered user"


register.jsp
========

 <%@page contentType="text/html"%>  
<%@page pageEncoding="UTF-8"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>

<body>
<html:form action="/register">
UserName :<html:text property="username"/><br>
Password :<html:password property="password1"/><br>
Reenter Password :<html:password property="password2"/><br>
<html:submit value="Register"/>
</html:form>
</body>
</html>


web.xml
======

 <?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
register.jsp
</welcome-file>
</welcome-file-list>
</web-app>


struts-config.xml
============

 <?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
<form-beans>
<form-bean name="RegisterForm" type="com.myapp.struts.RegisterForm"/>
</form-beans>

<action-mappings>
<action input="/register.jsp" name="RegisterForm" path="/register" scope="session"
type="com.myapp.struts.RegisterAction" validate="false">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.html"/>
</action>
</action-mappings>

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>

RegisterForm.java
=============

 package com.myapp.struts; 

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import com.myapp.struts.ConnectionObject;

public class RegisterForm extends org.apache.struts.action.ActionForm {

protected String username;
protected String password1;
protected String password2;

public RegisterForm() {
}

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}

public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}

public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
}



RegisterAction.java
=============

 package com.myapp.struts; 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

public class RegisterAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
RegisterForm rf = (RegisterForm) form;
String username = rf.getUsername();
String password1 = rf.getPassword1();
String password2 = rf.getPassword2();

if (password1.equals(password2)) {
try {
return mapping.findForward("success");
} catch (Exception e) {
return mapping.findForward("failure");
}
}
return mapping.findForward("failure");
}
}


Explanation:
========

'register.jsp' is the first page of the application. The username, password and reenter-password are filled and submit button is clicked. The form action has "/register" . So it calls the page '/register' . By default it has extension '.do'.
That is, /register.do

Then it just check the web.xml for servlet-mapping. In that, it is mapped in such a way that, for all *.do files, the servlet mapped is "org.apache.struts.action.ActionServlet" servlet. This is an in-built servlet.

This then checks the 'action' in 'action-mapping' tag of struts-config.xml file.


<action-mappings>
<action input="/register.jsp"
name="RegisterForm"
path="/register"
scope="session"
type="com.myapp.struts.RegisterAction"
validate="false" >
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.html"/>
</action>
</action-mappings>


In the action tag, input refers to from where the input was received
name refers to its corresponding Bean-class
type refers to its corresponding Action-servlet (for validation)
validate refers to whether or not we want to use the validation framework to automatically validate our
form

Here, the submitted fields are automatically set in the RegisterForm (bean) using setProperty methods. Then the RegisterAction class is called.

The RegisterAction class has a method "execute" having four parameters namely, 1. ActionMapping object 2. ActionForm object 3. HttpServletRequest 4. HttpServletResponse

Inside this "execute" method, validation takes place. And depending upon the success and failure of the validation, the appropriate page is called as in <action> tag
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.html"/>


A good link for struts:
http://learntechnology.net/content/struts/struts_lesson1.jsp