March 23, 2011

Spring Framework 2.0 - Spring AOP Hello World Example

Complete the Spring Hello World example as in this post - http://www.javaissues.com/2011/03/spring-framework-20-hello-world-example.html

Download additional jars (aspectjrt.jar and aspectjweaver.jar) from the link here and copy them into the lib folder of the web application.

1) Create a Java class, MyAdvice.java as below,

package info.icontraining.spring;

public class MyAdvice {

   public void myBeforeMethod() {
      System.out.println("Before Execution");
   }
 
   public void myAfterMethod() {
      System.out.println("After Execution");
   }
}

2) Configure the MyAdvice bean in the Spring configuration file, applicationContext.xml

<bean id="myAdvice" class="info.icontraining.spring.MyAdvice" />

3) Configure the AOP configuration in the Spring configuration file, applicationContext.xml below the MyAdvice bean configuration

<aop:config>
   <aop:aspect ref="myAdvice">
       <aop:before method="myBeforeMethod" 
          pointcut="execution (* *.sayGreeting())" />
       <aop:after-returning method="myAfterMethod" 
          pointcut="execution (* *.sayGreeting())" />
   </aop:aspect>
</aop:config>

4) Access the springHelloWorld.jsp page - check the server console log to see if the advice methods are invoked.

http://localhost:8080/WebAppName/springHelloWorld.jsp

March 21, 2011

Effect of static keyword on variables and methods in Java

Effect of static on variables


The static keyword can be applied to instance variables and cannot be applied to local variables. Marking an instance variable as static makes its cease to be an instance variable and become a static variable.


There is exactly one copy of the static variable irrespective of the number of objects of that class (0 to n) and the static variable can be accessed on the class name.


Sometimes, static variables are also referred to as class variables.

public class Test {

   private static int i;

   public void m1() {
      System.out.println("static i = " + Test.i);
   }

   public static void m2() {
      System.out.println("static i = " + Test.i);
   }    
}


Effect of static on methods


The static keyword can be applied on instance methods. Just as with instance variables, application of the static keyword on an instance method makes it cease to be an instance method and become a static method.


A static method can be invoked on the class name irrespective of the objects of that class. Static methods within a class can access static variables only, accessing instance variables directly from a static method is not allowed.


However, instance variables can be accessed from within a static method via an object reference variable.


For more example of member access from a static method/context, refer - http://www.javaissues.com/2011/02/access-issues-from-static-context-in.html

public class Test {

   int i;
   static int j;
     
   public static void m1() {
      System.out.println("Method m1");
      i = 3;       // not allowed, will not compile
      j = 2;       // allowed

      Test t = new Test();
      t.i = 3;     // now i can be accessed
   }
}

March 15, 2011

Spring Framework 2.0 - Hello World Example

Download the Spring Framework 2.0 jars from the link here and unzip the jars and add to the lib folder of the web application.

1) Create a GreetingService.java interface

package info.icontraining.spring;

public interface GreetingService {
   public String sayGreeting();
}

2) Create a GreetingServiceImpl.java class that implements the GreetingService interface

package info.icontraining.spring;

public class GreetingServiceImpl implements GreetingService {
   private String greeting;

   public GreetingServiceImpl() {}

   public GreetingServiceImpl(String greeting) {
      this.greeting = greeting;
   }

   public String sayGreeting() {
      return this.greeting;
   }

   public void setGreeting(String greeting) {
      this.greeting = greeting;
   }
}

3) Create a new applicationContext.xml file in the WEB-INF folder of the web application

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd" >

   <bean id="greetingService"
         class="info.icontraining.spring.GreetingServiceImpl">
         <property name="greeting">
             <value>Hello World!</value>
         </property>
   </bean>

</beans>

4) Modify the web.xml file to add the following content,

<web-app ...>
...
  <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
 
  <listener>
      <listener-class>
       org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>

...
</web-app>

5) Create a springHelloWorld.jsp file in the WebContent folder


<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

 <% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 GreetingService greetingService = (GreetingService)factory.getBean("greetingService");
 %>

 <%=greetingService.sayGreeting() %>

</body>
</html>


6) Open the following URL in your browser,

http://localhost:8080/WebAppName/springHelloWorld.jsp

