Please style sheet are not equal in internet explorer browser Firefox, Chrome, Safari, Apple and Opera browser please visit this website.

Thank for Visit My Site and Please sent me Shayari, Status and Quotes post request.

Java Server Pages - Session Management in JSP, JSP Components, JSP Cookies

Session Management in JSP
 
Introduction
 
By default, all JSP pages participate in an HTTP session.
The HTTP session object can be accessed within scriptlets through the session implicit JSP object.
Sessions are a good place for storing beans and objects that need to be shared across other JSP pages and servlets that may be accessed by the user.
 
The session objects is identified by a session ID and stored in the browser as a cookie. If cookies are unsupported by the browser, then the session ID may be maintained by URL rewriting. Support for URL rewriting is not mandated by the JSP specification and is supported only within a few servers. Although we cannot place primitive data types into the session, we can store any valid Java object by identifying it by a unique key.
 
For example:
<%
Form form = new Form();
session.putValue("form",form);
%>
 
makes available the Form instance within all JSP pages and servlets belonging to the same session.
 
The instance may be retrieved within a different JSP page as:
<%
Form myForm = (Form) session.getValue("form");
%>
 
The call to session.getValue() returns a reference to the generic Object type.
 
Thus it is important to always cast the value returned to the appropriate data type before using it. It is not mandatory for JSP pages to participate in a session; they may choose to opt out by setting the appropriate attribute of the page directive:
<%@ page session="false" %>
 
There is no limit on the number of objects you can store into the session.
 
However, placing large objects into the session may degrade performance, as they take up valuable heap space. By default, most servers set the lifetime of a session object to 30 minutes, although you can easily reset it on a per session basis by invoking setMaxInvalidationInterval(int secs) on the session object.
 
The figure below highlights the general architecture of session management:
 
The JSP engine holds a live reference to objects placed into the session as long as the session is valid. If the session is invalidated or encounters a session timeout, then the objects within are flagged for garbage collection.
 
 
 
Standard Actions
 
Actions allow us to perform sophisticated tasks like instantiating objects and communicating with server-side resources like JSP pages and servlets without requiring Java coding. Although the same can be achieved using Java code within scriptlets, using action tags promotes reusability of our components and enhances the maintainability of our application.
 
 
Using JavaBean Components
 
The component model for JSP technology is based on JavaBeans component architecture. JavaBeans components are nothing but Java objects which follow a well-defined design/naming pattern: the bean encapsulates its properties by declaring them private and provides public accessor (getter/setter) methods for reading and modifying their values.
 
Before we can access a bean within a JSP page, it is necessary to identify the bean and obtain a reference to it.
 
The <jsp:useBean> tag tries to obtain a reference to an existing instance using the specified id and scope, as the bean may have been previously created and placed into the session or application scope from within a different JSP page.
 
The bean is newly instantiated using the Java class name specified through the class attribute only if a reference was not obtained from the specified scope.
 
 
Consider the tag:
<jsp:useBean id="user" class="MKDTutorials.com.Person"
scope="session" />
In this example, the Person instance is created just once and placed into the session.
 
If this useBean tag is later encountered within a different JSP page, a reference to the original instance that was created before is retrieved from the session.
 
The <jsp:useBean> tag can also optionally include a body, such as :
<jsp:useBean id="user" class="MKDTutorials.com.Person"
scope="session">
<%
user.setDate(DateFormat.getDateInstance( ).format(new Date()));
//etc..
%>
</jsp:useBean>
 
Any scriptlet (or <jsp:setProperty> tags) present within the body of a <jsp:useBean> tag are executed only when the bean is instantiated, and are used to initialize the bean's properties.
 
Once we have declared a JavaBean component, we have access to its properties to customize it.
 
The value of a bean's property is accessed using the <jsp:getProperty> tag. With the <jsp:getProperty> tag, we specify the name of the bean to use (from the id field of useBean), as well as the name of the property whose value we are interested in. The actual value is then directly printed to the output:
<jsp:getProperty name="user" property="name" />
 
Changing the property of a JavaBean component requires you to use the <jsp:setProperty> tag.
 
