Saturday, 1 March 2014

JSP + Apache Tiles Example

Hello all,
This sample application will show you how to use apache tiles using JSP in your maven web application project. so lets get started.
Follow these steps to make your project:

Application Type: Maven Web Application
Apache Tiles: 2.2.2 version
Web Server: Tomcat 7.0.50

Download Source Code: Click here

web.xml Configuration Code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
    version="2.5">

    <context-param>
<param-name>
            org.apache.tiles.definition.DefinitionsFactory.DEFINITIONS_CONFIG
        </param-name>
<param-value>
            /WEB-INF/myTilesConfigFile.xml
        </param-value>
    </context-param>
    <listener>
    <listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>jsp/home.jsp</welcome-file>
    </welcome-file-list>

</web-app>

myTilesConfigFile.xml Configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="homePage" template="/jsp/template.jsp">
        <put-attribute name="header" value="/jsp/defaultHeader.jsp" />
        <put-attribute name="menu" value="/jsp/defaultMenu.jsp" />
        <put-attribute name="body" value="/jsp/home_body.jsp" />
        <put-attribute name="footer" value="/jsp/defaultFooter.jsp" />
    </definition>

</tiles-definitions>



Template.jsp

<%-- 
    Document   : defaultFooter
    Created on : Mar 1, 2014, 1:38:55 PM
    Author     : Umair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<html>
    <body style="width:100%;height:100%">
        <table border="1" cellspacing="0" cellpadding="0" style="width:100%;height:100%">
            <tr>
                <td colspan="2">
                    <tiles:insertAttribute name="header" /></td>
            </tr>
            <tr>
                <td>
                    <tiles:insertAttribute name="menu" /></td>
                <td>
                    <tiles:insertAttribute name="body" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <tiles:insertAttribute name="footer" /></td>
            </tr>
        </table>
    </body>

</html>

Thursday, 16 January 2014

Set/Get Variables in URL JSF Example

Hello guys today i shall be covering that how to set and retrieve parameter in jsf application. first of all i must tell you about application tools:

Maven Project
JSF
Primefaces
Apache Tomcat

You can also configure this project in your IDE by download it. Click Here to Download
Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.5">
<display-name>JSFApp</display-name>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<!-- Just here so the JSF implementation can initialize, *not* used at runtime -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Just here so the JSF implementation can initialize -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

</web-app>

-------------------------------------------------

POM.xml

Dependencies:
<dependencies>
<dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.0.2-b10</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>

  </dependencies>

--------------------------------------------------

Index.xhtml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</h:head>
<h:body>
<p:button outcome="target" value="Navigate">
<f:param name="id" value="20" />
</p:button>
</h:body>

</html>

---------------------------------------------------

Target.xhtml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</h:head>
<h:body>
<h:outputText value="#{param['id']}" />
</h:body>

</html>

Monday, 17 June 2013

Hibenate 4.2 Insert, Fetch Data Example

Insert Data

In the previous example i taught you how to use hibernate in your application with configuration and JPA annotations. today i shall be talking about how to insert and fetch data from table which is persisted in database.
this is linked to the previous tutorial : Hibernate Tutorial

Test is entity class and it is persisted in the database. to insert data inside table of database. you just need to create an object of entity class which Test and add data by using its setter methods. like this:

Test test = new Test();
test.setPassword("password");
test.setUsername("username");

after doing this. you need to create a hibernate session object like this. 

Session session = configuration.buildSessionFactory().openSession();

session.beginTransaction(); 
//it means that you are going to make a transaction with //database.

session.saveOrUpdate(test); 
// saveOrUpdate method works like if there is no record exist in //the table then the above data will be inserted if it exists //then the following record will be updated.

session.getTransaction().commit();
session.close();

Fetch Data from Database

After creating session object from the configuration file. you only need to add following line of code:
List<Test> list = session.createQuery("from Test").list();
// Test is the entity class. and this HQL query. you can also add 
// SQL into it like select * from Test

// Showing Outut of the data

for(int i=0;i<list.size();i++){
System.out.println(list.get(i).username);

}

Hibernate 4.2 with JPA Annotations example using PostgreSQL Database


Required Libraries for Hibernate 4.2
  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.2.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.1.Final.jar
  • postgresql-9.2-1002.jdbc3.jar *
 * Database driver file.
just keep these annotations in your mind while using Hibernate in your application.
JPA Annotations
  • Entity
  • Id
  • GeneratedValue
if you want that you java class may persist in the database with the same name you need to add @Entity annotation at the class level. 

@Entity
public class Test{}

now it will persist into the database with a table name "test". if you want to change the name of the table then you need to add name attribute of Entity. like this @Entity(name = "TableName"). Entity class must implement serializable interface. Serializable interface acts as a mask for the object and objects retain their identity acorss the network. 
Adding Columns into Table
adding columns is nothing difficult it is same you are defining data members in class. like this.

