Java J2ee Tutorials

javascript code to alert before delete a record

Monday, December 10, 2012

Write the javascript file js/delete.js containing the utility methods

view source
rint?
01function go(url)
02{
03 window.location = url;
04}
05 
06function delete(url)
07{
08 var isOK = confirm("Are you sure to delete?");
09 if(isOK)
10 {
11  go(url);
12 }
13}

Free Career Predictions

How to Upload and Take Backup of Large MySql Database File into Local Database Using Command Prompt

Monday, October 15, 2012

How to upload and take backup of large MySql database file into local database using command prompt
  1. Craete data base in your local database
  2. Copy the path where MySql bin folder is available in command prompt for example C:\wamp\bin\mysql\mysql5.5.24\bin
  3. Write command to store database : mysql -u root -p db_name.sql< C:\Users\Desktop\db_folder_name\db_name.sql
Where C:\Users\Desktop\db_folder_name\db_name.sql is the path where dump database is available and db_name.sql is the database name

Note:
u = username
p = password (write password after p without space)

How to take database backup
  1. Write command to command prompt : mysqldump -u root -p db_name > d:\class_db.sql
Where d:\class_db.sql is the path where you want to save backup file and class_bd is the name you want to save file as.

Free Career Predictions

How to upload and take backup of large MySql database file into local database using command prompt

Friday, September 14, 2012

How to upload and take backup of large MySql database file into local database using command prompt

  1. Create data base in your local database
  2. Copy the path where MySql bin folder is available in command prompt for example D:\wamp\bin\mysql\mysql5.5.24\bin
  3. Write command to store database : mysql -u root -p db_name < D:\db_name.sql
    where D:\db_name.sql is the path where dump database is available and db_name.sql is the database name

Note: 
u = username
p = password (write password after p without space)

How to take database backup
  • Write command to command prompt : mysqldump -u root -p db_name > D:\class_db.sql
    where D:\class_db.sql is the path where you want to save backup file and class_bd is the name you want to save file as.

Free Career Predictions

Writing the first Struts Application

Friday, August 31, 2012

Let's start with developing your first Struts application. Here are the steps involved in creating the Struts application.

Add relevant entries into the web.xml

a. Add ActionServlet Configuration with initialization parameters
b. Add ActionServlet Mapping
c. Add relevant taglib declaration
Start with a blank template for the struts-config.xml. In the struts-config.xml, add the following

a. Declare the RequestProcessor
b. Create a properties file and declare it as Message Resource Bundle
c. Declare the Message Resource Bundle
d. Declare the Form-bean
e. Declare the ActionMapping for the Form-bean
f. Add the forwards in the ActionMapping
Create the Form-bean class
Create the JSP with Struts tags
Create the Action class
For every <bean:message> tag in the JSP, add key value pairs to the Message Resource Bundle (properties file) created in Step 2b
Add Validation in the Form-bean
Define the error messages in the Message Resource Bundle
Create the rest of the JSPs.
Next, you will find the steps to build the Struts application. You will find more explanation & rationale for the steps in the book Struts Survival Guide.

1. Add relevant entries into the web.xml

web.xml for the Struts Application

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts Application</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
</web-app>

2) Create the struts-config.xml

struts-config.xml for the Struts Application

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="CustomerForm" type="struts.example.CustomerForm"/>
</form-beans>
<global-forwards>
<forward name="mainpage" path="index.jsp" />
</global-forwards>
<action-mappings>
<action path="/submitCustomerForm"
type="struts.example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="CustomerForm.jsp">
<forward name="success" path="Success.jsp" />
</action>
</action-mappings>
<controller processorClass="org.apache.struts.action.RequestProcessor"/>
<message-resources parameter="struts.example.MessageResources"/>
</struts-config>

3) Create the ActionForm

CustomerForm

public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() {
firstName = “”;
lastName = “”;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String s) {
this.firstName = s;
}
public String getLastName() {
return lastName;
}
public void setLastName(String s) {
this.lastName = s;
}
}

4) Create the CustomerForm JSP using Struts Tags

CustomerForm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message key="exercise01.formpage.title"/></title>
<html:base/>
</head>
<body background="images/blueAndWhiteBackground.gif">
<h2><bean:message key="exercise01.formpage.title"/></h2>
<html:errors/>
<html:form action="/submitCustomerForm">
<bean:message key="prompt.customer.firstname"/>:
<html:text property="firstName" size="16" maxlength="16"/>
<BR>
<bean:message key="prompt.customer.lastname"/>:
<html:text property="lastName" size="16" maxlength="16"/>
<BR>
<html:submit property="step">
<bean:message key="button.save"/>
</html:submit>
 