For this tag, we identify the bean and property to modify and provide the new value:
<jsp:setProperty name="user" property="name"
value="MKDTutorials.com" />
or
<jsp:setProperty name="user" property="name"
value="<%=expression %>" />
 
When developing beans for processing form data, we can follow a common design pattern by matching the names of the bean properties with the names of the form input elements.
 
We also need to define the corresponding getter/setter methods for each property within the bean. The advantage in this is that we can now direct the JSP engine to parse all the incoming values from the HTML form elements that are part of the request object, then assign them to their corresponding bean properties with a single statement, like this:
<jsp:setProperty name="user" property="*"/>
 
This runtime magic is possible through a process called introspection, which lets a class expose its properties on request.
 
The introspection is managed by the JSP engine, and implemented through the Java reflection mechanism. This feature alone can be a lifesaver when processing complex forms containing a significant number of input elements.
 
If the names of our bean properties do not match those of the form's input elements, they can still be mapped explicitly to our property by naming the parameter as:
<jsp:setProperty name="user" property="address"
param="parameterName" />
 
 
 
Forwarding Requests
 
With the <jsp:forward> tag, we can redirect the request to any JSP, servlet, or static HTML page within the same context as the invoking page. This effectively halts processing of the current page at the point where the redirection occurs, although all processing up to that point still takes place:
<jsp:forward page="somePage.jsp" />
 
The invoking page can also pass the target resource bean parameters by placing them into the request, as shown in the diagram:
 
 
A <jsp:forward> tag may also have jsp:param subelements that can provide values for some elements in the request used in the forwarding:
<jsp:forward page="<%= somePage %>" >
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>
 
 
 
Request Chaining
 
Request chaining is a powerful feature and can be used to effectively meld JSP pages and servlets in processing HTML forms, as shown in the following figure:
 
 
Consider the following JSP page, say Bean1.jsp, which creates a named instance fBean of type FormBean, places it in the request, and forwards the call to the servlet JSP2Servlet.
Observe the way the bean is instantiated--here we automatically call the bean's setter methods for properties which match the names of the posted form elements, while passing the corresponding values to the methods.
<jsp:useBean id="fBean" class="govi.FormBean"
scope="request"/>
<jsp:setProperty name="fBean" property="*" />
<jsp:forward page="/servlet/JSP2Servlet" />
 
The servlet JSP2Servlet now extracts the bean passed to it from the request, makes changes using the appropriate setters, and forwards the call to another JSP page Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller, can also place additional beans if necessary, within the request.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try
{
FormBean f = (FormBean) request.getAttribute ("fBean");
f.setName("Aman");
// do whatever else necessary
getServletConfig().getServletContext().
getRequestDispatcher("/jsp/Bean2.jsp").
forward(request, response);
}
catch (Exception ex)
{
. . .
}
}
 
The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that may have been passed by the controller servlet) from the request and extract its properties.
<html>
<body>
<jsp:useBean id="fBean" class="govi.FormBean"
scope="request"/>
<jsp:getProperty name="fBean" property="name" />
</body>
</html>
 
 
 
Including Requests
 
The <jsp:include> tag can be used to redirect the request to any static or dynamic resource that is in the same context as the calling JSP page. The calling page can also pass the target resource bean parameters by placing them into the request, as shown in the diagram:
 
 
Consider the following JSP page, say Bean1.jsp, which creates a named instance fBean of type FormBean, places it in the request, and forwards the call to the servlet JSP2Servlet.
Observe the way the bean is instantiated--here we automatically call the bean's setter methods for properties which match the names of the posted form elements, while passing the corresponding values to the methods.
 
For example:
<jsp:include page="tutorial.jsp" flush="true"/>
 
not only allows tutorial.jsp to access any beans placed within the request using a <jsp:useBean> tag, but the dynamic content produced by it is inserted into the calling page at the point where the <jsp:include> tag occurs. The included resource, however, cannot set any HTTP headers, which precludes it from doing things like setting cookies, or else an exception is thrown.
 
 
 
Synchronization Issues
 
By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state is effectively synchronized. There are a couple of different ways to ensure that the service methods are thread-safe.
 
The easy approach is to include the JSP page directive:
<%@ page isThreadSafe="false" %>
 
For example:
<jsp:include page="tutorial.jsp" flush="true"/>
 