Struts 1.x - Validator Framework Example

We shall replace the validate() method in this example - http://www.javaissues.com/2011/03/struts-1x-reset-and-validate-methods-in.html with the Validator Framework

In addition to the Struts 1.3.8 jars and the Apache Commons jars, also add the Jakarta-Oro jar into the lib folder of your application. Download the oro jar from here

1) Change the LoginForm.java file to make the LoginForm class extend from the ValidatorForm class instead of the ActionForm class. Also remove the validate() method from the LoginForm class.

public class LoginForm extends ValidatorForm {
      ...
}


2) Modify the struts-config.xml file to add the <plug-in> element,

<struts-config>
   ...   
   <message-resources parameter="ApplicationResources" />

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


3) Add a new validation.xml file to the WEB-INF folder of the web application, as below. This configuration will validate the username and password fields for required field validation and also for the form input to comply/match the regular expressions.

<!DOCTYPE form-validation PUBLIC
        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
        "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

<form-validation>
 
   <global>
      <constant>
         <constant-name>id</constant-name>
         <constant-value>^([a-zA-Z_]{1}[a-zA-Z0-9_-]{7,14})$</constant-value>
      </constant>
      <constant>
         <constant-name>pass</constant-name>
         <constant-value>^([a-zA-Z0-9_-]{8,15})$</constant-value>
      </constant>
   </global>

   <formset>
      <form name="loginForm">
         <field property="username" depends="required,mask">
            <arg position="0" key="username.required"/>
            <var>
               <var-name>mask</var-name>
               <var-value>${id}</var-value>
            </var>
         </field>
         <field property="password" depends="required,mask">
            <arg position="0" key="password.required"/>
            <msg name="mask" key="password.maskmsg" />
            <var>
               <var-name>mask</var-name>
               <var-value>${pass}</var-value>
            </var>
         </field>
      </form>
   </formset>
 
</form-validation>


4) In the message resources bundle, the ApplicationResources.properties file, add the following messages,

# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.

username.required=Username
password.required=Password
password.maskmsg=Password should be of length between 8 and 15 characters


5) Open the following URL in the browser and test for required field validation as well as form field input validation that complies with the regular expressions in the validation.xml

http://localhost:8080/WebAppName/login.jsp

March 7, 2011

Struts 1.x - reset() and validate() methods in ActionForm

To setup the Struts Framework in your J2EE web application, visit the following post - http://www.javaissues.com/2011/03/struts-1x-hello-world-example.html

Create login.jsp

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html>
<body>
   <html:errors />
   <form action="login.do" method="post">
      <input type="text" name="username" /> <br/>
      <input type="password" name="password" /> <br/>
      <input type="submit" value="Submit" />
   </form>
</body>
</html>


Create LoginForm.java

package info.icontraining.struts;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public class LoginForm extends ActionForm {

   private String username;
   private String password;
 
   public String getUsername() {
      return username;
   }
   
   public void setUsername(String username) {
      this.username = username;
   }
 
   public String getPassword() {
      return password;
   }
 
   public void setPassword(String password) {
      this.password = password;
   }
 
   public void reset(ActionMapping mapping, HttpServletRequest request) {
      username = null;
      password = null;
   }
 
   public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
      ActionErrors errors = new ActionErrors();
  
      if ((username == null) || (username.length() <= 0) ) {
          errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.username"));
      }
      if ((password == null) || (password.length() < 8)) {
          errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.password"));
      }
      return errors;
   }
}


Create LoginAction.java

package info.icontraining.struts;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.struts.action.*;

public class LoginAction extends Action {

   public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
  
      String username = ((LoginForm)form).getUsername();
      String password = ((LoginForm)form).getPassword();
  
      if (username.equals("abc") && password.equals("def")) {
          return mapping.findForward("success");
      } else {
          return mapping.findForward("failure");
      }  
   }
}


Create ApplicationResources.properties and place it in the src folder (in Eclipse) or in the default package

error.username=Username is required<br/>
error.password=Password must contain minimum 8 characters<br/>


Add the following configuration to struts-config.xml

