Wednesday, 21 November 2012

JSF :- Sample web application

//  Sample web application which gives basic information about jsf 

Step 1 :- Cretae a dynamic webproject in eclipse if you have plugin for faces create a faces project

Step 2 :- Download jsf-api-2.0.jar,jsf-impl.jar  these two jars and keep it in the lib folder

Step 3 :- Change the content in the web.xml in the following way

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" 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_3_0.xsd">
    <display-name>JsfTutorial1</display-name>
    <context-param>
        <description>
        The location where state information is saved.
Valid values are 'server' (typically saved in HttpSession) and 'client' (typically
saved as a hidden field in the form.
Default is server
.</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>server</param-value>
    </context-param>
    <context-param>
        <description>
        Comma-delimited list of context-relative resource paths under which the JSF implementation
will look for application configuration resources, before loading a configuration resource
named /WEB-INF/faces-config.xml (if such a resource exists).
</description>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value></param-value>
    </context-param>
    <context-param>
        <description>
        The default suffix for extension-mapped resources that contain JSF components.
Default is '.jsp'.
</description>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>
    <context-param>
        <description>
        A human readable string describing where this particular JSF application is
in the software development lifecycle.
Valid values are 'Development', 'UnitTest', 'SystemTest' and 'Production'.
Default is 'Production'.
This parameter is not available in JSF 1.x
.</description>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <description>
        Monitors Faces JSP files for modifications and synchronizes a running server with
the changes without restarting the server. If this parameter is set to false or
removed from the deployment descriptor, any changes made to Faces JSP files may
not be seen by the server until it is restarted. This parameter is usually set
to true while the Faces JSP files are being developed and debugged in order to
improve the performance of the development environment
.</description>
        <param-name>com.ibm.ws.jsf.JSP_UPDATE_CHECK</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>
        Load JSF runtime when the application server starts up. If this parameter is set to false or removed,
JSF runtime will be loaded and initialized when the first JSF request is processed.
This may disable custom JSF extensions, such as factories defined in the project.
</description>
        <param-name>com.ibm.ws.jsf.LOAD_FACES_CONFIG_AT_STARTUP</param-name>
        <param-value>true</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>//our main controller servlet
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <!-- Welcome page -->
    <welcome-file-list>
        <welcome-file>jsfs/hello.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Step 4 :- Create a faces-config.xml under the web-inf which is the main controller for faces frame work as given bellow








The above is the typical structure of the project
//faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    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-facesconfig_2_0.xsd"
    version="2.0">
   
</faces-config>

Step 5 :- Under webcontent make folder with name jsfs and create two xhtml as given above picture

//hello.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:body>
<h3>JSF 2.0 Hello World Example - hello.xhtml</h3>
    <h:form>
        <h:inputText value="#{helloBean.name}"></h:inputText>
        <h:commandButton value="WelcomeMe" action="welcome"></h:commandButton>
    </h:form>
</h:body>
</html>
        above helloBean is our bean class and name is a property in it the user entered value will be stored there , after clicking button it will go to welcome.xhtml mentioned in the action

//welcome.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>welcome</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:body bgcolor="white">
    <h3>JSF 2.0 Hello World Example - welcome.xhtml</h3>
    <h4>Welcome #{helloBean.name}</h4>
</h:body>
</html>

Step 6 :- Creation of HelloBean

package com.prac.jsfTutorial;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import java.io.Serializable;

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Step 7 :- Clean build the project and run it.

output :- 







After enterring value






After clicking submit

 

J2ee Tutorial Part 5 :- Exploring the Servlet Life Cycle

// Exploring the Servlet Life Cycle here we will closely observe the order of execution of lifecycle methods
import java.io.*;

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

public class LifeCycle extends HttpServlet {

    public static int instanceCount;
    {
        System.out.println("Doing static initialization on LifeCycle class");
        instanceCount = 0;

    }

    public void init() {
        System.out.println("In init() on LifeCycle");
    }

    public LifeCycle() {
        instanceCount++;
        System.out.println("In LifeCycle constructor");
    }

    public void destroy() {
        System.out.println("In destroy() on LifeCycle");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("In doGet() on LifeCycle");
        try {
            throw new Exception();
        } catch (Exception e) {
            // Just doing this to show doGet() called from service()
            e.printStackTrace();
        }
    }

}

Output :-//Bellow you can see the order in which lifecycle methods are called
Doing static initialization on LifeCycle class
In LifeCycle constructor
In init() on LifeCycle
In doGet() on LifeCycle
In destroy() on LifeCycle

J2ee Tutorial part 4:- Using HttpServletResponse to load a image

//Using HttpServletResponse to load a image and show in the web page

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
public class ImageLoader extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("image/gif");//setting the content type as image
        String path = getServletContext().getRealPath("tomcat.gif");//getting the image
        File imageFile = new File(path);
        long length = imageFile.length();
        response.setContentLength((int) length);
        OutputStream os = response.getOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(//reading image
                imageFile));
        int info;
        while ((info = bis.read()) > -1) {
            os.write(info);//writing to servlet output stream
        }
        os.flush();

    }

}