This causes the JSP page implementation class to implement the SingleThreadModel interface, resulting in the synchronization of the service method, and having multiple instances of the servlet to be loaded in memory. The concurrent client requests are then distributed evenly amongst these instances for processing in a round-robin fashion, as shown below:
 
 
The downside of using this approach is that it is not scalable. If the wait queue grows due to a large number of concurrent requests overwhelming the processing ability of the servlet instances, then the client may suffer a significant delay in obtaining the response.
 
A better approach is to explicitly synchronize access to shared objects (like those instances with application scope, for example) within the JSP page, using scriptlets:
<%
synchronized (application)
{
SharedObject form = (SharedObject)
application.getAttribute("sharedObject");
foo.update(someValue);
application.setAttribute("sharedObject",form);
}
%>
 
 
 
JSP Components
 
Introduction
 
A JavaServer Pages (JSP) component may use a JavaBeans component as a proxy to access an enterprise bean.
The following diagram illustrates how these components work together:
 
JSP Client of an Enterprise Bean
 
The Below sections that follow show how to create a J2EE application with the following elements:
 
.JSP client:
<html>
<jsp:useBean id="accountBean" scope="session" class="AccountBean" />
<jsp:setProperty name="accountBean" property="*" />
<%! String status; %>
<% status = accountBean.processRequest(); %>
<html>

<head>
<title>Account JSP</title>
</head>
<body background="back.gif">
<font size = 5 color="#CC0000">
<h1><b><center>Account JSP Example</center></b></h1>
<hr>
<br>

<form method=POST action=Account.jsp>
<BR>
<br>Account ID <INPUT type=text name="id" size="8" value="<jsp:getProperty name="accountBean" property="id" />" >
Balance <INPUT type=text name="balance" size="8" value="<jsp:getProperty name="accountBean" property="balance" />" ><br>
First Name <INPUT type=text name="firstName" size="8" value="<jsp:getProperty name="accountBean" property="firstName" />">
Last Name <INPUT type=text name="lastName" "size=8" Value="<jsp:getProperty name="accountBean" property="lastName" />" ><br> <br>
<h2><b>Action :</b></h2>
<INPUT type="radio" name="action" value="create">Create
<INPUT type="radio" name="action" value="find">Find
<INPUT type="radio" name="action" value="debit">Debit
<INPUT type="radio" name="action" value="credit">Credit
<br>

<br>Amount <INPUT type=text name="amount"><br>
<INPUT type=submit name="submit" value="Submit">
</form>
</FONT>
</body>
</html>

<hr>
<h3><b>Status :</b></h3> <%= status %>
</html>
 
.JavaBeans component:
 
