Sunday, December 2, 2007
JSP - Synchronization
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 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
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
Friday, October 5, 2007
Simple XSL Transformation
The xsl transformation is done to translate the xml file content to any file formats. Namely- html, xhtml, etc
The xslt transformation can be done statically by including the 'xsl file' name in the xml file. But here we achieve this at run time. The java xslt code gets the xml file, xsl file and an output file as input through command line.
xml-file.xml
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Age of Empires</title>
<artist>Eric</artist>
<country>India</country>
<company>Pearl</company>
<price>15.90</price>
<year>1983</year>
</cd>
</catalog>
xsl-file.xsl
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="catalog">
<html>
<head>
<xsl:for-each select="cd">
<xsl:if test="country = 'India'">
<title><xsl:value-of select="country"/></title>
</xsl:if>
</xsl:for-each>
</head>
<body>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XSLTdemo.java
package xsltsample;
import java.io.File;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XSLTdemo {
public XSLTdemo() {
}
public static void main(String[] args) {
File xmlfile = new File("/techhome/mahesh/javaprograms/XSLTSample/xml-file.xml");
File xslfile = new File("/techhome/mahesh/javaprograms/XSLTSample/xsl-file.xsl");
File outfile = new File("/techhome/mahesh/javaprograms/XSLTSample/output-file");
TransformerFactory tf = TransformerFactory.newInstance();
try {
Transformer t = tf.newTransformer(new StreamSource(xslfile));
Source s = new StreamSource(xmlfile);
Result r = new StreamResult(outfile);
t.transform(s, r);
} catch (TransformerConfigurationException ex) {
ex.printStackTrace();
} catch (TransformerException ex) {
ex.printStackTrace();
}
}
}
output-file
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>India</title>
</head>
<body></body>
</html>
Wednesday, September 26, 2007
Usage of Properties file
-----------------------------------------------------------------------------------------------------------------
package com.mahesh.struts;
import java.util.ResourceBundle;
public class ResourceManager {
private static ResourceBundle bundle=ResourceBundle.getBundle("com.mahesh.struts.
ApplicationResources");
public static String getString(String key){
return bundle.getString(key)
}
}
com.mahesh.struts.ApplicationResources => This is a simple file having key-value pairs. The value can be retrieved from it using the key. The value can be retrieved using the "getString(key)" method.
The key-value pairs will be written in "com.mahesh.struts.ApplicationResources" is as shown below,
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://192.168.1.125:3306/
database.user=root
database.password=passwd
The values are retrieved using the key as shown below,
String driverClass = ResourceManager.getString("database.driver");
String dbUrl = ResourceManager.getString("database.url");
String dbUser = ResourceManager.getString("database.user");
String dbPassword = ResourceManager.getString("database.password");
request.getRequestDispatcher and getServletContext().getRequestDispatcher
Example:
RequestDispatcher dispatcher=request.getRequestDispatcher("Coreservlet");
(or)
RequestDispatcher dispatcher=request.getRequestDispatcher("/Coreservlet");
But,
RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher
("/Coreservlet");
dispatcher.forward() and response.sendRedirect()
This will forward all the request parameters to the jsp/servlet mentioned in
RequestDispatcher dispatcher=request.getRequestDispatcher("/Coreservlet");
But the url in the browser will remain the same.
response.sendRedirect()
This will forward all the request parameters to the jsp/servlet mentioned in
response.sendRedirect("/MVC2practice/Coreservlet");
But the url in the browser will not remain the same.
With a sendRedirect(), the only way to pass data is through the session or with web parameters (url?name=value). It does not handle request parameters here as done in "dispatcher.forward(req,res);"
Singleton design pattern
1. to create only one object of a class at a time, and
2. that too the object can be created only by its own class.
Necessiates
1. The class' s constructor has to be declared 'private' . This makes the class to create its object by itself only.
2. The clone() method has to be overridden from the base class. This avoids the object to be cloned by any other class.
3. The instantiation (object creation) is done in its own method. And that method should be synchronized and should be declared static.
4. It is declared static because, only then the other classes can call the method without object.
Example:
class Singleton {
private static Singleton singletonObject;
// A private Constructor prevents any other class from instantiating.
private Singleton() {
// Optional Code
}
public static synchronized Singleton getSingletonObject() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
public class SingletonObjectDemo {
public static void main(String args[]) {
// Singleton obj = new Singleton(); Compilation error not allowed
//create the Singleton Object..
Singleton obj = Singleton.getSingletonObject();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}
JSP Implicit Objects
1. out
out.println("mahesh");
2. request
request.getParameter("abc");
request.getSession();
etc
3. response
response.getWriter();
4. session
session.isNew();
session.getAttribute("abc");
session.setAttribute("abc",123);
session.removeAttribute("abc");
session.getAttributeNames();
session.getServletContext(();
session.invalidate();
5. pageContext
pageContext.getServletContext();
pageContext.getServletConfig();
pageContext.getSession();
pageContext.getRequest();
pageContext.getResponse();
pageContext.getAttribute("abc");
pageContext.setAttribute("abc",123);
6. page
7. config
config.getServletContext();
config.getInitParameter("abc");
config.getInitParameterNames();
config.getServletName();
8.application
application.getInitParameter("abc"); //here this refers to context parameters becoz this is application.
application.getInitParameterNames();
application.getAttribute("abc");
application.setAttribute("abc",123);
application.removeAttribute("abc");
application.getRequestDispatcher(String path);
Sunday, July 22, 2007
When do we go for Abstract classes and when do we go for Interfaces in java
Abstract class is a class that contains 0 or more abstract methods and also ordinary methods. Interface is specification of method prototypes(all abstract methods only).
Whenever the developers wants to use some features be shared by all objects(different classes), that time they go for abstract class.
When the developers wants different implementation for every objects then they go for interface.
We cannot create the object for abstract and interface. Instead we can create the reference of abstract class and interface.
Method Overriding versus Variable Shadowing in java
class A {
int i = 1;
int f() {
return i;
}
}
class B extends A {
int i = 2; // Shadows variable i in class A.
int f() {
return -i;
} // Overrides method f in class A.
}
public class Override_test {
public static void main(String args[]) {
B b = new B();
System.out.println(b.i); // Refers to B.i; prints 2.
System.out.println(b.f()); // Refers to B.f(); prints -2.
A a = (A) b; // Cast b to an instance of class A.
System.out.println(a.i); // Now refers to A.i; prints 1;
System.out.println(a.f()); // Still refers to B.f(); prints -2;
}
}
Another example of method overriding and variable shadowing
class Parent {
String classStr = "Parent";
void test() {
getClassName();
System.out.println(classStr);
}
void getClassName() {
System.out.println("Parent");
}
}
class Child extends Parent {
String classStr = "Child";
void test() {
super.test();
}
void getClassName() {
System.out.println("Child");
}
}
public class Main {
public static void main(String a[]) {
Child child = new Child();
child.test();
}
}
Output:
=======
Child
Parent
Thursday, July 19, 2007
Javascript for setting a timer for a page
var timerID = null;
var timerRunning = false;
var secondsleft = null;
function stopclock() {
if (timerRunning) {
clearTimeout(timerID);
timerRunning = false;
}
}
function startclock(s) {
secondsleft=s;
stopclock();
showtime();
}
function showtime() {
secondsleft = secondsleft - 1;
if (secondsleft == 60) {
alert("1 minute left");
}
if (secondsleft == 0) {
stopclock();
document.title ="Time over";
alert("Sorry Time's up");
window.document.getElementById("id_submitbutton").click();
//document.getElementById("mform1").submit();
} else {
current = secondsleft;
var hours = Math.floor( current / 3600 );
current = current - (hours*3600);
var minutes = Math.floor( current / 60 );
current = current - (minutes*60);
var seconds = current;
var timeValue = "" + hours;
timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
timeValue += ((seconds < 10) ? ":0" : ":") + seconds;
document.title = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
}
-----------------------------------------------------
In the above code, we can use either
window.document.getElementById("id_submitbutton").click();
or
document.getElementById("mform1").submit();
Wednesday, June 13, 2007
Passing parameters between servlets and jsp
First method is using session object depending on the application environment, for example
HttpSession ses = req.getSession(true);
ses.putValue("key","value");
you can get back this data in the second servlet by :
HttpSession ses = req.getSession(true);
String val1 = (String)ses.getValue("key");
Second method is using the,
request.getParameter ("key"); and
request.setParameter("key","value");
methods. These methods are used to retrieve parameters from forms or through querystring.
Third method is using the,
request.getAttribute("key"); and
request.setAttribute("key","value");
methods. These methods are used with RequestDispatcher class's object.
Ex. <% @ page import="java.util.*" %>
<%
request.setAttribute("username","mahesh");
RequestDispatcher dispatcher = request.getDispatcher("abc.jsp");
if(dispatcher != null) {
dispatcher.forward(request,response);
}
%>
abc.jsp
<% out.println(request.getAttribute("username"));
%>
Fourth method is using Java Beans,
getXXX() and
setXXX() methods.
Saturday, June 9, 2007
Regular Expression- Pattern Matching in java
Java provides a package called 'java.util.regex' for pattern matching.
The java.util.regex package has two classes and one exception class, the two classes namely - Pattern and Matcher.
A small example code given below validates the string with the given regular expression.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\d*"); //reg exp for 0 or more integers
Matcher matcher = null;
matcher = pattern.matcher("1111");
if (matcher.matches()) {
System.out.println("Matched");
} else {
System.out.println("Not Matched");
}
}
}
Similarly, there are more regular expression format and quantifiers.
Using Reflections in Java
Reflection is a powerful approach to analyze the class at runtime. If new classes are added into your application dynamically then Reflection is used to get the structure of the class.
Reflection uses special kind of java class: Class. The object of the Class type can hold all the information of the class and also have its own methods to retrieve all the information.
This example code extracts the structure of the String class. It will display the name of the constructors, declared fields and methods to the console.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
Class cl = Class.forName("java.lang.String");
Constructor cnst[] = cl.getConstructors();
Field fld[] = cl.getDeclaredFields();
Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class");
for (int i = 0; i < cnst.length ; i++) {
System.out.println(cnst[i].getName());
}
System.out.println("Name of the Declared fields");
for (int i = 0; i < fld.length; i++) {
System.out.println(fld[i].getName());
}
System.out.println("Name of the Methods");
for (int i = 0; i < mtd.length; i++) {
System.out.println(mtd[i].getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
To find the structure details of user defined classes, we need not use the Class.forName() method. Instead simply give the class name itself. And don't forget to import the package of that class.
Example:
Class cl = Userdefinedclass.class;
The Class.forName() method searches for the class given as argument, in the Java Class Library.
Passing unspecified number of arguments to a method in Java
An example code is given below..
public int add(char a,int... num ) //variable length argument
{
int no=num.length;
int sum=0;
for(int i=0;i!=no;i++)
sum+=num[i];
sum+=a;
return sum;
}
public static void main(String[] args) {
Main m=new Main();
System.out.println(m.add('A',10,20));
System.out.println(m.add('A',10,20,30));
}
Dynamic Method Dispatch in Java
A small example code is given below...
class A {
A() {
System.out.println("Constructor of Class A");
}
void show() {
System.out.println("I m in Class A");
}
}
class B extends A {
B() {
System.out.println("Constructor of Class B");
}
void show() {
System.out.println("I m in Class B");
}
}
public class DynamicMethodDispatch {
public static void main(String a[]) {
A aobj;
aobj = new A();
aobj.show();
aobj = new B();
aobj.show();
}
}
Output:
Constructor of Class A
I m in Class A
Constructor of Class A
Constructor of Class B
I m in Class B
Anonymous Inner Classes in Java
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class WindowAdapterTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Window Listener");
WindowListener listener = new WindowAdapter() { // anonymous class starts here
public void windowClosing(WindowEvent w) {
System.exit(0);
}
}; //anonymous class ends here
frame.addWindowListener(listener);
frame.setSize(300, 300);
frame.show();
}
}