Search This Blog

Loading...

Friday, June 13, 2008

Deadly Combination

Yes, Deadly combination!! It doesn't means that there would some super stars of the film who would go the devil place and finish him. No No !!

I am talking about the deadly combination used in the development of the web sites. I am talking about the tools used for the Java development. Any guesses so far....

Yes, they are Struts2, Spring, and Hibernate

I am currently working all these tools. I am amazed to see the power of all the three technologies and how they makes the life of a developer like me, so easy.
All of three would make your project a huge success.

Now talking about Struts2... It is great framework with the inbuilt Ajax tags that would help many developers. Many new features of the struts2 are marvelous.

Hibernate... I already told in my last post about this. Hibernate would provide you a greater facility for your data persistence. its in built architecture that is fully object oriented which makes it a powerful tool. And yes, not to forget about the HQL (Hibernate Query Language).

Spring... Again a master piece framework which lets you to do handle hibernate and specially the IOC (Inversion of Control) that lets programmers to walk to the higher level. Spring have many in built functionalities that help in various ways. One of them is scheduling of tasks. Before this you have to do manually write lots of code but now with a fewer code you can achieve greater flexibility.

So enjoy working with the deadly combination ......

Thursday, June 12, 2008

Hibernate Rocks

After few days working on hibernate I found it very interesting and useful tool for the developers. It allows to handle code more efficiently while working on the database part.
Since I am new to it I don't know all the features of the hibernate, but yes the features that I had used are tremendous and the code is more reliable and efficient.
All the connection management is handled by it. And specially the mapping files which allows us to connect to the database
i enjoyed working with it and hopes it will provide more features in the future.

Changing default style of <s:actionerror/> / <s:actionmessage/> tag

In struts 2 when you put <s:actionerror /> tag it displays the errors in the following way:

<ul>
<li>error 1</li>
<li>error 2</li>
</ul>


But sometimes it seems to be very ugly when displaying the dot (.) in the action errors or action messages

Below is a normal code that displays the tags in your customized way.
You can specify your own css for this

<s:if test="hasActionErrors()">
<s:iterator value="actionErrors">
<span class="errorMessage"><s:property escape="false" />
</span>
</s:iterator>
</s:if>
Alternatively you can change the file in the "/template/simple/actionerror.ftl” and put it in the /web-directory/struts/simple if using simple theme

Similar for <s:actionmessage /> tag.

Enjoy Struts

Session Check Interceptor

There must be some way to check that the current session is valid or invalid. This can be done using interceptors in struts in a very easy way.
Here I am giving an example how to resolve this.

First of all we will make an interceptor named SessionCheck.java.

package com.demo.interceptors;

import java.util.Collections;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class SessionCheck implements Interceptor {

public void init() {
}

public void destroy() {
}

public String intercept(ActionInvocation invocation) throws Exception {
ActionProxy proxy;
proxy = invocation.getProxy();
Map session = ActionContext.getContext().getSession();
Map results = proxy.getConfig().getResults();
/*
* We are checking that the user
* that is set at login time is null or not
*/
if (session.get("user") != null) {

return invocation.invoke();
} else {
/* Here we are passing the result to an
* invalid page by specifying its location
*/
ResultConfig rc = new ResultConfig("invalid",
"org.apache.struts2.views.freemarker.FreemarkerResult",
Collections.singletonMap("location",
"/com/demo/interceptors/invalid.jsp"));
results.put("invalid", rc);

return "invalid";
}

}
}

Now in struts.xml put the following code

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

<struts>
-----
---

<interceptors>

<interceptor name="SessionCheck"
class="com.demo.interceptors.SessionCheck" />
</interceptors>
<!—- We are using this because we want it to apply for each and every action -->
<default-interceptor-ref name="SessionCheck"/>


---
---
</struts>

Struts 2 Ajax drop down Example

Struts 2 has emerged as boon for developers. But the documentation available is very small. So I had decided to give a brief demonstration of the ajax used in struts 2.

In this example when u select from one drop down the other will populate accordingly. You can use it as it is or play with it. Enjoy !!

Index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:action name="ListingAction" executeResult="true"></s:action>

Listing.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<s:head theme="ajax" />
<title>Listing</title>
</head>
<script>
function show_details() {
dojo.event.topic.publish("show_detail");
}
</script>
<body>
<s:form id="frm_demo" name="frm_demo" theme="simple">
<table border="0">
<tr>
<td><s:select list="lstList1" name="lst"
onchange="javascript:show_details();return false;" ></s:select>
</td>
<td><s:url id="d_url" action="DetailAction" /> <s:div showLoadingText="false"
id="details" href="%{d_url}" theme="ajax"
listenTopics="show_detail" formId="frm_demo">
</s:div></td>
</tr>
</table>
</s:form>
</body>
</html>

Detail.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>

<s:if test="lstList != null">
<s:select list="lstList"></s:select>
</s:if>