import java.util.*;
import java.io.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class AccountBean {
private String action;
private String id;
private String firstName;
private String lastName;
private double balance;
private double amount;

private AccountHome accountHome;
private Account account;

public AccountBean() {
try {
Context ic = new InitialContext();

java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account");

accountHome = (AccountHome) PortableRemoteObject.narrow(objref, AccountHome.class);

System.out.println("obtained accountHome object");

} catch (Exception re) {
System.err.println ("Couldn't locate Account Home");
re.printStackTrace();
}
reset();

}
public String processRequest() {
String message = "";
System.out.println("Process request called ");
System.out.println(this);
try {
if( action.equals("create") ) {
account =
accountHome.create(id, firstName, lastName, balance);
message = "Created account '" + id + "'";

}
else if( action.equals("debit") ) {
account = accountHome.findByPrimaryKey(id);
account.debit(amount);
loadFromEJB();
message = "Debited account '" + id + "' by $" + amount;
}
else if( action.equals("credit") ) {
account = accountHome.findByPrimaryKey(id);
account.credit(amount);
loadFromEJB();
message = "Credited account '" + id + "' by $" + amount;
}
else if( action.equals("find") ) {
account = accountHome.findByPrimaryKey(id);
loadFromEJB();
message = "Found account '" + id;

}
} // try
catch (Exception e) {
message = e.toString();
}
return message;
}
public String getAction() {
System.out.println("Getting action");
return action;
}
public void setAction(String a) {
System.out.println("Setting action : " + a);
action = a;
}
public String getId() {
System.out.println("Getting id");
return id;
}
public void setId(String i) {
System.out.println("Setting id : " + i);
id = i;
}
public String getFirstName() {
System.out.println("Getting firstName");
return firstName;
}
public void setFirstName(String f) {
System.out.println("Setting first name : " + f);
firstName = f;
}

public String getLastName() {
System.out.println("Getting lastName");
return lastName;
}

public void setLastName(String l) {
System.out.println("Setting last name : " + l);
lastName = l;
}

public double getBalance() {
System.out.println("Getting balance");
return balance;
}

public void setBalance(double b) {
System.out.println("Setting balance : " + b);
balance = b;
}

public double getAmount() {
System.out.println("Getting amount");
return amount;
}

public void setAmount(double a) {
System.out.println("Setting amount : " + a);
amount = a;
}

private void reset() {
System.out.println("Calling reset()");
final String emptyString = "";
final double zero = 0.0;

setAction(emptyString);
setId(emptyString);
setFirstName(emptyString);
setLastName(emptyString);
setBalance(zero);
setAmount(zero);
}

private void loadFromEJB() {
System.out.println("Calling loadFromEJB()");
try {
setFirstName(account.getFirstName());
setLastName(account.getLastName());
setBalance(account.getBalance());
} catch (Exception re) {
System.err.println ("Failed to load AccountBean from AccountEJB.");
re.printStackTrace();v }
}

public String toString() {
StringBuffer output = new StringBuffer();

output.append("Action : " + action);
output.append( " Id : " + id);
output.append( " first name : " + firstName);
output.append( " last name : " + lastName);
output.append( " balance : " + balance);
output.append( " amount : " + amount);
return output.toString();
}
}
 
.Entity bean:
 
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;