@Entity
public class Test implements Serializable{
int id;
String username;
String password;

        @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}

@Id annotation is to define a primary key of table and i have made it auto generated. now define an xml file to define this entity class and make common configuration like database name, username, password, host name

hibernate.cfg.xml file code:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.password">umairbaig</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/imageDB</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
  <mapping class="Test"/>
    </session-factory>
</hibernate-configuration>

When you are done configuration inside main method add these lines:


public static void main(String[] args) {
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration.configure();
// if your xml file name is hibernate.cfg.xml then you dont need //to pass argument inside configure();
new SchemaExport(configuration).create(true, true);
}

Database table is created with the following columns;
Table Name test
Columns:
  • id (Primary Key)
  • username
  • password

Sunday, 9 June 2013

Image Uploading and Rendering from Database in JSF(Primefaces)

Add.xhtml  

    <h:form id="add-form" enctype="multipart/form-data">
             <p:growl id="messages" showDetail="true"/>
             <h:panelGrid columns="2">
                  <p:outputLabel for="choose" value="Choose Image :" />
                  <p:fileUpload id="choose" validator="#{productController.validateFile}" multiple="false" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"  value="#{productController.file}" required="true" mode="simple"/>
                <p:commandButton value="Submit" ajax="false" update="messages" id="save-btn" actionListener="#{productController.saveProduct}"/>
             </h:panelGrid>
    </h:form>

 
Here is Managed Bean Code:

    @ManagedBean
  @RequestScoped
    public class ProductController implements Serializable{
    private ProductBean bean;
    @ManagedProperty(value = "#{ProductService}")
    private ProductService productService;
    private StreamedContent content;
    private UploadedFile file;
    public StreamedContent getContent() {
    FacesContext context = FacesContext.getCurrentInstance();
   
    if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
               return new DefaultStreamedContent();
           }
    else{
    String imageId = context.getExternalContext().getRequestParameterMap().get("id");
    Product product = getProductService().getProductById(Integer.parseInt(imageId));
    return new DefaultStreamedContent(new ByteArrayInputStream(product.getProductImage()));
    }
    }
    public ProductController() {
    bean = new ProductBean();
    }
   
    public void setContent(StreamedContent content) {
    this.content = content;
    }
    public UploadedFile getFile() {
    return file;
    }
    
    public void setFile(UploadedFile file) {
    this.file = file;
    }
    public void saveProduct(){
    try{
    Product product = new Product();
    product.setProductImage(getFile().getContents());
   
    getProductService().saveProduct(product);
    file = null;
   
    }
    catch(Exception ex){
    ex.printStackTrace();
    }
    }
    public void validateFile(FacesContext ctx,
                UIComponent comp,
                Object value) {
    List<FacesMessage> msgs = new ArrayList<FacesMessage>();
    UploadedFile file = (UploadedFile)value;
    int fileByte = file.getContents().length;
    if(fileByte > 15360){
    msgs.add(new FacesMessage("Too big must be at most 15KB"));
    }
    if (!(file.getContentType().startsWith("image"))) {
       msgs.add(new FacesMessage("not an Image file"));
    }
    if (!msgs.isEmpty()) {
       throw new ValidatorException(msgs);
    }
    }
    }

Add these lines of code in web.xml


    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

And Dont Forget to add following jar files in lib folder.
commons-io-X.X  and commons-fileupload-X.X, recommended most recent version.



View.xhtml

    <h:form id="ShowProducts">
    <p:dataTable rowsPerPageTemplate="3,6,9" var="products" paginator="true" rows="3" emptyMessage="Catalog is empty" value="#{productController.bean.products}">
    <p:column headerText="Product Name">
    <p:graphicImage width="80" height="80" value="#{productController.content}">
    <f:param name="id" value="#{products.productId}" />
      </p:graphicImage>
    #{products.productName}
    </p:column>
    </p:dataTable>
    </h:form>

Wednesday, 17 April 2013

JSF Getting Started Eclipse IDE

JSF(Java Server Faces) getting started with Eclipse IDE.
in order make make your first application in JSF. follow these steps:

required library :
javax.faces.jar file which is 2MB approximately.

Click on new project:
choose Dynamic Web Project:
like this:


I'm using Apache Tomcat 7.0 web server thats why i have chosen Apache Tomcat in the target Runtime. 












remove template="" from <ui:composition> tag. like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">

<ui:composition>
<ui:define name="header">
   Add your header here or delete to use the default
</ui:define>
<ui:define name="content">
   Add your content here or delete to use the default
</ui:define>
<ui:define name="footer">
   Add your footer here or delete to use the default
</ui:define>
</ui:composition>
</html>


Now Right click on your project and choose run on server. and delopy your project on server and see the output. please post your comments and inform me about your problems thanks alot :)