Archive

Archive for the ‘J2EE’ Category

EJB3 Sample application in Weblogic 10.3

February 19, 2013 2 comments

In this post will see how to create and test a EJB3 SayHello application.
Here I have created a simple stateless session bean and packaged it as EAR using ANT script.

Jars required :
1. javaee-api-5.0-2.jar
2. wlfullclient.jar

EAR Structure :

ApplicationStructure

ApplicationStructure


 

SayHello Sample Structure

SayHelloEclipseStructure

SayHelloEclipseStructure


 

SayHello.java remote interface

package com.wordpress.rathinasaba.ejb3;

import javax.ejb.Remote;

@Remote
public interface SayHello {
	public String sayHello(String name);
}

 
SayHelloBean.java
This Stateless session bean implements Remote interface SayHello.java
name
mappedName
description
the above three attributes can be used in Stateless session bean.

Here the mappedName attribute is used from Client

package com.wordpress.rathinasaba.ejb3;

import javax.ejb.Stateless;

@Stateless(mappedName = "SayHello")
public class SayHelloBean implements SayHello {
	
	public String sayHello(String name) {
		return "Hello " + name + " welcome to EJB 3 In Action!";
	}
}

 

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"
	id="Application_ID" version="5">
	<display-name>SayHello EJB3 Sample</display-name>
	<module>
		<ejb>SayHello-ejb.jar</ejb>
	</module>
</application>

 

weblogic-application.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://www.bea.com/ns/weblogic/weblogic-application"
	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/javaee_5.xsd http://www.bea.com/ns/weblogic/weblogic-application http://www.bea.com/ns/weblogic/weblogic-application/1.0/weblogic-application.xsd">
	<wls:application-param>
		<wls:param-name>webapp.encoding.default</wls:param-name>
		<wls:param-value>UTF-8</wls:param-value>
	</wls:application-param>
</wls:weblogic-application>

 

build.properties

wls.home=C:\\Saba\\soa11g\\soa11.1.1.5\\Middleware

ANT Script – build.xml
The below ANT script file will compile the EJB3 Code and pack it as SayHello.ear file.

<?xml version="1.0" encoding="UTF-8"?>
<project name="SayHello-ejb" default="buildEar" basedir=".">
	<property file="build.properties" />
	<property name="ear.name" value="SayHello" />
	<property name="src.server" value="${basedir}/src/server" />
	<property name="src.common" value="${basedir}/src/common" />
	<property name="build" value="${basedir}/build" />
	<property name="dist" value="${basedir}/dist" />
	<property name="wl.home.lib" value="${wls.home}/wlserver_10.3/server/lib" />

	<echo message="${wl.home.lib}" />

	<path id="classpath">
		<fileset dir="${wl.home.lib}">
			<include name="*.jar" />
		</fileset>
	</path>

	<target name="clean">
		<delete dir="${build}" />
		<delete dir="${dist}" />
	</target>

	<target name="init" depends="clean">
		<mkdir dir="${build}" />
		<mkdir dir="${dist}/META-INF" />
		<mkdir dir="${dist}/APP-INF/lib" />
		<mkdir dir="${dist}/APP-INF/classes" />
		<mkdir dir="${dist}" />
		
	</target>

	<taskdef name="wlappc" classpathref="classpath" classname="weblogic.ant.taskdefs.j2ee.Appc" />

	<target name="compile" depends="init">
		<echo> "Compiling Java" </echo>
		<javac srcdir="${src.server}" destdir="${build}" debug="on">
			<classpath refid="classpath" />
		</javac>
	</target>

	<target name="ejb3Compile" depends="compile">
		<echo> "Compiling EJB" </echo>
		<wlappc source="${build}" output="${build}" keepgenerated="true" verbose="true"/>
	</target>
	
	<target name="buildEar" depends="ejb3Compile">
		<echo> "Building EJB JAR" </echo>
		<copydir dest="${dist}/META-INF/" src="${src.common}/META-INF/"/>
		<jar jarfile="${dist}/${ant.project.name}.jar" basedir="${build}" />
		<jar jarfile="${dist}/${ear.name}.ear" basedir="${dist}" />
	</target>
	