public class AccountEJB implements EntityBean {

private String id;
private String firstName;
private String lastName;
private double balance;
private EntityContext context;
private Connection con;
private String dbName = "java:comp/env/jdbc/AccountDB";

public void debit(double amount)
throws InsufficientBalanceException {

if (balance - amount < 0) {
throw new InsufficientBalanceException();
}
balance -= amount;
}

public void credit(double amount) {

balance += amount;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {

return lastName;
}

public double getBalance() {

return balance;
}

public String ejbCreate(String id, String firstName, String lastName, double balance)
throws CreateException {

if (balance < 0.00) {
throw new CreateException
("A negative initial balance is not allowed.");
}

try {
insertRow(id, firstName, lastName, balance);
} catch (Exception ex) {
throw new EJBException("ejbCreate: " + ex.getMessage());
}

this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;

return id;
}

public String ejbFindByPrimaryKey(String primaryKey)
throws FinderException {

boolean result;
try {
result = selectByPrimaryKey(primaryKey);
} catch (Exception ex) {
throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
}
if (result) {
return primaryKey;
}
else {
throw new ObjectNotFoundException
("Row for id " + primaryKey + " not found.");
}
}

public Collection ejbFindByLastName(String lastName) throws FinderException {

Collection result;

try {
result = selectByLastName(lastName);
} catch (Exception ex) {
throw new EJBException("ejbFindByLastName " + ex.getMessage());

}

if (result.isEmpty()) {
throw new ObjectNotFoundException("No rows found.");
}
else {
return result;
}
}

public Collection ejbFindInRange(double low, double high)
throws FinderException {

Collection result;

try {
result = selectInRange(low, high);

} catch (Exception ex) {
throw new EJBException("ejbFindInRange: " + ex.getMessage());
}
if (result.isEmpty()) {
throw new ObjectNotFoundException("No rows found.");
}
else {
return result;
}
}

public void ejbRemove() {

try {
deleteRow(id);
} catch (Exception ex) {
throw new EJBException("ejbRemove: " + ex.getMessage());
}
}

public void setEntityContext(EntityContext context) {

this.context = context;
try {
makeConnection();
} catch (Exception ex) {
throw new EJBException("Unable to connect to database. " +
ex.getMessage());
}
}

public void unsetEntityContext() {


try {
con.close();
} catch (SQLException ex) {
throw new EJBException("unsetEntityContext: " + ex.getMessage());
}
}

public void ejbActivate() {

id = (String)context.getPrimaryKey();
}
public void ejbPassivate() {

id = null;
}
public void ejbLoad() {

try {
loadRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: " + ex.getMessage());
}
}

public void ejbStore() {

try {
storeRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: " +
ex.getMessage());
}
}

public void ejbPostCreate(String id, String firstName,
String lastName, double balance)
{ }

/*********************** Database Routines *************************/

private void makeConnection() throws NamingException, SQLException {

InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(dbName);
con = ds.getConnection();
}

private void insertRow (String id, String firstName, String lastName,
double balance) throws SQLException {

String insertStatement = "insert into account values ( ? , ? , ? , ? )";
PreparedStatement prepStmt =
con.prepareStatement(insertStatement);

prepStmt.setString(1, id);
prepStmt.setString(2, firstName);
prepStmt.setString(3, lastName);
prepStmt.setDouble(4, balance);

prepStmt.executeUpdate();
prepStmt.close();
}

private void deleteRow(String id) throws SQLException {

String deleteStatement = "delete from account where id = ? ";
PreparedStatement prepStmt = con.prepareStatement(deleteStatement);

prepStmt.setString(1, id);
prepStmt.executeUpdate();
prepStmt.close();
}

private boolean selectByPrimaryKey(String primaryKey)
throws SQLException {

String selectStatement =
"select id " +
"from account where id = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setString(1, primaryKey);

ResultSet rs = prepStmt.executeQuery();
boolean result = rs.next();
prepStmt.close();
return result;
}

private Collection selectByLastName(String lastName)
throws SQLException {

String selectStatement =
"select id " +
"from account where lastname = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);

prepStmt.setString(1, lastName);
ResultSet rs = prepStmt.executeQuery();
ArrayList a = new ArrayList();

while (rs.next()) {
String id = rs.getString(1);
a.add(id);
}

prepStmt.close();
return a;
}

private Collection selectInRange(double low, double high)
throws SQLException {

String selectStatement =
"select id from account " +
"where balance between ? and ?";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setDouble(1, low);
prepStmt.setDouble(2, high);
ResultSet rs = prepStmt.executeQuery();
ArrayList a = new ArrayList();

while (rs.next()) {
String id = rs.getString(1);
a.add(id);
}

prepStmt.close();
return a;
}

private void loadRow() throws SQLException {

String selectStatement =
"select firstname, lastname, balance " +
"from account where id = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);

prepStmt.setString(1, this.id);

ResultSet rs = prepStmt.executeQuery();

if (rs.next()) {
this.firstName = rs.getString(1);
this.lastName = rs.getString(2);
this.balance = rs.getDouble(3);
prepStmt.close();
}
else {
prepStmt.close();
throw new NoSuchEntityException("Row for id " + id +
" not found in database.");
}
}

private void storeRow() throws SQLException {
String updateStatement =
"update account set firstname = ? ," +
"lastname = ? , balance = ? " +
"where id = ?";
PreparedStatement prepStmt =
con.prepareStatement(updateStatement);
prepStmt.setString(1, firstName);
prepStmt.setString(2, lastName);
prepStmt.setDouble(3, balance);
prepStmt.setString(4, id);
int rowCount = prepStmt.executeUpdate();
prepStmt.close();

if (rowCount == 0) {
throw new EJBException("Storing row for id " + id + " failed.");
}
}

} // AccountEJB
 
The Account.jsp and AccountBean.java files are in the
doc/guides/ejb/examples/jsptobean directory.
 
The AccountEJB.java source code is in the
doc/guides/ejb/examples/account directory.
 
 
 
Setting Up the JSP Component's J2EE Application
 
The following figure shows the J2EE application that contains the JSP component.
 
Stored in a .ear file, the J2EE application holds an EJB .jar file and a web component .war file.
 
The EJB .jar file contains the AccountEJB entity bean.
The .war file contains the JSP component (Account.jsp) and the JavaBeans component (AccountBean).
 
J2EE Application .ear File
 
 
The sections that follow describe how to create and package the web components, but first, we should set up the J2EE application:
1. Create a J2EE application named AccountJSPApp.
2. Create an entity bean for the AccountEJB class.
3. Add the entity bean to the J2EE application.
4. Set the display name for the entity bean to AccountBean.
5. Create the ACCOUNT database table.
 
 
 