<html:cancel>
<bean:message key="button.cancel"/>
</html:cancel>
</html:form>
</body>
</html:html>

5) Create the Action class

CustomerAction class

public class CustomerAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
ActionForward nextPage = null;
if (isCancelled(request)) {
System.out.println("Cancel Operation Performed");
return mapping.findForward("mainpage");
}
CustomerForm custForm = (CustomerForm) form;
if ("Save".equals(custForm.getStep()))
{
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
System.out.println("Customer First name is " + firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
}
return nextPage;
}
}

6) Add properties to MessageResources.properties

Message Resource Bundle

########################################
# Exercise01 index page strings
########################################
exercise01.indexpage.title=Welcome to Exercise01

########################################
# Exercise01 CustomerForm strings
########################################
exercise01.formpage.title=Please enter your details
prompt.customer.firstname=First Name
prompt.customer.lastname=Last Name
button.save=Save
button.cancel=Cancel

7) Add validation to the Form bean

validate() method for CustomerForm

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
// Firstname cannot be empty
if (firstName == null || firstName.trim().equals("")) {
errors.add("firstName", new ActionError("error.cust.firstname.empty"));
}
// Lastname cannot be empty
if (lastName == null || lastName.trim().equals("")) {
errors.add("lastName", new ActionError("error.cust.lastname.empty"));
}
return errors;
}

8) Add ActionError keys to the Message Resources

ActionError keys to Message Resources

########################################
# Common
########################################
errors.header=<h3><font color="red">Validation Error</font></h3>You must
correct the following error(s) before proceeding:<ul>
errors.footer=</ul><hr>
errors.prefix=<li>
errors.suffix=</li>

########################################
# Exercise01 CustomerForm ActionErrors
########################################
error.cust.firstname.empty=First Name is Required
error.cust.lastname.empty=Last Name is Required

9) Create the rest of the JSPs - index.jsp and Success.jsp. Notice that index.jsp uses the regular html:link tag that just forwards to another JSP. The Success.jsp uses the MVC compliant action mapping as the link. Define entries in MessageResource.properties for each of the bean:message keys in the JSPs.

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message key="exercise01.indexpage.title"/></title>
<html:base/>
</head>
<body background="images/blueAndWhiteBackground.gif">
<div align="center">
<html:link page="/CustomerForm.jsp">Go to Customer Form</html:link>
</div>
</body>
</html:html>

Notice the usage of bean:write tags in Success.jsp. They let you access certain beans in appropriate scope and write their properties to the Servlet/JSP OutputStream

Success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true">
<head>
<title><bean:message key="exercise01.successpage.title"/></title>
<html:base/>
</head>
<body background="images/blueAndWhiteBackground.gif">
<h2><bean:message key="exercise01.successpage.title" />
<bean:write name="CustomerForm" property="firstName" />
<bean:write name="CustomerForm" property="lastName" />
</h2>
<h3><bean:message key="exercise01.successpage.message" /></h3>
<html:img src="images/beerchug.gif"/>
<html:link page="/showCustomerForm.do">Go Back</html:link>
</body>
</html:html>

Free Career Predictions

What Is the Struts Framework?

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

  • Open source
  • Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:

    • Model: application state
    • View: presentation of data (JSP, HTML)
    • Controller: routing of the application flow
  • Implements the JSP Model 2 Architecture
  • Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.

The diagram below describes the flow in more detail:

  1. User clicks on a link in an HTML page.
  2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.
  3. Action makes a call to a Model layer service.
  4. Service makes a call to the Data layer (database) and the requested data is returned.
  5. Service returns to the action.
  6. Action forwards to a View resource (JSP page)
  7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
  8. JSP file is invoked and sent to the browser as HTML.
  9. User is presented with a new HTML page in a web browser.

Free Career Predictions

Differences Between Struts1 and Struts2

The table given below describes some differences between struts1 and struts2

Feature
Struts 1
Struts 2
Action classes
Struts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces. While in Struts 2, an Action class implements an Action interface, along with other interfaces use optional and custom services. Struts 2 provides a base ActionSupport class that implements commonly used interfaces. Although an Action interface is not necessary, any POJO object along with an execute signature can be used as an Struts 2 Action object.
Threading Model
Struts 1 Actions are singletons therefore they must be thread-safe because only one instance of a class handles all the requests for that Action. The singleton strategy restricts to Struts 1 Actions and requires extra care to make the action resources thread safe or synchronized while developing an application. Struts 2 doesn't have thread-safety issues as Action objects are instantiated for each request. A servlet container generates many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.
Servlet Dependency
Actions are dependent on the servlet API because HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked therefore Struts1. Container does not treat the Struts 2 Actions as a couple. Servlet contexts are typically represented as simple Maps that allow Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. While other architectural elements directly reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse.
Testability