</project>

 
Deployment and Client Testing
1. Deploy the SayHello.ear in weblogic server by targetting managed server.
2. Use the below Client Code to Test the EJB3 Sample from main method.

SayHelloClient.java

package com.wordpress.rathinasaba.ejb3.client;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.wordpress.rathinasaba.ejb3.SayHello;

public class SayHelloClient {

	private static SayHello client;

	public static void main(String[] args) {
		println(invokeEJB3());
	}

	public static String invokeEJB3() {
		println("===============================================");
		println("                Invoking EJB                   ");
		println("===============================================");
		String response = null;
		try {
			Context ctx = new InitialContext(getInitialContext());
			client = (SayHello) ctx.lookup("SayHello#com.wordpress.rathinasaba.ejb3.SayHello");
			response = client.sayHello("Rathina Sabapathy");
			println("--- Invoked EJB successfully ---");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return response;
	}

	private static void println(Object content) {
		System.out.println(content);
	}

	private static Hashtable<String, Object> getInitialContext() {
		Hashtable<String, Object> props = new Hashtable<String, Object>();
		props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
		props.put(Context.PROVIDER_URL, "t3://localhost:8011");
		return props;
	}

}
Advertisements
Categories: EJB3 Tags:

Difference between ServletConfig and ServletContext

November 2, 2011 1 comment
S.No ServletConfig ServletContext
1. A ServletConfig object passes configuration information from the server to a servlet. ServletConfig also includes ServletContext object A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
2. There is one ServletConfig parameter per servlet. There is only one SevletContext for the entire web application.
3. The param-value pairs for ServletConfig object are specified in the “init-param” within the “servlet” tags in the web.xml file The param-value pairs for ServletContext object are specified in the “context-param” tags in the web.xml file.
4. Init parameters for ServletConfig are defined within “servlet” element for each specific servlet

<servlet>
			<servlet-name>SampleServlet</servlet-name>
			<servlet-class>com.sample.test.SampleServlet</servlet-class>
				<init-param>
					<param-name>foo</param-name>
					<param-value>bar</param-value>
				</init-param>
		</servlet>
		
Init parameters for ServletContext are defined within the “web-app” element but NOT within a specific “servlet” element.

<web-app>
			<context-param>
				<param-name>foo</param-name>
				<param-value>bar</param-value>
			</context-param>
			<!-- Other stuff -->
		</web-app>
		
5. Servlet Code:

getServletConfig().getInitParameter("foo");
Servlet Code:

getServletContext().getInitParameter("foo");

Difference between GET and POST method in HTTP

October 19, 2011 Leave a comment
S.No GET POST
1. The data passed using the GET method would be visible to the user of the website in the browser address bar The data passed using POST method is not visible to the user directly
2. GET method form-data parameters are appended to the URL in name/value pairs and sent along with header information POST method sends form-data as an HTTP post transaction.
3. Parameters are not encrypted Parameters are encrypted
4. GET method has maximum length restricted to 256 characters POST method has no size limitations
5. GET method is designed for reading the information from server( a document, a chart, or a database query ) POST method is designed for posting information to the server
6. GET method is faster than POST method.Because it is requesting information from server POST method is slow compared to GET. Because it is updating information to the server
7. GET method is not secure POST method is secure
8. It allows bookmarks It disallows bookmarks

Difference between Statement and PreparedStatement in JDBC with examples

October 13, 2011 Leave a comment

The Prepared Statement is a slightly more powerful version of a Statement and it will take less time to execute when compared with Statement.
Because

* In Statement the SQL query will be compiled and executed every time.

* In PreparedStatement at the First time RDBMS comiple the SQL and PreparedStatement is executed then from the next time it doesn’t compile the SQL only execute the SQL within the connection live.

Here I have given the example using the statement and preparedstatement to insert customer details into database.

  
1. Queries used to create the customer table.

CREATE TABLE SAM_CUSTOMER(CUST_ID NUMBER PRIMARY KEY,
                          CUST_NAME VARCHAR2(25) NOT NULL,
                          CUST_ADDRESS VARCHAR2(45),
                          CUST_MOBILE NUMBER(10),
                          CUST_MAILID VARCHAR2(30)
                          );

-- The unique sequence id will be inserted while inserting record into table. For that we have created sequence.

CREATE SEQUENCE CUST_ID_SEQ START WITH 100 INCREMENT BY 1 NOCACHE NOCYCLE;

 
 
2. Insert Customer using JDBC Statement.

package com.room.sample.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class StatementTest {


	public void insertCustomer(Customer customer){
		Connection connection=null;
		Statement stmt=null;
		try {
			connection=getConnection();
			final String query="INSERT INTO SAM_CUSTOMER VALUES(CUST_ID_SEQ.nextval,"+"'"+customer.getName()+"','"+customer.getAddress()+"',"+customer.getMobile()+",'"+customer.getEmailid()+"')";
			
			long startTime=System.currentTimeMillis();
			stmt=connection.createStatement();
			int status=stmt.executeUpdate(query);
			System.out.println("Statement Execution Response :"+status);
			
			long timtaken=System.currentTimeMillis() - startTime;
			System.out.println("Time Taken for executing Statement :"+timtaken+" milli seconds");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Connection getConnection() throws Exception{
		Connection conn=null;
		 try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			 conn=DriverManager.getConnection("jdbc:oracle:thin:@SABA:1521:XE", "system", "password");
			 System.out.println("--- java.sql.Connection created ----");
		} catch (ClassNotFoundException e){
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return conn;
	}
	
	public static void main(String[] args) {
		Customer cust=new Customer();
		cust.setName("Sabapathy");
		cust.setAddress("NorthWales-AU");
		cust.setMobile(Long.valueOf("1234567891"));
		cust.setEmailid("test@hotmail.com");
		
		StatementTest test=new StatementTest();
		//executing Statement method
		test.insertCustomer(cust);
	}
}

 
 
3. Insert customer using JDBC PreparedStatement.

package com.room.sample.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class PreparedStatementTest {

	public void insertCustomer(Customer customer){
		Connection connection=null;
		PreparedStatement prepareStmt=null;
		try {
			connection=getConnection();
			final String query="INSERT INTO SAM_CUSTOMER(CUST_ID,CUST_NAME,CUST_ADDRESS,CUST_MOBILE,CUST_MAILID) VALUES (CUST_ID_SEQ.nextval,?,?,?,?)";
			long startTime=System.currentTimeMillis();
			
			prepareStmt=connection.prepareStatement(query);
			prepareStmt.setString(1, customer.getName());
			prepareStmt.setString(2, customer.getAddress());
			prepareStmt.setLong(3, customer.getMobile());
			prepareStmt.setString(4, customer.getEmailid());
			
			int status=prepareStmt.executeUpdate();
			System.out.println("PreparedStatement Execution Response :"+status);
			long timtaken=System.currentTimeMillis() - startTime;
			
			System.out.println("Time Taken for executing PreparedStatement :"+timtaken +" milli seconds");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Connection getConnection() throws Exception{
		Connection conn=null;
		 try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			 conn=DriverManager.getConnection("jdbc:oracle:thin:@SABA:1521:XE", "system", "password");
			 System.out.println("--- java.sql.Connection created ----");
		} catch (ClassNotFoundException e){
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return conn;
	}
	
	
	public static void main(String[] args) {
		Customer cust=new Customer();
		cust.setName("Rathina");
		cust.setAddress("New Delhi");
		cust.setMobile(Long.valueOf("2233445566"));
		cust.setEmailid("test@rediffmail.com");
		
		PreparedStatementTest test=new PreparedStatementTest();
		//Executing Prepared Statement method
		test.insertCustomer(cust);

	}
}

Simple Webapplication using Servlet and JSP

October 13, 2011 4 comments

Here in this post we will see simple web application using Servlet and JSP where we are going to give customer details in JSP page then get the customer details in servlet and show the customer details inserted in Welcome page.

Environment used:
1. Eclipse 3.3
2. JDK6
3. Tomcat Servler 6.x

1. Create “Dynamic Web Project” with Dynamic web module version – 2.5 Then Click Finish.

Web application structure in eclipse will look like this.

 

WebAppStructure

WebAppStructure

2. Create a Customer.jsp page inside WebContent folder of web application structure.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Details</title>
</head>
<body>
<form action="insertCustomer" method="post">
<table align="center" bgcolor="#99FFCC" border="1" width="70%">
	<tr>
		<td colspan="2" align="center">Customer Details </td>
	</tr>
	<tr>
		<td>Name </td>
		<td><input type="text" name="name" maxlength="25"></td>
	</tr>
	<tr>
		<td>Address </td>
		<td><input type="text" name="address" maxlength="40"></td>
	</tr>
	<tr>
		<td>Mobile </td>
		<td><input type="text" name="mobile" maxlength="10"></td>
	</tr>
	<tr>
		<td>EmailId </td>
		<td><input type="text" name="emailid" maxlength="30"></td>
	</tr>	
	<tr>
		<td colspan="2" align="center"><input type="submit" value="Submit"></td>
	</tr>	
</table>
</form>
</body>
</html>

This customer page will look like the below.

 

CustomerPage

CustomerPage

 

3. Create a InsertCustomerServlet.java servlet class. While submitting the form from the “Customer.jsp” page the servlet will get the form value in HttpServletRequest object .
 

package com.room.sample.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.room.sample.view.Customer;

public class InsertCustomerServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response){
		System.out.println("----- InsertCustomerServlet -----");
		try {
		// Get the customer value submitted from Customer.jsp page through HttpServletRequest object
			String name=request.getParameter("name");
			String address=request.getParameter("address");
			String mobile=request.getParameter("mobile");
			String emailid=request.getParameter("emailid");
			
			//Set the Customer values into Customer Bean or POJO(Plain Old Java Object) class
			Customer customer=new Customer();
			customer.setName(name);
			customer.setAddress(address);
			customer.setMobile(Long.valueOf(mobile));
			customer.setEmailid(emailid);
			
			RequestDispatcher dispatcher=request.getRequestDispatcher("/Welcome.jsp");
			//Set the customer instance into request.Then only the customer object 
			//will be available in the Welcome.jsp page
			request.setAttribute("cust",customer);
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

}

4. Bean Class to store information received in Servlet class.

package com.room.sample.view;

import java.io.Serializable;

public class Customer implements Serializable{

	private static final long serialVersionUID = 1L;
	private String name;
	private String address;
	private Long mobile;
	private String emailid;
	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;
	}
	public Long getMobile() {
		return mobile;
	}
	public void setMobile(Long mobile) {
		this.mobile = mobile;
	}
	public String getEmailid() {
		return emailid;
	}
	public void setEmailid(String emailid) {
		this.emailid = emailid;
	}
	
}

5. Create Welcome.jsp page to display the customer details processed.

<%@page import="com.room.sample.view.Customer"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Customer Details</title>
</head>
<body>
<%
	Customer customer=(Customer)request.getAttribute("cust");
%>
<table align="center" bgcolor="#FFFFCC" border="1" width="70%">
	<tr>
		<td colspan="2" align="center"><%="Welcome "+customer.getName()+" !!!!. Your details Processed." %></td>
	</tr>
	<tr>
		<td>Name </td>
		<td><%=customer.getName()%></td>
	</tr>
	<tr>
		<td>Address </td>
		<td><%=customer.getAddress() %></td>
	</tr>
	<tr>
		<td>Mobile </td>
		<td><%=String.valueOf(customer.getMobile()) %></td>
	</tr>
	<tr>
		<td>EmailId </td>
		<td><%=customer.getEmailid() %></td>
	</tr>	
</table>
</body>
</html>

6. Connect the flow using web.xml. For a servlet defined , the element value under element and element value under should be same.
Then only the requested action “insertCustomer” can find the corresponsing servlet to be executed from web.xml file.

<?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>Simple Customer Application</display-name>
  <welcome-file-list>
    <welcome-file>Customer.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>customer</servlet-name>
  	<servlet-class>com.room.sample.servlet.InsertCustomerServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>customer</servlet-name>
  	<url-pattern>/insertCustomer</url-pattern>
  </servlet-mapping>
</web-app>

Welcome.jsp page will look like the below.

 

Welcome

Welcome