Javabeans
- Javabeans are java classes that adhere to the JavaBeans
specification.
This specification establishes guidelines for developing Java code that
is
easy to reuse.
- For a java class to comply with the specifications it must:
- have a constructor that requires no arguments
- can't have any public instance variables
- have getXXX() and setXXX() methods for each class variable (use
isXXX and setXXX for boolean variables)
private String firstName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String
f)
{
firstName = f;
}
- Be careful to follow the naming and capitalization of your
variables and methods. The variable should start with a lower
case letter, the methods start with a lower case set/get/is, then the
name is capitalized.
- JSP allows any java class to be used as a bean, even if it does
not
strictly follow the specification.
- Javabeans allow more complex java code to be created in the
standard
way (as .java files, not embedded in html files), and shared with other
java
applications and applets.
- To create and use a java bean in a jsp file you can use the useBean directive.
<jsp:useBean
id="objectname" class = "classname" scope = "session"/>
- This line checks to see if an instance of objectname exists, if
it doesn't, then it creates an instance of the object defined by
the classname
and
stores it in a variable with the name of id. The object is then
available
for the life time of the session (since scope was set to session). This
is an alternative to using the
session object. Example:
<jsp:useBean id="course"
class="registrarbeans.Course" scope ="session"
/>
replaces the following seqence.
registrarbeans.Course course =
(registrarbeans.Course)session.getAttribute("course");
if(course == null) // new sesssion, just create a course
{
course = new registrarbeans.Course();
session.setAttribute("course", course);
}
- The scope (or lifetime)
of
a java bean can be one of four values
- page - bean is discarded at the end of the page request
processing.
it is available only to the current page.
- request - bean is available to all "included" jsp that are part
of
the request, discarded after the request is done. (request can be
viewed
as the processing of a single submit button press).
- session - bean is discarded when the
session
expires. it can be used across multiple requests from the same user in
the
same session, you code can set the maxium inactive interval for
the session (see notes on sessions). Also, if you are using the
Apache Tomcat web server the session will expire
if the user exits the browser.
- application - bean is available to any jsp running on the
application
server for the lifetime of the server.
- For many objects, the session scope is the most useful. It
allows
data to be shared between jsps invoked during a single user session.
- The id is the object
variable
name
used in your code.
- The class is the class
name
file of the bean. Bean classes are stored in a special directory in the
Web
module, for Apache-Tomcat this directory is WEB-INF/classes.
- In Netbeans, your web
project will have a "src" directory, within that is a "java"
directory. To create a java bean, first create a package in the
src-java directory, then create the class within the package.
- For javabean objects that don't need to be around for the
lifetime
of the session , you use the page or request scope, or you
can import the bean class, then create bean objects as
you
would other java classes in application. Use the import directive to do
this
- <%@ page
import="registrarbeans.Course"%>
- registrarbeans is the name of the package, and also the name
of
the
subdirectory
under the WEB-INF/classes directory.
- To create an instance of Item, you declare a variable and
use
the new statement
- Course course = new Course(.......);
Connecting HTML parameters/forms directly to javabeans objects
- In jsp, it is possible to automatically copy values from a form
into a javabean object.
- to do this you need to use two jsp directives, usebean and
setProperty, e.g.
<jsp:useBean id="course"
class="registrarbeans.Course" scope ="page" />
<jsp:setProperty name="course" property="*"
/>
- the first line creates a Course object and stores it in the
variable course
- the second line initializes the variables in the course object
to request
parameters,
- the "*" means that all all the Javabean variables whose names
match the parameter names in the request object (i.e.. form field
names), should be set to the values of the of the request object
parameters. This matching of names is case sensitive! Also, the first letter of the names needs
to be lower case, i.e. firstName, gender, address, age, lastName.
- This means that if you have an HTML form with field names the
same as
variables in the object, the values from the HTML form will be copied
directly
into the javabean object.
- This is done using the mutator methods, so you must have properly
named methods for each property, e.g. if the name on the form is
"lastName", then the variable should be named "lastName" and mutator
method must be named setLastName (note the capital L). JSP server
will do automatic conversions for numeric types, but exceptions
could be thrown if the data is bad.
- Also, an exception could be thrown if invalid data is present in
one of the inputs, therefore, place this inside a try/catch or use the
errorpage directive
- It is also possible to copy one parameter at a time by
specifying a
single property.
<jsp:setProperty name="course"
param="crn"
property="crn" />
Course.java with JavaBean
requirements:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package registrarbeans;
import java.sql.*;
/**
*
* @author Mark Pendergast
*/
public class Course {
int crn = 0;
String course = "";
String title = "";
int credits = 0;
String instructor = "";
int maxseats = 0;
int seatsleft = 0;
String college = "";
public Course()
{
}
//
// accessor methods, be careful of naming, must be
get followed by variable name with first letter in caps
//
public int getCrn()
{
return crn;
}
public String getCourse()
{
return course;
}
public String getTitle()
{
return title;
}
public int getCredits()
{
return credits;
}
public String getInstructor()
{
return instructor;
}
public int getMaxseats()
{
return maxseats;
}
public int getSeatsleft()
{
return seatsleft;
}
public String getCollege()
{
return college;
}
//
// mutator methods, be careful of naming, must be
set followed by variable name with first letter in caps
//
public void setCrn(int n)
{
crn = n;
}
public void setCourse(String str)
{
course = str;
}
public void setTitle(String str)
{
title = str;
}
public void setCredits(int n)
{
credits = n;
}
public void setInstructor(String str)
{
instructor = str;
}
public void setMaxseats(int n)
{
maxseats = n;
}
public void setSeatsleft(int n)
{
seatsleft = n;
}
public void setCollege(String str)
{
college = str;
}
@Override
public String toString()
{
return crn+" "+course+" "+title;
}
//
// Database methods
//
public boolean insertInto(String url)
{
//
// database work
//
try{
// open a connection
Connection con =
null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //
load the driver
con =
DriverManager.getConnection(url);
// create the sql command
PreparedStatement prep = con.prepareStatement("insert into
courseschedule (crn, course, title, credits, instructor, maxseats,
seatsleft, college) values (?,?,?,?,?,?,?,?)");
prep.setInt(1,crn);
prep.setString(2,course);
prep.setString(3,title);
prep.setInt(4,credits);
prep.setString(5,instructor);
prep.setInt(6,maxseats);
prep.setInt(7,seatsleft);
prep.setString(8,college);
int result =
prep.executeUpdate();
prep.close();
con.close();
if(result == 1)
return true;
else
return false;
}
catch(Exception sqlex)
{
return
false;
}
}
}
addCourseWitBeans.jsp
<%--
Document : addCourseWithBeans
Created on : Oct 24, 2012, 10:34:12 AM
Author : Mark Pendergast
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page errorPage =
"errorPage.jsp" %>
<jsp:useBean id="course"
class="registrarbeans.Course" scope="page"
/>
<jsp:setProperty
name="course" property="*" />
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add
Course</title>
</head>
<body>
<h2>Add Course</h2>
<%
boolean ok =
course.insertInto("jdbc:sqlserver://rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232;");
if(ok)
out.println("course added successfully
:)<br/>");
else
out.println("error - course not added :(
<br/>");
%>
</body>
</html>
errorPage.jsp
<%--
Document : errorPage
Created on : Oct 24, 2012, 10:56:31 AM
Author : Mark Pendergast
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@page isErrorPage = "true"
%>
<html>
<head><title>System Error</title></head>
<body>
<h2>An error occurred while processing your request</h2>
<input type="button" value="click here to try again"
onclick="javascript:history.back()">
<p>
<%= "Input Error : "+exception.getMessage()+"\n"%>
<p>
</body>
</html>