Struts1 application has a major problem while testing the application because the execute method exposes the Servlet API. Struts TestCase provides a set of mock object for Struts 1.
To test the Struts 2 Actions instantiate the Action, set the properties, and invoking methods. Dependency Injection also makes testing easier.
Harvesting Input
Struts 1 recieves an input by creating an ActionForm object. Like the action classes, all ActionForms class must extend a ActionForm base class. Other JavaBeans classes cannot be used as ActionForms, while developers create redundant classes to receive the input. DynaBeans is the best alternative to create the conventional ActionForm classes. Struts 2 requires Action properties as input properties that eliminates the need of a second input object. These Input properties may be rich object types, since they may have their own properties. Developer can access the Action properties from the web page using the taglibs. Struts 2 also supports the ActionForm pattern, POJO form objects and POJO Actions as well.
Expression Language
Struts1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into views
Struts 1 binds objects into the page context by using the standard JSP mechanism. Struts 2 uses a ValueStack technology to make the values accessible to the taglibs without coupling the view to the object to which it is rendering. The ValueStack strategy enables us to reuse views across a range of types, having same property name but different property types.
Type Conversion
Struts 1 ActionForm properties are almost in the form of Strings. Commons-Beanutils are used by used by Struts 1 for type conversion. Converters are per-class, which are not configurable per instance. Struts 2 uses OGNL for type conversion and converters to convert Basic and common object types and primitives as well.
Validation
Struts 1 uses manual validation that is done via a validate method on the ActionForm, or by using an extension to the Commons Validator. Classes can have different validation contexts for the same class, while chaining to validations on sub-objects is not allowed. Struts 2 allows manual validation that is done by using the validate method and the XWork Validation framework. The Xwork Validation Framework allows chaining of validations into sub-properties using the validations defined for the properties class type and the validation context.
Control of Action Execution
Each module in Struts 1 has a separate Request Processors (lifecycles), while all the Actions in the module must share the same lifecycle. In Struts 2 different lifecycles are created on a per Action basis via Interceptor Stacks. Custom stacks are created and used with different Actions, as required.s

Free Career Predictions

Download and Install Hibernate

Saturday, August 18, 2012

Let us see what are the jar files we need to download to work with hibernate framework, and how to install.

Working with the framework software is nothing but, adding the .jar(s) files provided by that framework to our java application. Each framework software is not an installable software, it means we do not contain any setup.exe
When we download any framework software, we will get a ‘zip‘ file and we need to unzip it, to get the jar files required, actually all framework softwares will follow same common principles like:


  • Framework software will be in the form of a set of jar files, where one jar file acts as main (We can call this file as core) and remaining will acts as dependent jar files.
  • Each Framework software contain at least one configuration xml file, but multiple configuration files also allowed.
  • In this case, in order to setup the Hibernate framework environment into a java application, the configuration file is the first one to be loaded into a java application, will see about this in later sessions.


Download Hibernate .jar(s) files:
we can download jars related to hibernate at http://sourceforge.net/projects/hibernate/files/hibernate3

  • From the above URL choose hibernate 3.2.2-ga.zip, as we are in initial stage this version will be better.
  • Unzip it, and now you can find some jar files in the lib folder right.?, actually we doesn’t require all the jar files, out of them just select the following jar files :

Anttr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
ehcash.jar
dom4j-1.6.1.jar
hibernate3.jar
jta.jar
log4j-1.2.3.jar

  • These are the main jar files to run hibernate related programming and among all the jars hibernate3.jar is the main file, but for annotation we need to add 4 – 6 other jar files, i will let you when time comes.
  • Remember: along with the hibernate jars we must include one more jar file, which is nothing but related to our database, this is depending on your database.
  • So finally we need total of 12 jar files to run the hibernate related program.

Free Career Predictions

EClipse Directory Structure


  • WebContent: Regular Web files (HTML, JavaScript, CSS, JSP, images, etc.)
  • WebContent/some-subdirectory: Web files in subdirectory.
  • WebContent/WEB-INF: web.xml (used for servlet mappings)
  • WebContent/WEB-INF/lib: JAR files specific to application.
  • src/(default package): Unpackaged (default package) Java code. Using the default package is generally a bad choice in Web apps.
  • src/somePackage: Java code in somePackage package.
  • Note: You can cut/paste or drag/drop existing files into appropriate locations, but it is hard to drag files into a Java package until you create at least one class first.

Free Career Predictions

Java Questions

Sunday, April 22, 2012