<struts-config>
...
   <form-bean name="loginForm" type="info.icontraining.struts.LoginForm" />
   ...

   <action path="/login" type="info.icontraining.struts.LoginAction" name="loginForm" validate="true" input="/login.jsp"> 
      <forward name="success" path="/loginSuccess.jsp" />
      <forward name="failure" path="/loginFailure.jsp" /> 
   </action>

   ...
   <message-resources parameter="ApplicationResources" />
...
</struts-config>


Visit the following URL in the browser,

http://localhost:8080/WebAppName/login.jsp

javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE


Topic:  Struts 1.3.8

Application Server: JBoss 4.2.2GA

Exception:


ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE
at org.apache.struts.taglib.TagUtils.retrieveMessageResources(TagUtils.java:1112)
at org.apache.struts.taglib.TagUtils.present(TagUtils.java:1055)
at org.apache.struts.taglib.html.ErrorsTag.doStartTag(ErrorsTag.java:200)
at org.apache.jsp.login_jsp._jspx_meth_html_005ferrors_005f0(login_jsp.java:156)
at org.apache.jsp.login_jsp._jspx_meth_html_005fform_005f0(login_jsp.java:112)
at org.apache.jsp.login_jsp._jspService(login_jsp.java:77)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:336)



Resolution:

To resolve this error, first add a message resources bundle (a .properties file) to the Struts-enabled web application - the file should be placed in the classpath of the application.

Next, configure the file information in the struts-config.xml Struts configuration file, by adding the <message-resources> element as below,

<message-resources parameter="resources.ApplicationResources" />

where resources.ApplicationResources is the fully-qualified name (reflecting the package structure) of the file ApplicationResources.properties (the .properties extension is not required in the configuration).

March 6, 2011

Struts 1.x - Hello World Example

Download the Struts 1.3.8 jars from here, unzip and copy them to the lib folder of the web application

Download the Apache Commons jars (Struts dependencies) from here, unzip and also copy to the lib folder of the web application

Add the following Servlet configuration to the web.xml file of the web application:

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>application</param-name>
      <param-value>resources.application</param-value>
    </init-param>
    <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>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>


Create a struts-config.xml file in the WEB-INF folder of the web application and add the following content in it:

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

<struts-config>

  <form-beans>
     <form-bean name="helloForm" type="info.icontraining.struts.HelloForm" /> 
  </form-beans>

  <action-mappings>
     <action path="/hello" type="info.icontraining.struts.HelloAction" name="helloForm"> 
   <forward name="success" path="/hello.jsp" /> 
     </action> 

  </action-mappings>

</struts-config>


Create a welcome.jsp page

<html>
<body>
<form action="hello.do" method="post">
<input type="text" name="user" />
<input type="submit" name="Submit" />
</form>
</body>
</html>


Create a HelloForm.java class

package info.icontraining.struts;

import org.apache.struts.action.ActionForm;

public class HelloForm extends ActionForm {
 
   private String user;

   public String getUser() {
      return user;
   }

   public void setUser(String user) {
      this.user = user;
   }
}


Create a HelloAction.java class

package info.icontraining.struts;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class HelloAction extends Action {
 
   public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    
      request.setAttribute("user", ((HelloForm)form).getUser()); 
      return mapping.findForward("success");
   }
}


Create a hello.jsp page

<%@ page isELIgnored="false" %>
<html>
<body>
Welcome, ${requestScope.user}
</body>
</html>


Enter the following URL in the browser to test:

http://localhost:8080/WebAppName/welcome.jsp

March 2, 2011

JSTL 1.1 - <c:choose>, <c:when> and <c:otherwise> example


<c:set var="userType" scope="request" value="none" />
<c:choose>
   <c:when test="${requestScope.userType == 'regular'}">
      Welcome! You are a regular user.
   </c:when>
   <c:when test="${requestScope.userType == 'premium'}">
      Welcome! You are a premium user.
   </c:when>
   <c:otherwise>
      Welcome! You are not a registered user.
   </c:otherwise>
</c:choose>

prints,

Welcome! You are not a registered user.

JSTL 1.1 - <c:forTokens> example


Example 1:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table border="1">
   <c:forTokens var="element" items="t1;t2/t3;t4/t5;t6,t7,t8;t9" delims=";,/"  varStatus="c">
      <tr>
         <td>${c.count}</td>
         <td>${element}</td>
      </tr>
   </c:forTokens>