Setting Up the Database
 
The instructions that follow explain how to use the AccountEJB example with a Cloudscape database. The Cloudscape software is included with the J2EE SDK download bundle. We may also run this example with databases provided by other vendors.
 
1. From the command-line prompt, run the Cloudscape database server:
cloudscape -start
 
2. Edit the script that creates the account database table.
Write the Following command in Windows:
cd %J2EE_HOME%\doc\guides\ejb\examples\util
In the cloudTable script, change <installation-location> to the directory in which you installed the J2EE SDK.
 
3. Run the script that creates the account database table.
Note: If you are not using a Cloudscape database, we may run the account/createTable.sql script to create the account table.
 
 
Writing the JSP File
 
Here we briefly describes the JSP tags in the Account.jsp file. These tags are marked by bold font in the full listing of Account.jsp included at the end of this section.
 
The first JSP tag in the Account.jsp file specifies the JavaBeans component. The jsp:useBean tag creates a JavaBeans component by instantiating the AccountBean class, names the component accountBean, and indicates that the component will be available for the current HTTP session.
 
Unlike the other JSP tags, the jsp:useBean tag is executed just once during the session-- when the end-user first accesses the Account.jsp page:
<jsp:useBean id="accountBean" scope="session" class="AccountBean" />
 
The jsp:setProperty tag sets all of the property values in the accountBean to the parameters passed by the HTML form.
For example, if the end-user selects the Debit radio button and clicks Submit, the action parameter is set to debit. This parameter value is sent to the web server, which assigns it to the action property value of the accountBean.
 
The asterisk in the tag indicates that all properties will be set:
<jsp:setProperty name="accountBean" property="*" />
 
JSP scripting elements are enclosed as follows:
<% element %>.
 
The first scripting element declares the status variable:
<%! String status; %>
 
The next scripting element invokes processRequest method of the accountBean object.
 
This method checks the action property value and invokes methods on the entity bean:
<% status = accountBean.processRequest(); %>
 
Near the bottom of the Account.jsp file, the status variable returned by the processRequest method is displayed:
<h3><b>Status :</b></h3> <%= status %>
 
In the HTML form tag, the action parameter indicates that the Account.jsp page is to be executed when the end-user clicks the form's Submit button.
( the web server transforms the Account.jsp page into a servlet which it then executes.)
 
Except for the jsp:useBean tag, every JSP tag and scripting element in the Account.jsp page is executed whenever the end-user clicks Submit:
<form method=POST action=Account.jsp>
 
Each jsp:getProperty tag fetches a property value from the accountBean. For example, the second jsp:getProperty tag retrieves the balance property from the accountBean. The balance is displayed in the text field of the HTML form. The next time the end-user clicks the Submit button, the value in the text field is sent to the web server as the balance parameter. The jsp:setProperty tag causes the web server to assign this parameter to the balance property of the accountBean.
 
Here is the jsp:getProperty tag for the balance property:
 
<INPUT type=text name="balance" size="8"
value="<jsp:getProperty name="accountBean" property="balance" />">
The full listing for the Account.jsp file follows:
<html>
<jsp:useBean id="accountBean" scope="session" class="AccountBean" />
<jsp:setProperty name="accountBean" property="*" />
<%! String status; %>
<% status = accountBean.processRequest(); %>

<html>
<head>
<title>Account JSP</title>
</head>
<body background="back.gif">
<font size = 5 color="#CC0000">
<h1><b><center>Account JSP Example</center></b></h1>
<hr>
<br>
<form method=POST action=Account.jsp>
<br>

<br>Account ID
<INPUT type=text name="id" size="8"
value="<jsp:getProperty name="accountBean" property="id" />" >
Balance
<INPUT type=text name="balance" size="8"
value="<jsp:getProperty name="accountBean" property="balance" />" >
<br>
First Name
<INPUT type=text name="firstName" size="8"
value="<jsp:getProperty name="accountBean" property="firstName" />">
Last Name
<INPUT type=text name="lastName" "size=8"
Value="<jsp:getProperty name="accountBean" property="lastName" />"
><br>