1. What is the difference between ServletContext and ServletConfig?
Both are interfaces. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
The ServletContext interface provides information to servlets regarding the environment in which they are

Free Career Predictions

Hibernate's Main Feature

Monday, April 16, 2012

The most important Hibernate's feature is mapping from Java classes to database tables (and from Java data types to SQL data types), but also to provides data query ( and retrieval facilities ).
It is important that Hibernate generates the SQL calls and relieves keeping the application portable to all SQL databases, with database portability delivered at very little performance overhead.This feature can significialy reduce development time that programmer would have to spent with manual data handling in SQL and JDBC.

Free Career Predictions

What is a Hibernate?

Hibernate is an open source object (relational) mapping library for the Java language,that provides persistent classes and logic without caring how to handle the data.

Persistance in Java ( Hibernate ) is storing data in a relational databse using SQL.

Free Career Predictions

How does hibernate generate beans and DAO(Data Access Object) from database?

Sunday, April 15, 2012

This movie shows some basics about generating beans and DAO (Data Access Object)* from database. To achieve this in this sample we are using JBoss Tools which have Hibernate reverse engineering. That's all for now. Enjoy the movie!

The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessing this data. The oldest and most mature technique is to use the Java Database Connectivity (JDBC) API, which provides the capability to execute SQL queries against a database and then fetch the results, one column at a time. Although this API provides everything a developer needs to access data and to persist application state, it is a cumbersome API to develop against - which makes a Java DAO code generator particularly useful.

Free Career Predictions

Login Form Example With Struts

Wednesday, March 28, 2012

Login Form Example With Struts

This post will show you how a form process in struts 1 framework. We will create a login form and then using struts 1 we will verify the authentication of the user. This example will take following steps :

  1. First of all we will create a form bean (LoginForm.java) that will hold the form values provided by the user.
  2. Create a jsp page (Login.jsp) which will contain the form to be displayed to the user.
  3. Create a success page (Success.jsp) and failure page (Failure.jsp) for providing feedback to the user on their form submission.
  4. Create a controller helper class (LoginAction.java) that will check for the user input and decide which view to be respond to the users (Success.jsp or Failure.jsp).
  5. And finally we will configure our form bean and action classes in struts-config.xml.
LoginForm.java

Following is the code in LoginForm.java file:

package com.demo.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class LoginForm extends ActionForm {

private static final long serialVersionUID = -3491637470205228033L;

private String userName = null;
private String passWord = null;

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;
}

@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.passWord = null;
}
}


There are two fields in this form bean “username” and “password”, that will hold the value of two fields in the login form. One new goods here is the method “reset” which is overwritten by our form bean. “reset” method is called at the end of the every request processed by the struts. In reset method we have set the value of password as null which means every time the user will open the login jsp in browser it will show the last username but will not show the value of password.

Login.jsp

Bellow are the content of Login.jsp:


This jsp will render a form with two fields, “userName” and “passWord”. Struts HTML taglib has been used to create the form. will render as a html form with submit url as “/Login.do”, so our action must use this path in configuration to be run. will be render as html input tag and it’s value will be put in the “username” field of the form bean LoginForm. Same with the property “password”.

LoginAction.java

Lets look inside the code in LoginAction.java:

public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm)form;
if(loginForm.getUsername() == null || loginForm.getPassword() == null ||
!loginForm.getUsername().equalsIgnoreCase("abc") || !loginForm.getPassword().equals("123")){
return mapping.findForward("failure");
}
else
return mapping.findForward("success");
}
}

As you can see first of all the ActionForm instance is typecast to LoginForm in the execute method of LoginAction and then logic to verify the username and password will decide which view to be send back to the user. In this case, username must be “rahul” ans password must be “abc” to go to the view associated with the “success”, otherwise view associated with “failure” will be returned. We can see the jsp files associated with “success” and “failure”.

struts-config.xml

Entries of form beans and actions aer done in struts-config.xml as follows :


Our LoginForm class has been added as a form bean named “loginForm” and associated with the action class LoginAction. Attributes associated with the action class are specified as with the following reason :

name=”loginForm” : Struts will instantiate the LoginForm class will set the value of form properties.
path=”/Login” : The action class will be associated with the request path “/Login.do”. Hence the Login.jsp contains “/Login” as action attribute value.
input=”/Login.jsp” : Form inputs will be taken from Login.jsp.
There are two action forwards also registered with our action which tells struts that if “failure” is return by action then the response view will be “/Failure.jsp” and if “success” is returned by action then the response view will be “/Success.jsp”.

Deploy the war file in Tomcat 6 and hit the url in your browser you will get the following login form:

Free Career Predictions