Pages

Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Wednesday, October 5, 2011

J2EE WebApp - For Beginners


This article is for beginners who want to try out their first J2EE application. It explains the step by step process to create a web application using JSF 2.0, Rich Faces 3.3 for UI and MYSQL5.5 for database and Jboss 5.0.1GA server for deployment.


    Set up MYSQL5.5

     
  • Download and install the MYSQL Installer pack (32bit or 64bit) from http://dev.mysql.com/downloads/installer/


  • Remember and save the root password for MYSQL that you create during the installation.


  • MYSQL Services will start listening to port 3306 after successful installation.


  • Start MYSQL Command Line Client from Start Menu  and enter the root password.


  • Create a database.  Give the command,  ‘create database company ;’ (without quotes) and hit enter. You will see the response ‘Query OK, 1 row affected’.


  • Create User Id/Password for that database. Give the command, ‘grant all privileges on company.* to johnsmith@localhost identified by 'password-1';’. Here the user name is ‘johnsmith’ and password is ‘password-1’. You will need this user id/password for accessing any table with the ‘company’ database.

  •        
  • Set the ‘company’ database as default. Give the command, ‘use company;’


  • Create a table. Give the command, ‘create table EMPLOYEE (employeeFirstName varchar(20), employeeLastName varchar(20), upddttm DATE);’


  • Insert a sample record into the table. Give the command, ‘insert into EMPLOYEE (employeeFirstName,employeeLastName,upddttm) values ('Alex','Roger',current_timestamp);’



    • Set up JBOSS 5.0.1GA


  • Download and install JBOSS 5.0.1GA from http://www.jboss.org/jbossas/downloads


  • To tell Jboss to connect to your MYSQL5.5 during server startup, drop a file named ‘mysql-ds.xml’ inside the ‘ /server/default/deploy’ folder.


  • The contents of the mysql-ds.xml should contain the connection url, user name, password for the database it wants to connect.



    1. <datasources>
          <local-tx-datasource>
           <jndi-name>MySqlDS</jndi-name>
           <connection-url>jdbc:mysql://localhost:3306/company</connection-url>
           <driver-class>com.mysql.jdbc.Driver</driver-class>
           <user-name>johnsmith</user-name>
           <password>password-1</password>
           <min-pool-size>2</min-pool-size>
           <max-pool-size>10</max-pool-size>
           </local-tx-datasource>
      </datasources>


  • Please note, you have to provide optimized values for the Database connection pooling as per your database usage. Too many or too less will result in performance degrade.



    • Set up Web Application:


  • I assume, you have Eclipse 3.5 or above and JDK 1.6 installed on your machine. I also assume, you have JSF 2.0 libraries (Say Mojara 2.0) on your machine.


  • On Eclipse, Create a new Dynamic Web project – SampleWeb, with target runtime as Jboss 5.0, Dynamic Web Module version 2.5, Added to SampleWebEAR and with Context root ‘SampleWeb’. Check the ‘Generate web.xml deployment descriptor’ option in the Wizard.


  • Right click on SampleWeb  Properties  Project Facets  Check Java Server Faces 2.0. If you see further configurations required at the bottom, click the link and browse your JSF Implementation Library.


  • Rich Faces library has certain dependencies with JSF library. This example uses Rich Faces 3.3 and JSF 2.0.


  • Before we start with our JSP file, ensure, you have the following jars in your ‘lib’ directory inside web-inf folder.


      commons-beanutils.jar
      commons-collections-3.2.1.jar
      commons-digester.jar
      commons-logging.jar
      jboss-faces.jar
      jsf-api.jar
      jsf-impl.jar
      richfaces-api-3.3.3.Final.jar
      richfaces-impl-3.3.3.Final.jar
      richfaces-ui-3.3.3.Final.jar



  • Your web.xml needs the below entry to support Rich Faces.



    1. <context-param>
      <param-name>org.richfaces.SKIN</param-name>
      <param-value>blueSky</param-value>
      </context-param>
      <context-param>
      <param-name>org.richfaces.CONTROL_SKINNING</param-name>
      <param-value>enable</param-value>
      </context-param>
      <filter>
      <display-name>RichFaces Filter</display-name>
      <filter-name>richfaces</filter-name>
      <filter-class>org.ajax4jsf.Filter</filter-class>
      </filter>
      <filter-mapping>
      <filter-name>richfaces</filter-name>
      <servlet-name>Faces Servlet</servlet-name>
      <dispatcher>REQUEST</dispatcher>
      <dispatcher>FORWARD</dispatcher>
      <dispatcher>INCLUDE</dispatcher>
      </filter-mapping>


  • Before we get to the Employee. jsp, let’s create a employee bean for the page.



    1. package com.example.richfaces;
      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.sql.Statement;
      import javax.naming.InitialContext;
      import javax.sql.DataSource;

      public class EmployeeBean {

      private String employeeFirstName;
      private String employeeLastName;

      public String getEmployeeFirstName() {
      return employeeFirstName;
      }

      public void setEmployeeFirstName(String employeeFirstName) {
      this.employeeFirstName = employeeFirstName;
      }

      public String getEmployeeLastName() {
      return employeeLastName;
      }

      public void setEmployeeLastName(String employeeLastName) {
      this.employeeLastName = employeeLastName;
      }

      public void doGetEmployeeName() {

      InitialContext ctx = null;
      DataSource ds = null;
      Connection conn = null;
      Statement stmt = null;
      try {
      ctx = new InitialContext();
      ds = (DataSource) ctx.lookup("java:/MySqlDS");
      conn = ds.getConnection();
      stmt = conn.createStatement();
      ResultSet rs = stmt
      .executeQuery("select employeeFirstName, employeeLastName from EMPLOYEE");
      while (rs.next()) {
      setEmployeeFirstName(rs.getString(1));
      setEmployeeLastName(rs.getString(2));
      }

      rs.close();
      stmt.close();
      conn.close();

      } catch (Exception ex) {
      // Implement finally block and better Exception handling here
      ex.printStackTrace();
      }

      }

      }


  • Add the Employee Bean entry to faces-config.xml. This way, we can refer the bean from our JSP page using ‘employee’ object



    1. <?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">
      <managed-bean>
      <description>Employee Bean</description>
      <managed-bean-name>employee</managed-bean-name>
      <managed-bean-class>com.example.richfaces.EmployeeBean</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
      <managed-property>
      <property-name>employeeFirstName</property-name>
      <property-class>java.lang.String</property-class>
      <value />
      </managed-property>
      <managed-property>
      <property-name>employeeLastName</property-name>
      <property-class>java.lang.String</property-class>
      <value />
      </managed-property>
      </managed-bean>
      </faces-config>


  • Create a new JSP File (Employee.jsp)



    1. <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
      <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
      <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
      <!-- RichFaces tag library declaration -->
      <%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
      <%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
      <html>
      <head>
      <title>RichFaces Example</title>
      </head>
      <body>
      <f:view>
      <a4j:form>
      <rich:panel header="RichFaces Greeter" style="width: 315px">

      <a4j:commandButton value="Get Our Employee" reRender="greeting"
      action="#{employee.doGetEmployeeName}" />

      <h:panelGroup id="greeting">
      <h:outputText value="Hello, "
      rendered="#{not empty employee.employeeFirstName}" />
      <h:outputText value="#{employee.employeeFirstName}" />
      <h:outputText value="#{employee.employeeLastName}"
      rendered="#{not empty employee.employeeFirstName}" />
      </h:panelGroup>
      </rich:panel>
      </a4j:form>
      </f:view>
      </body>
      </html>


  • You are all set!! Get going..














  • Tuesday, December 7, 2010

    Web Services - An Introduction

    Hello there,
    This article is for the beginners and people who are new to Web Services. I have compiled the things you need to know when you get started with Web Service. Screenshots are available in the attached document.

    Web Services Introduction:
    Web Services help in exposing the available services in your application to the Web thereby making your application a web application. With web services exchange of data between different applications on different platforms becomes simple. Web Services are application components that communicate using XML + HTTP. Web Services use XML to encode and decode data. It uses SOAP to transport the data.

    It is composed of three elements
    • SOAP – Simple Object Access Protocol (Platform independent, XML Based)
    • UDDI – Universal Description, Discovery and Integration
    • WSDL – Web Services Description Language

    SOAP – Platform independent, XML based protocol for accessing a web service.
    UDDI - A directory service where companies can register and search for Web services.
    WSDL - XML based language that describes Web Services message formats and protocols.

    Creating Web Services:
    Web Services can be created in two ways.
    • Top Down Approach (WSDL  Coding)
    • Bottom Up Approach (Coding  WSDL)

    Top down Approach:
    In this method, the WSDL is created first using the WSDL editor. The web service wizard on eclipse can be used to create skeleton Java Classes and the desired implementation can be done on or based out of those classes. Creating the WSDL first gives more control over the web service and hence this is the recommended way of implementing a web service.

    Bottom up Approach:
    In this method, the desired implementation is done through coding and the service class (Java Bean or EJB) is exposed as Web Service. Web Service wizard in eclipse can help in creating the WSDL file and web service configurations corresponding to the Service class that is exposed. This method is easier and faster and used by developers who are new to Web Service.


    IDE / JDK requirement:
    1. Get Eclipse 3.2 or above.
    2. Install JDK 1.4 or above.
    3. Install Tomcat 5.5 or above.
    The example project here uses Eclipse 36 (Helios, Java EE IDE for Web Developers), JDK 1.6 and Tomcat 6.0.1.2

    Getting Started with Web Service:
    Let’s build a web service that accepts a name and says Hello. i.e. If you pass “John”, the web service will return a string “Hello John” as response. The method exposed to web here is “sayHello”.
    Top Down Approach:

    Create a Workspace with a dynamic web project (2.5).
    Copy axis.jar, saaj.jar, jaxrpc.jar to the lib folder of WEB-INF.
    Create a folder named “wsdl” inside your WEB-INF. Copy/Paste your wsdl file to that.






















    Right Click on the WSDL file (Hello.wsdl), Select Web Services and Create Java Bean Skeleton.






















    Web Service Wizard will pop up. Carefully note down the text fields and values. Do not change anything here. Click Next.



































    Click Next



































    Now your Java Bean classes are created. Click on Start Server. This will add the Web Project (Hello_Web) to the Tomcat server and start the server. You can also see the Web Service Descriptor files created inside Web Project (deploy.wsdd and undeploy.wsdd).





















    Bottom Up Approach:

    Create a new dynamic web project (Hello_WebWS) .
    Copy axis.jar, saaj.jar, jaxrpc.jar to the lib folder inside WEB-INF.
    Create a Java Class (com.webservice.sample.Hello.java) with a public method with signature “public String sayHello (String name)”. Let the method return the string “Hello + name”.






















    Right Click on Hello.java Web Services Create Web Service






















    Web Service Wizard will show up with Web Service type as “Bottom Up” Approach. No changes here. Click Next.


































    All your public methods in Hello.java should come here. Select the methods you want to be exposed as Web Service. Click Next.


































    You do not want to publish your web service now. So, click finish button here.
    Your WSDL file, Web Service Descriptors (deploy.wsdd, undeploy.wsdd) are created on Web Project, and web project added to server and should be in STARTED status now.



    Testing Web Services:
    Testing the web service is easy and is same for both the development approaches. Right click on the WSDL, Select Test with Web Services Explorer.



































    Click on the sayHello method. It will show a text field to accept the input (name). Type in “John” and click on GO. You will see the response printed on the explorer.





















    Hope it helps... :)