<br>
<h2><b>Action :</b></h2>
<INPUT type="radio" name="action" value="find">Find
<INPUT type="radio" name="action" value="create">Create
<INPUT type="radio" name="action" value="debit">Debit
<INPUT type="radio" name="action" value="credit">Credit
<br>

<br>Amount <INPUT type=text name="amount"><br>
<INPUT type=submit name="submit" value="Submit">

</form>
</FONT>
</body>
</html>

<hr>
<h3><b>Status :</b></h3> <%= status %>
</html>
 
 
 
Coding the JavaBeans Component
 
The following description of the AccountBean code is quite brief.
 
The AccountBean JavaBeans component is created when the end-user first accesses the Account.jsp page. (This action is specified by the jsp:useBean tag in the Account.jsp file.) The AccountBean class accesses the entity bean implemented by the AccountEJB class. The constructor of the AccountBean class locates the entity bean's home interface by invoking the lookup method:
 
public AccountBean()
{

try
{
Context ic = new InitialContext();
java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account");
accountHome =
(AccountHome) PortableRemoteObject.narrow(objref, AccountHome.class);
}
catch (Exception re)
{
System.err.println ("Couldn't locate Account Home");
re.printStackTrace();
}
reset();
}
 
The end-user indicates the action parameter by selecting a radio button on the Account.jsp page. The web server assigns the parameter value to the action property of the AccountBean. Invoked by a scripting element in the Account.jsp page, the processRequest method of the AccountBean checks the value of the action property. If the action property is create, for example, the processRequest method creates a new entity bean. Here is the code for the processRequest method:
 
public String processRequest()
{

String message = "";

System.out.println("Process request called ");
System.out.println(this);

try
{

if( action.equals("create") )
{

account =accountHome.create(id, firstName, lastName, balance);
message = "Created account `" + id + "`";

}
else if( action.equals("debit") )
{

account = accountHome.findByPrimaryKey(id);
account.debit(amount);
loadFromEJB();
message = "Debited account `" + id + "` by $" + amount;

}
else if( action.equals("credit") )
{
account = accountHome.findByPrimaryKey(id);
account.credit(amount);
loadFromEJB();
message = "Credited account `" + id + "` by $" + amount;

}
else if( action.equals("find") )
{

account = accountHome.findByPrimaryKey(id);
loadFromEJB();
message = "Found account `" + id;

}

} // try

catch (Exception e) {
message = e.toString();
}

return message;
}
 
 
 
Compiling the JavaBeans Component
 
When compiling AccountBean.java, you must include the j2ee.jar and ejb.jar files in the classpath. The ejb.jar file is required because it contains the class files for the Account and AccountHome interfaces-- types used by the AccountBean class. When you created the enterprise bean (AccountEJB) for the AccountJSPApp application, the tool inserted the ejb.jar file into the AccountJSPApp.ear file.
 
To extract the ejb.jar file from the AccountJSPApp.ear file, follow these steps:
1. In the tree view, select the EJB .jar file for the AccountJSPApp application.
2. From the File menu, choose Save As.
3. Save the ejb.jar file in the examples/jsptobean directory.
 
 
Creating the JSP Component's .war File
 
To package the AccountBean.class and Account.jsp files in a .war file, you run the New Web Component Wizard of the Application Deployment Tool. To start the wizard, from the File menu choose New Web Component. The wizard displays the following dialog boxes. (You may skip any dialog boxes not listed here.)
 
WAR File General Properties Dialog Box:
a. In the combo box labelled "Web Component Will Go In," select AccountJSPApp.
b. In the WAR Display Name field, enter AccountWAR.
c. Click Add.
d. In the Add Content Files dialog box, choose the root directory containing the Account.jsp file (examples/jsptobean). You may either type the directory name in the Root Directory field or locate it by clicking Browse.
e. Select the Account.jsp file from the text area and click Add.
f. Click Next.
g. In the Add Class Files dialog box choose, the examples/jsptobean directory again.
h. Select the AccountBean.class file from the text area and click Add.
i. Click Finish.
j. Click Next.
 
Choose Component Type Dialog Box:
a. Select JSP.
b. Click Next.
 
