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>