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

Friday, October 5, 2007

Simple XSL Transformation

This article demonstrates the xsl transformation in java.

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

This demonstrates the usage of Properties file where the commom values used through out the project can be stored.
-----------------------------------------------------------------------------------------------------------------

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

The only difference is that the pathname specified in 'ServletRequest.getRequestDispatcher' does not require a leading slash, so you can use it with a relative URL. 'ServletContext.getRequestDispatcher' requires a leading slash.

Example:

RequestDispatcher dispatcher=request.getRequestDispatcher("Coreservlet");
(or)
RequestDispatcher dispatcher=request.getRequestDispatcher("/Coreservlet");


But,

RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher
("/Coreservlet");

dispatcher.forward() and response.sendRedirect()

dispatcher.forward()

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

The Singleton design pattern is used for,
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

These are Jsp system defined objects. We no need to create these objects to access them.

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);