Component General Properties Dialog Box:
a. In the JSP Filename combo box, select Account.jsp.
b. In the Web Component Display Name field, enter TheAccount.
c. Click Next.
 
Enterprise Bean References Dialog Box:
a. Click Add.
b. In the Coded Name column enter ejb/Account.
c. In the Type column select Entity.
d. In the Home column enter AccountHome.
e. In the Remote column enter Account.
f. Click Finish.
 
 
Specifying the Web Context Root
1. In the tree view select AccountJSPApp.
2. In the Web Context tabbed pane, enter AccountContextRoot in the ContextRoot column.
 
 
 
Specifying the JNDI Names
 
In the JNDI Names tabbed pane for the AccountJSPApp, enter the JNDI names shown in the following table:
 
AccountJSPApp JNDI Names
Component/ Reference Name JNDI Name
AccountBean MyAccount
jdbc/AccountDB jdbc/Cloudscape
ejb/Account MyAccount
 
 
Deploying the JSP Component's J2EE Application
 
1. From the Tools menu, choose Deploy Application.
2. In the first dialog box, do not select the checkbox labelled "Return Client Jar."
3. In the second dialog box, verify the JNDI names.
4. In the third dialog box, verify the context root.
 
 
 
Running the JSP Component
 
To run Account.jsp from your browser, specify the URL as follows, but replace with the name of the machine that is running the J2EE server:
http://<host>:8000/AccountContextRoot/Account.jsp
 
To create a new account, follow these steps:
1. In the Account ID field, enter a three-digit integer.
2. In the Balance field, enter the intitial balance (for example, 100.00).
3. In the First Name and Last Name fields enter your name.
4. Under Action, select Create.
5. Click the Submit button.
 
To credit an account, perform the following tasks:
1. In the Account ID field, enter the three-digit account identifier.
2. In the Amount field, enter the credit amount (for example, 55.00).
3. Under Action, select Credit.
5. Click the Submit button.
 
 
JSP Cookies
 
Introduction
 
Here we will see how to handle cookies in JSP pages. In this we will learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page.
 
Cookies are short pieces of data sent by web servers to the client browser. The cookies are saved to clients hard disk in the form of small text file.
 
Cookies helps the web servers to identify web users, by this way server tracks the user.
Cookies pay very important role in the session tracking.
 
 
 
In JSP cookie are the object of the class javax.servlet.http.Cookie.
 
This class is used to creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server.
 
A cookie's value can uniquely identify a client, so cookies are commonly used for session management.
 
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
 
The getCookies() method of the request object returns an array of Cookie objects.
 
Cookies can be constructed using the following code:
Cookie(java.lang.String name, java.lang.String value)
 
Cookie objects have the following methods:
 
Method
Description
getComment() Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
getMaxAge() Returns the maximum specified age of the cookie.
getName() Returns the name of the cookie.
getPath() Returns the prefix of all URLs for which this cookie is targeted.
getValue() Returns the value of the cookie.
setComment(String) If a web browser presents this cookie to a user, the cookie's purpose will be described using this comment.
setMaxAge(int) the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted
setPath(String) This cookie should be presented only with requests beginning with this URL.
setValue(String) Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the "at" sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.
 
 
 
Example Using Cookies
 
No we will write code in JSP file to set and then display the cookie.
 
Create Form
Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name.
 
<%@ page language="java" %>

<html>

<head>

<title>Cookie Input Form</title>
</head>

<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>

<html>
 
Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file, which sets the cookie.
 
Output:
 
Here is the code of setcookie.jsp file:
 
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";


Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);

%>

<html>

<head>

<title>Cookie Saved</title>

</head>
<body>

<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>

</body>

<html>
Above code sets the cookie and then displays a link to view cookie page.
 
Output:
 
Here is the code of display cookie page (showcookievalue.jsp):
 
<%@ page language="java" %>
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}
%>
<html>
<head>
<title>Show Saved Cookie</title>
</head>
<body>


<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%>
<p>Welcome: <%=myCookie.getValue()%>.
<%
}
%>
</body>

<html>
When user navigates to the above the page, cookie value is displayed.
 
Output:
 
 

SHARE THIS PAGE

0 Comments:

Post a Comment

Circle Me On Google Plus

Subject

Follow Us