</table>

prints,

1t1
2t2
3t3
4t4
5t5
6t6
7t7
8t8
9t9

Example 2:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="testString" scope="application" value="t1;t2/t3;t4/t5/t6,t7,t8;t9" />
<table border="1">
   <c:forTokens var="element" items="t1;t2/t3;t4/t5;t6,t7,t8;t9" delims=";,/"  varStatus="c" begin="1" end="7" step="2">
      <tr>
         <td>${c.count}</td>
         <td>${element}</td>
      </tr>
   </c:forTokens>
</table>

prints,



1t2
2t4
3t6
4t8

JSTL 1.1 - <c:catch> example


<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:catch var="ex" >
   <% int j=3/0; %>
</c:catch>
<c:out value="${ex.message}" />

prints,

/ by zero

JSTL 1.1 - <c:remove> example


<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="name" value="Dinesh" scope="session" />
<c:out value="${sessionScope.name}" /><br/>
<c:remove var="person" scope="session" />
<c:out value="${sessionScope.name}" /><br/>


prints, (the second <c:out> does not display anything)


Dinesh



JSTL 1.1 - <c:set> example

Example 1: Setting an attribute in some scope

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="userType" scope="request" value="premium" />
<c:out value="${requestScope.userType}" default="normal" />

prints,

premium


Example 2: setting JavaBean property
Note: PersonBean.java is a simple JavaBean with properties firstName and age


<%@ page import="info.icontraining.beans.PersonBean"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
 PersonBean p = new PersonBean();
 session.setAttribute("person", p);
%>
<c:set target="${sessionScope.person}" property="firstName" value="Dinesh" />
<c:set target="${sessionScope.person}" property="age" value="32" />
<c:out value="${sessionScope.person.firstName}" /><br/>
<c:out value="${sessionScope.person.age}" /><br/>


prints,

Dinesh
32


Example 2: setting a key-value pair in a Map
Note: PersonBean.java is a simple JavaBean with properties firstName and age

<%@ page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% 
   Map m = new HashMap();
   session.setAttribute("map", m);
%>
<c:set target="${sessionScope.map}" property="firstName" value="Dinesh" />
<c:set target="${sessionScope.map}" property="lastName" value="PC" />
<c:out value="${sessionScope.map.firstName}" /><br/>
<c:out value="${sessionScope.map.lastName}" /><br/>

prints,

Dinesh
PC

JSTL 1.1 - <c:if> example


<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<% request.setAttribute("userType","premium"); %>
<c:if test="${requestScope.userType == 'premium'}" var="isPremiumMember" scope="session" >
   Welcome! You are a privileged customer.
</c:if>
<br/>
<c:out value="${sessionScope.isPremiumMember}" />

prints,

Welcome! You are a privileged customer.
true

JSTL 1.1 - <c:forEach> example

test.jsp

Example 1:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
   String[] arr = new String[] {"dog", "cat", "pig", "cow"};
   application.setAttribute("arrayAttribute", arr);
%>

<table border="1">
<c:forEach var="element" items="${arrayAttribute}" varStatus="c">
 <tr><td>${c.count}</td>
 <td>${element}</td></tr>
</c:forEach>
</table>

prints,


1dog
2cat
3pig
4cow


Example 2:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
   String[] arr = new String[] {"dog", "cat", "pig", "cow", "horse", "rhino", "hippo"};
   application.setAttribute("arrayAttribute", arr);
%>

<table border="1">
<c:forEach var="element" items="${arrayAttribute}" varStatus="c" begin="1" end="5" step="2">
 <tr><td>${c.count}</td>
 <td>${element}</td></tr>
</c:forEach>
</table>

prints,


1cat
2cow
3rhino

JSTL 1.1 - <c:out> example

test.jsp


Example 1:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="<h1>Hello</h1>" escapeXml="false" />

prints:

Hello


Example 2:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="<h1>Hello</h1>" escapeXml="true" />

prints:

<h1>Hello</h1>

Example 3:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% session.setAttribute("cart",null); %>
<c:out value="${sessionScope.cart}" default="Shopping Cart is Empty" />

prints:

Shopping Cart is Empty  (when ${sessionScope.cart} evaluates to a null value)