DetailAction.java
package ajaxdemo.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class DetailAction extends ActionSupport {
private String lst;
private List lstList = null;
private List lstList2 = null;

public String execute() throws Exception {

if (getLst() != null && !getLst().equals("")) {
populateDetail(getLst());
return SUCCESS;
} else {
return SUCCESS;
}
}

private void populateDetail(String id) {
lstList = new ArrayList();
if (id.equalsIgnoreCase("Fruits")) {
lstList.add("Apple");
lstList.add("PineApple");
lstList.add("Mango");
lstList.add("Banana");
lstList.add("Grapes");
} else if (id.equalsIgnoreCase("Places")) {
lstList.add("New York");
lstList.add("Sydney");
lstList.add("California");
lstList.add("Switzerland");
lstList.add("Paris");
} else {
lstList.add("Other 1");
lstList.add("Other 2");
lstList.add("Other 3");
lstList.add("Other 4");
lstList.add("Other 5");
}
}

public List getLstList() {
return lstList;
}

public void setLstList(List lstList) {
this.lstList = lstList;
}

public String getLst() {
return lst;
}

public void setLst(String lst) {
this.lst= lst;
}
}

DetailListing.java
package ajaxdemo.action;

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;

public class ListingAction extends ActionSupport {
private List lstList1 = null;

public String execute() throws Exception {
populateDetail();
return SUCCESS;
}

private void populateDetail() {
lstList1 = new ArrayList();
lstList1.add("Fruits");
lstList1.add("Places");
lstList1.add("Others");

}

public List getLstList1() {
return lstList1;
}

public void setLstList1(List lstList1) {
this.lstList1 = lstList1;
}
}

Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="demo" extends="struts-default">
<action name="ListingAction" class="ajaxdemo.action. ListingAction">
<result>/listing.jsp</result>
</action>
<action name="DetailAction" class="ajaxdemo.action. DetailAction">
<result>/detail.jsp</result>
</action>
</package>
</struts>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Simple LDAP Authentication

This is a simple example through which we will connect to the LDAP Server and authenticate user.
I have used ApacheDS Server as a LDAP Server.

Install ApacheDS server and run it.
Following is a servlet used. make login.html and use as it

Login.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;

public class Login extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

public Login() {
super();
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

final String SUCCESS = "Success.html";
final String FAILURE = "Failure.html";
String strUrl = "login.html";
String username = request.getParameter("username");
String password = request.getParameter("password");

Hashtable env = new Hashtable(11);

boolean b = false;

env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid="+ username +",ou=system");
env.put(Context.SECURITY_CREDENTIALS, password);

try {
// Create initial context
DirContext ctx = new InitialDirContext(env);

// Close the context when we're done
b = true;
ctx.close();

} catch (NamingException e) {
b = false;
}finally{
if(b){
System.out.print("Success");
strUrl = SUCCESS;
}else{
System.out.print("Failure");
strUrl = FAILURE;
}
}
RequestDispatcher rd = request.getRequestDispatcher(strUrl);
rd.forward(request, response);

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
}
Enjoy LDAP!! :)

Performance Increase

Many of us passes through the same situation of having a low performance of our application. But if you follow some of the tips and tricks below you will soon realize the increase in the performance.

Collections
Always assign size to ArrayLists and other collections. Ex:
Collection c = new ArrayList(10);


Strings
Always use
String abc = "I love Java";instead of
String abc = new String("I love Java");


JDBC
Always close these statements after use:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("databaseUrl","username","password");
Statement stmt = conn.createStatement();
String strSql = "select * from abc";
ResultSet rs = stmt.executeQuery("strSql");// close these
stmt.close();
rs.close();
conn.close();
strSql=null;


Use only the required columns in select query:
Select FIRSTNAME,LASTNAME from PERSON;

instead of
Select * from Person;


JSP
Use session object as compared to hidden values, url rewriting and cookies

Use
System.out.print()
instead of
System.out.println();
wherever necessary

Everywhere Java

Java is everywhere from your shoes to mars and from mobiles to big dream machines and from your favorite bike to space shuttles.

You can't even escape Java if you are a programmer or a developer.

Struts2

Struts 2 is a new framework for the java developers. It is a combination of Struts 1 + Webworks formally known as Struts Ti. It is available with the enhanced quality of code and helps developers to work in a more organized way.

In built Ajax functionality is a boon for the developers. When I started working on the Struts 2. I felt that it may be very hard to learn but not actually. It is far easier then I thought. I haven’t work on other frameworks like Tapestry, Wicket, Spring etc. but I know what I am doing is good enough for me.

All frameworks provide there own way of style of coding which are good in there respect.

In built Interceptors provided a great functionality that helps in lots of situations. The one I like is a WaitAndExecute Interceptor. It is very helpful in situations when your action takes lots of time to execute. This interceptor displays a default page when your action is executing at background

Lots of more features are there for developers like Ajax functionality, themes to be used on pages, Inversion of Control.

I know that the documentation is little less but you know when a new technology grows it takes time. Struts 2 also one of them. The latest release of the Struts 2 is 2.0.11 which can be downloaded from Struts 2 home.

I had a Struts 2 forum on the nabble.com which can help you answer all your queries related to the Struts 2. You are welcome to post queries