Thursday, March 31, 2011

Post List of objects from jsp to Struts action

How to pass objects list from jsp to Struts?
How to post objects list from jsp to Struts?
Struts 2 framework have provided very powerful features using OGNL to post list of Objects from jsp to Struts 2 Action class.

Here is the example of passing list of objects from jsp to Struts.

We must have Struts 2 framework with OGNL script.
Following example will allows you to add multiple user list at the same time from jsp.
Code of required POJO, Acion Class and Jsp to post list of Person Object from jsp to action class are written below.

Person.Java Pojo
public class Person 
{    
    int person_id;
    String name;
    String address;
    public int getPerson_id() {
        return person_id;
    }
    public void setPerson_id(int personId) {
        person_id = personId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
Struts 2 Action Class
@ParentPackage("default")
public class ManageUsers extends ActionSupport  
{
    List<Person> personList ;
    @Action(value="addUserList",results={
            @Result(name=ActionSupport.SUCCESS,location="addPersonList",type="tiles")})
    public String execute() throws Exception
    {      
        if(personList==null)
        {         
            personList = new ArrayList<Person>();
        }      
        Person p = new Person();
        p.setName("NAME");
        personList.add(p);      
        return SUCCESS;
    }
    public List<Person> getPersonList() {
        return personList;
    }
    public void setPersonList(List<Person> personList) {
        this.personList = personList;
    }
}
JSP
<s:if test="personList != null && personList.size > 0">
        <tr>
            <th width="50%">Person Name</th>
            <th width="50%">Address</th>
        </tr>
    <s:iterator value="personList"  status="p">
        <tr>
            <td><s:textfield name="personList[%{#p.index}].name" /></td>
             <td><s:textfield name="personList[%{#p.index}].address" /></td>
        </tr>
    </s:iterator>
    </s:if>




Monday, March 28, 2011

Sort ArrayList In Java

We have multiple options to sort ArrayList in Java. We can use iterator , iterate each and every element of ArrayList & use any sorting algorithm to sort.
But Collection framework of Java also provide sort method.

Sort Array List in Java with Examples:

List data = new ArrayList();
data.add(4);
data.add(2);
data.add(1);
data.add(3);


Collections.sort(data);

Add two Arrays


Adding two arrays in java, 
Using Commons lib (but you require commons-lang.jar file)
//import org.apache.commons.lang.ArrayUtils;
String[]first = new String[]{"1","2"};
String[]second = new String[]{"1","2"};
String[] both = (String[]) ArrayUtils.addAll(first, second);
Using JAVA API only
String[] f(String[] first, String[] second) {
    List<String> both = new ArrayList<String>(first.length + second.length);
    Collections.addAll(both, first);
    Collections.addAll(both, second);
    return both.toArray(new String[] {});
}

Friday, March 25, 2011

JSP Servlets for beginner


 Servlets
Servlets are Java technology’s answer to Common Gateway Interface (CGI) programming. They are programs that run on a Web server, acting as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Their job is to:

1. Read any data sent by the user
This data is usually entered in a form on a Web page, but could also come from a Java applet or a custom HTTP client program.

2. Look up any other information about the request that is embedded in the HTTP request
This information includes details about browser capabilities, cookies, the host name of the requesting client, and so forth.

3. Generate the results
This process may require talking to a database, executing an RMI or CORBA call, invoking a legacy application, or computing the response directly.

4. Format the results inside a document
In most cases, this involves embedding the information inside an HTML page.

5. Set the appropriate HTTP response parameters
This means telling the browser what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

6. Send the document back to the client
This document may be sent in text format (HTML), binary format (GIF images), or even in a compressed format like gzip that is layered on top of some other underlying format.

4. JavaServer Pages
JavaServer Pages (JSP) technology enables us to mix regular, static HTML with dynamically generated content from servlets. Many Web pages that are built by CGI programs are primarily static, with the parts that change limited to a few small locations. For example, the initial page at most on-line stores is the same for all visitors, except for a small welcome message giving the visitor’s name if it is known. But most CGI variations, including servlets, make us generate the entire page via our program, even though most of it is always the same. JSP lets us to create the two parts separately. Most of the page consists of regular HTML, which is passed to the visitor unchanged. Parts that are generated dynamically are marked with special HTML-like tags and mixed right into the page.

4.1 JSP Processing
A JSP page is simply an HTML page that contains special instructions to execute Java code throughout the page. A J2EE web container capable of processing servlets and JSP pages handles the page. The web container has a servlet engine that will go through a series of steps to deliver the results of the JSP page.

Figure 1: JSP processing steps
The first time a JSP page is requested, the servlet engine will read the file and generate source code to create a servlet. The code compiles and the servlet loads. Once loaded, it handles requests in the same manner as any other servlet. The only difference is that each time a request is made of a JSP file, the timestamp of the file is checked against an embedded timestamp in the servlet. If the JSP file is newer, then it has to be compiled into a servlet and reloaded. This can have performance implications in many situations. For instance, let's say we have a web application that consists of a series of 40 different pages. The first person to use the application would have a horrible experience if they had to sit through the compilation of every page as they navigate their way through the system. Most J2EE web containers allow us to precompile our JSP files to avoid this performance problem. This also helps to alleviate the problem encountered when a page has compiler errors. We certainly would not want the user to see that. As we can imagine, a JSP page goes through a lifecycle similar to that of a servlet. When it's first loaded, the jspInit() method is called. Once loaded, the jspService() method is called to generate a response to the request. This method contains the servlet code that will output the HTML along with the results of the Java code contained in the JSP file. Before the servlet (JSP) is unloaded from the web container, the jspDestroy() method is called. The jspInit() and jspDestroy() methods can be overridden in the declarations section of the JSP page. The jspService() method cannot explicitly be overridden because it's a system generated method that corresponds to the body of the JSP page. Lets  look at how to override the jspInit() and jspDestroy() methods in a JSP page:
<%! public void jspInit() {
            // Initialization code (DB initialization, login to resources)
}
public void jspDestroy() {
            // Cleanup code (close system resources, cleanup filesystem)
}
%>

Figure 2: JSP-Servlet MVC


Configuration of web.xml in case of JSP and servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Project1</display-name>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>controller.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginC</url-pattern>
  </servlet-mapping>
 
</web-app>