J2ee Tutorial part 3:- Reading HttpServletRequest Headers and Cookies

// Reading HttpServletRequest Headers and Cookies example

import java.io.*;
import java.util.*;

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

/**
 * This servlet exists to display all the parameters passed to it.
 */

public class RequestHeaders extends HttpServlet {

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

        // Set appropriate content type for response, and obtain
        // the HTML output stream.

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Set up start of HTML page
        out.write("<html>\n<head>\n<title>Display Request Headers</title>\n</head>\n<body>");

        Enumeration headerNames = request.getHeaderNames();//getting all headers
        out.write("<h2>Request Headers</h2>");
        out.write("<table border=\"1\"><tr><th>Header Name</th><th>Header Values</th></tr>");
        while (headerNames.hasMoreElements()) {
            out.write("<tr>");
            String headerName = (String) headerNames.nextElement();
            out.write("<td>" + headerName + "</td>");
            Enumeration headerValues = request.getHeaders(headerName);//passing header nameto get values
            out.write("<td>");
            while (headerValues.hasMoreElements()) {
                String headerValue = (String) headerValues.nextElement();
                out.write(headerValue + ";");
            }
            out.write("</td></tr>");
        }
        out.write("</table>");
       
        // Obtain HttpSession so you are likely to have at least one cookie
        HttpSession session = request.getSession();
       
        out.write("<h2>Cookie Details</h2>");
        Cookie[] cookies = request.getCookies();//getting all cookies
        int length = (cookies == null) ? 0 : cookies.length;
        for (int i = 0; i < length; i++) {
            Cookie cookie = cookies[i];
            out.write("<table border=\"1\"><tr><th>Cookie Attribute</th><th>Attribute Value</th></tr>");
            out.write("<tr><td>Name</td><td>" + cookie.getName() + "</td></tr>" );
            out.write("<tr><td>Value</td><td>" + cookie.getValue() + "</td></tr>" );
            out.write("<tr><td>Domain</td><td>" + cookie.getDomain() + "</td></tr>" );
            out.write("<tr><td>Path</td><td>" + cookie.getPath() + "</td></tr>" );
            out.write("<tr><td>Comment</td><td>" + cookie.getComment() + "</td></tr>" );
            out.write("<tr><td>MaxAge</td><td>" + cookie.getMaxAge() + "</td></tr>" );
            out.write("<tr><td>Version</td><td>" + cookie.getVersion() + "</td></tr>" );
            out.write("<tr><td>Secure</td><td>" + cookie.getSecure() + "</td></tr></table>" );
           }
       
        // Finish off the HTML page and close cleanly
        out.write("\n</body>\n</html>");
        out.close();

    }


}


Output ;-

POI-API :- Uploading a excel file and parsing it on server side using J2EE

//Uploading a excel file and parsing it on server side using apache file upload and poi api

Step 1 :- Download following jar files commons-io-1.4.jar,commons-fileupload-1.2.1.jar,poi-3.8-20120326.jar from apache website

Step 2 :- Create a dynamic web project and place the above jars in the lib folder

Step 3 :- Create a jsp which consits ui to upload a file

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><%@page
    language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>parseXlSheet</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form action="DemoParseServlet" method="post" enctype="multipart/form-data">
<input type="file" name="xlFile">
</br>
</br>
<input type="submit" value="Insert to db">
</form>
</body>
</html>

 

Step 4 :- Create a servlet which will take the xl file parse it and get required content

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * Servlet implementation class DemoParseServlet
 */
@WebServlet("/DemoParseServlet")
public class DemoParseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DemoParseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("entering in doget");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        System.out.println("filename:- " + fileName);
                        Workbook wb = new HSSFWorkbook(item.getInputStream());
                        Sheet sheet = wb.getSheetAt(0);
                        for (Iterator<Row> rit = sheet.rowIterator(); rit
                                .hasNext();) {
                            Row row = rit.next();
                            for (Iterator<Cell> cit = row.cellIterator(); cit
                                    .hasNext();) {
                                Cell cell = cit.next();
                            System.out.println("cell value :- "+cell.toString());//printing content inside each row
                                // do something here
                            }
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}






Step 5 :-Make changes in xml so that our required jsp will load first then Clean build the project and run it

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...