You are on page 1of 24

JSP FUNDAMENTALS Posted on: January 30, 2005 at 12:00 AM JSP FUNDAMENTALS JSP FUNDAMENTALS By: Hrishikesh Deshpande

Introduction : JSP termed as Java Server Pages is a technology introduced by Sun Microsystems Inc. to develop the web application in more efficient way than Servlets. It has got many

JSP FUNDAMENTALS

By: Hrishikesh Deshpande

Introduction :
JSP termed as Java Server Pages is a technology introduced by Sun Microsystems Inc. to develop the web application in more efficient way than Servlets. It has got many advanced features than servlets, one of them itself define the JSP i.e. JSP separates the presentation logic from the business logic and provide the designer and developer of the web application to work independently without any hassle. Lets start with the basic of the JSPs, JSP is flavour of Cold fusion and ASP and hence provide the flexibility to embed the business logic efficiently within the HTML content (presentation logic). JSP page is built using components such as :

Directives Declarations Scriplets Expressions Standard Actions Custom Tags

Directives :

Listing some of them to start off : 1) Page Syntax : < %@ page Language=?Java? extends=?<Class name>? import=?<class> or <package>? %> Attributes: a. Language = ?Java? b. Import = ?Class? c. Buffersize = ?? d. Scope = ?REQUEST/PAGE/SESSION/APPLICATION? e. And etc?. Page directive is aimed to define certain attribute of a JSP page for e.g. Language of the page in which the page content should be written , which class to be imported so that it can be used within the JSP page. 2) Include Syntax: <%@ include file=?<filename>? %> Attributes: a. file = ?<filename>? This directive is to include the a HTML, JSP or Sevlet file into a JSP file. This is a static inclusion of file i.e. it will be included into the JSP file at the time of compilation and once the JSP file is compiled any changes in the included the file will not the reflected. Declarations: Syntax: <%! Declare all the variables here %> Scriplets: Syntax: <% All your scripts will come here %> Expressions: Syntax: <%= expression evaluation and display the variable %> Standard Action: Syntax:

Include <jsp:include page =?<filename>? />

This inclusion of file is dynamic and the specified file is included in the JSP file at run-time i.e. out put of the included file is inserted into the JSP file.
Forward <jsp:forward page=?<filename>? /> This will redirect to the different page without notifying browser. And many more. Custom Tags: taglib Syntax: <%@ taglib uri=?<tag library uri>? prefix=?<tagprefix>? %> Attributes: a. uri = ?<relative path of the tag library uri>? b. prefix = ?<tagprefix>? prefix is alias name for the tag library name. JSP provides certain Implicit Objects listed below. Object Out Request Response Of Kind JSP writer HttpServletRequest HttpServletRespose HttpSession ServletContext Sevlet Config Object

Session Application

Config Page

PageContext

Page Context => is responsible for generating all other implicit objects.

Out: This object is instantiated implicitly from JSP Writer class and can be used for displaying anything within delimiters. For e.g. out.println(?Hi Buddy?); Request: It is also an implicit object of class HttpServletRequest class and using this object request parameters can be accessed. For e.g. in case of retrieval of parameters from last form is as follows: request.getParameters(?Name?); Where ?Name? is the form element. Response: It is also an implicit object of class HttpServletResponse class and using this object response(sent back to browser) parameters can be modified or set. For e.g. in case of modifying the HTTP headers you can use this object. Response.setBufferSize(?50?); Session: Session object is of class HttpSession and used to maintain the session information. It stores the information in Name-Value pair. For e.g. session.setValue(?Name?,?Jakes?); session.setValue(?Age?,?22?); Application:

This object belongs to class SevletContext and used to maintain certain information throughout the scope of Application. For e.g. Application.setValue(?servername?,?www.myserver.com?); PageContext: This object is of class pageContext and is utilized to access the other implicit objects. Connection Pooling

<%@ page language="Java" import="javax.naming.*,javax.sql.*,java.sql.*,java.util.*"%> <jsp:useBean id="empEli" scope = "page" class ="Elitraining.Employee" /> <jsp:setProperty name ="empEli" property = "*" /> <% try { Properties p = new Properties();

p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://ramses:7001"); InitialContext ic = new InitialContext(p); DataSource ds = (DataSource)ic.lookup("demoPool"); Connection con = ds.getConnection(); Statement stmt = con.createStatement(); int i = stmt.executeUpdate( "insert into employee values('" + empEli.getFirstName() + "','" +

empEli.getLastName() + "')" ); } catch(Exception ex) { ex.printStackTrace(); } %> <html> <body> Employee Firstname is : <jsp:getProperty name="empEli" property ="firstName" /> <BR> Employee Lastname is : <jsp:getProperty name="empEli" property ="lastName" /> </body> </html>

Here we are using the property feature to store all the attributes required to use the connection pool like INITIAL_CONTEXT_FACTORY, PROVIDER_URL.
DataSource ds = (DataSource)ic.lookup("demoPool");

This statement looks up for the connection pool already configured in the particular Application Server. Here the name of the connection pool is named as demoPool.
Connection con = ds.getConnection();

This statement gets hold of an connection to the database from the pool of database connections already existing with the application server. The rest of the statements are standard JDBC statements used in a normal connection to the database.

*************************************************************************************
1 import java.io.*; 2 import javax.servlet.*; 3 import javax.servlet.http.*; 4 import java.sql.*; 5 import java.util.*; 6 7 public class SendMail extends HttpServlet{ 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 else mno=100; if(rs.next()) mno=Integer.parseInt(rs.getString(1))+1; sql="SELECT MAILID FROM MAIL ORDER BY MAILID DESC"; rs=st.executeQuery(sql); public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:bank"); st=con.createStatement(); String sql=null; int mno; Connection con; Statement st; ResultSet rs; PreparedStatement ps;

30 31 32 33 34 35 36 37 38 39 40 41 42

int rano=Integer.parseInt(req.getParameter("ANO"));

String rmsg=req.getParameter("MSG"); ps=con.prepareStatement("insert into mail values(?,?,?)");

ps.setInt(1,mno); ps.setInt(2,rano); ps.setString(3,rmsg); ps.executeUpdate();

res.setContentType("text/html"); PrintWriter out=res.getWriter();

Calendar calendar = new GregorianCalendar(); 43 String 44 date=calendar.get(Calendar.DATE)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar .YEAR); 45 46 out.println("<html><head><title>OnLineEntry</title></head>"); 47 out.println("<body 48 background=\"http:\\\\localhost:8080\\examples\\servlets\\images\\globe.jpg\" link=red alink=green vlink=blue>"); 49 out.println("<h2 align=\"center\"><font color=\"#000080\">"); 50 out.println("<img border=\"0\" 51 src=\"http:\\\\localhost:8080\\examples\\servlets\\images\\earth.gif\" align=\"left\" width=\"50\" height=\"49\">"); 52 out.println("</font></h2><h2 align=\"center\"><font 53 color=\"#000080\">UNIVERSAL NET BANK"); 54 55 56 57 58 out.println("</font></h2><p align=\"center\">&nbsp;</p>"); out.println("<table border=\"2\" width=\"100%\" bordercolorlight=\"#0000FF\" bordercolordark=\"#0000FF\">"); out.println("<tr><td width=\"12%\" valign=\"top\" align=\"center\">"); out.println("<a href=\"http:\\\\localhost:8080\\examples\\servlet\\Welcome?ANO="+rano+"\">Welcome"); out.println("</a></td><td width=\"18%\" valign=\"top\" 59 align=\"center\">");

60 61

out.println("<a href=\"http:\\\\localhost:8080\\examples\\servlet\\ADetail?ANO="+rano+"\">Account Details"); out.println("</a></td><td width=\"14%\" valign=\"top\"

62 align=\"center\">"); 63 64 65 align=\"center\">"); 66 67 68 align=\"center\">"); out.println("<a href=\"http:\\\\localhost:8080\\examples\\servlet\\Deposit?ANO="+rano+"\">Deposits"); out.println("</a></td><td width=\"12%\" valign=\"top\" out.println("<a href=\"http:\\\\localhost:8080\\examples\\servlet\\WithDraw?ANO="+rano+"\">Withdrawals"); out.println("</a></td><td width=\"12%\" valign=\"top\"

out.println("<a 69 href=\"http:\\\\localhost:8080\\examples\\servlet\\Loan?ANO="+rano+"\">Loans"); 70 align=\"center\">"); 71 out.println("<a 72 href=\"http:\\\\localhost:8080\\examples\\servlet\\Mail?ANO="+rano+"\">Mail Us"); 73 align=\"center\">"); 74 out.println("<a 75 href=\"http:\\\\localhost:8080\\examples\\servlet\\Option?ANO="+rano+"\">Options"); 76 align=\"center\">"); 77 out.println("<a 78 href=\"http:\\\\localhost:8080\\examples\\servlets\\Logout.html\">Logout"); 79 80 81 82 83 84 85 86 color=\"#000080\">"); 87 88 89 out.println(rano); out.println("</b></font></td><td width=\"50%\" align=\"right\"><font out.println(date); out.println("</a></td></tr></table><table border=\"0\" width=\"100%\">"); out.println("<tr><td width=\"50%\"><font color=\"#000080\"><b>"); out.println("Date&nbsp;&nbsp; :&nbsp; </b></font><font color=\"#000080\"><b>"); out.println("</a></td><td width=\"11%\" valign=\"top\" out.println("</a></td><td width=\"10%\" valign=\"top\" out.println("</a></td><td width=\"12%\" valign=\"top\"

out.println("<b>Account No : <font size=\"4\">");

90 91 92 93 94 out.println("<p><img border=\"0\" src=\"http:\\\\localhost:8080\\examples\\servlets\\images\\onlinebg.jpg\" width=\"403\" 96 height=\"83\"></p>"); 95 97 98 99 10 0 10 1 to all our esteemed"); 10 2 10 3 10 4 10 5 10 6 10 7 } catch(ClassNotFoundException cnfe){ System.out.println("Class Not Found "+cnfe); } }//END OF doPost } } catch(SQLException sqle4){ System.out.println("Sql4 Exception "+sqle4); out.println("customers. It\'s one step in the right direction to achieving financial freedom"); out.println("and peace of mind.</p>"); out.println("<p>Happy banking!</p>"); out.println("</body></html>"); to do........like"); out.println("going to the bank, standing in queue to make a withdrawal etc..etc..</p>"); out.println("<p>That\'s why we brought our unique net banking facility out.println("<p>Freedom.............That's what we all cherish. </p>"); out.println("<p>Freedom to enjoy all the things we are otherwise prevented from enjoying in"); out.println("order to make way for all the mundane things we are forced out.println("</font></b></font></td></tr></table>"); out.println("<p><font color=\"#000080\"><b>"); out.println("Your Mail has been Successfully Received.</b></font></p>");

2.

A Servlet is a Java class so let us begin by creating a new text document called Simple.java in the 'src' subfolder of the WEB-INF folder.

3. 4. 5. 6.

The Servlet begins by importing the packages required for the class: import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

7.

Next we define our Servlet class as extending the HttpServlet class,

8. public class Simple extends HttpServlet 9. { 10. 11. } 12. We will only be overriding the doGet() method so add the following 13. public void doGet(HttpServletRequest request, 14. HttpServletResponse response) 15. throws ServletException, IOException 16. { 17. 18. 19. }

to the body of the Servlet,

Note, this method, as always, takes two parameters: HttpServletRequest and HttpServletResponse and raises two exceptions: ServletException, and IOException. 20. The first thing we always do within the doGet() method is to define the content type for the output which is usually HTTP but could be other formats for example XML or even binary if the servlet is used to generate images. In our example we are outputting HTML and so we also instantiate the out object to which we will be writing our HTML.
21. response.setContentType("text/html"); 22. PrintWriter out = response.getWriter();

23. Next we want to analyse the query string and pick up the first and last names
24. String sFirstName = request.getParameter("firstname"); 25. String sLastName = request.getParameter("lastname");

26. And then it is just a matter of writing the appropriate HTML to the output stream
27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. out.println("<html>"); out.println("<head>"); out.println("<title>A Simple Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>A Simple Servlet</h1>"); out.println("<p>Hello " + sFirstName + " " + sLastName + "</p>"); out.println("</body>"); out.println("</html>");

39. Finally we close the output stream,


40. out.close();

Part 2. Define the Environment Before we can compile the Servlet we need to setup our environment specifically our classpath. A good practice is to create a batch file that will do this for you so in future you can just run this batch file to set your environment. 1. 2.
3. 4. 5. 6. 7. 8. 9. 10.

Create a batch file in the classes folder called set_env.bat. In this file define your classpath to point to the JDK and to your Servlet Container. If you are using Tomcat the the example below would do. You may need to change the paths.
rem JDK location Set jdk=C:\jdk1.3\bin rem JSP Container location Set AppServer_Home=[tomcat home]\common\lib Set servlet=%AppServer_Home%\servlet.jar Set CLASSPATH=%jdk%;%servlet%;

11. 12. echo %classpath%

13. Save and close this file. 14. Open a command or DOS prompt and navigate to the 'src' directory, the one containing your Servlet and this batch file. 15. Execute the batch file by entering set_env.bat at the command prompt. 16. You have now set the classpath correctly. Note, this classpath will only apply for the duration of the command prompt. If you close the window you will need to re-execute set_env.bat next time you open the command prompt. Part 3. Compile the Servlet 1.
2.

To compile the Servlet enter the following at the command prompt.


javac -d ../classes Simple.java

This will compile the Servlet and if it worked it will create the file Simple.class in the 'classes' folder, the '-d ../classes' switch tells the compiler where to put the compiled class file. If you encountered the error "javax.servlet does not exist" then your classpath is incorrect. Check the paths defined in your batch file and try again. Errors with the actual Servlet file are reported in the usual manner. Below is an error regarding a missing semicolon:
Simple.java:33: ';' expected out.println("") ^
1 error

Part 4. Test the Servlet

1.
2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.

We need to define each Servlet that you are intending to <?xml version="1.0" encoding="ISO-8859-1"?>

use in the web.xml file as follows.

<!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>My Test Servlet</display-name> <description>My Test Servlet </description> <servlet> <servlet-name>SimpleServlet</servlet-name> <servlet-class>Simple</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>/Simple</url-pattern> </servlet-mapping> <web-app>

22. Since we made a change to the 'web.xml' file we will need to restart Tomcat before we can test our Servlet 23. To test the Servlet enter the following URL in a browser,
http://localhost:8100/testapp/Simple?firstname=Barney&lastname=Bear

Here the name of the web application is testapp. Next is the URL pattern that we defined in the 'web.xml' file '/Simple'. Finally we just have a normal query string starting at the question

****************************************************************** JSP Actions for JavaBeans


To use a JavaBean in our JSP page we make use of three JSP actions that we saw earlier. They are,
<jsp:useBean/> - find or instantiate a JavaBean <jsp:setProperty/> - sets the property of a JavaBean <jsp:getProperty/> - gets the value of a JavaBean property

The first of these is used to specify which JavaBean we want to use in our page. The next two actions, as their names suggest, are used to set and get values of properties of the JavaBean. The useBean Action Syntax
<jsp:useBean id="beanID" scope="beanScope" class="package.beanName" />

Where BeanID is the variable you use in your code to reference the Bean, beanScope is the scope the Bean has. It can take one of the following values,
Value page request session Description It lasts until the page completes and there is no storage of state. The JavaBean instance lasts for the client request and so will remain if the request is forwarded. The JavaBean lasts as long as the client session.

application The JavaBean is instantiated with the application and remains in use until the application ends.

and beanName refer to the package and name of the JavaBean you wish to use. Note, some applications servers require that you also use the page import directive to reference the package or class that contains the JavaBean
package

The setProperty and getProperty Actions These are used to set and read property values. Syntax
<jsp:setProperty name="bean" property="propertyName" value="val" /> <jsp:getProperty name="bean" property="propertyName" />

where beanID is the variable name used in the <jsp:usebean/> tag and propertyName is the name of the property you are setting or getting. To use a variable as either a property or a more often as a value then, between the quotes, enter a JSP expression that returns the value of the variable. For example,
<jsp:setProperty name="employeeBean" property="firstName" value="<%= strFirst %>" />

where strFirst is a variable used in the page. Example The following JavaServer Page illustrates how to access a JavaBean from a JavaServer Page. The JavaBean being used here is the one we saw earlier in the item "Example JavaBean".
<HTML> <HEAD> <TITLE>Example: Simple Java Bean</TITLE> <jsp:useBean id="employeeBean" scope="page" class="com.acme.mybean.EmployeeBean" /> </HEAD> <BODY> <% String last = "Burns"; %> <%-- Set bean properties --%> <jsp:setProperty name="employeeBean" property="firstName" value="Robert" /> <jsp:setProperty name="employeeBean" property="lastName" value="<%=last%>" /> <%-- Get bean properties --%> <P> <jsp:getProperty name="employeeBean" property="fullName" /> </P> </BODY> </HTML>

Note, we can also call the associated property methods directly within Java code using syntax similar to,
employeeBean.setFirstName("Robert"); employeeBean.setLastName("Burns"); String name = employeeBean.getFullName();

JavaBeans and HTML Form Synchronisation Suppose we have a web application updates records against a database, employee information say. We have an HTML Form to display the employee data and to allow the end user make changes as required. We also have a JavaBean that performs the reading and writing to and from the database. Our JSP code will therefore need to consist of a series of statements that read the HTML form data and then set all the parameters in the JavaBean. Although this isn't complex code it is certainly repetitive. Form synchronisation is a feature of JSP that synchronises HTML Forms with a JavaBean thus alieviating much of this repetitive coding. More specifically each Form element will synchronise with a property of a JavaBean that has the same name as the Form element.

The following demo illustrates this syncronisation. The scenario here is a JSP page that calculates the interest and repayments made for a bank loan. The two input boxes on the form ask for the amount of the loan and the interest rate. These Form elements synchronise with the equivalent properties in the JavaBean. When this data is submitted the JSP then builds a table of repayment possibilities for 1,2,3,4 and 5 years. Demo Syntax To enable form synchronisation all you need to do is to add the following statement after you declaration of the JavaBean.
<jsp:setProperty name="BeanName" property="*" />

Where BeanName is the name assigned to the JavaBean in the <usebean/> declaration. Then ensure that the Form elements are named the same as the JavaBean properties remembering case sensitivity. Summary JavaBeans are
Component based technology Java classes that adhere to a few specific rules Can be synchronised to work with HTML Forms Great way of removing complex business logic code from the display orientated code of a JSP

**************************************************** JavaServer Pages and JavaBeans


Objective JavaServer Pages and JavaBeans is a big topic and this tutorial doesn't really do it justice. The objective therefore is to provide an introduction to JSP JavaBean architecture and discuss the advantages of using JavaBeans. What is a JavaBean A JavaBean can be defined as a reusable software component. What this means is that we can write a JavaBean that can then be used in a variety of other Java based softwares such as applications, Servlets or JSP pages. In this way we can define our business logic within a JavaBean and then consistently use that logic in seperate applications. In many ways they are analogous to Microsoft's COM and ActiveX technologies. JavaBeans can also have a visual component in a manner similar to the ActiveX controls that can be dragged-anddropped into a Visual Basic application. This tutorial does not discuss this as we are concentrating on how JavaBeans can be of benefit to our JavaServer Page technology. Benefits of JavaBeans We now have three ways of writing code to be used by a JSP. These are,

1. 2. 3.

Place the code at the start of a JSP in a declaration, Use an include statement to reference another file which contains the code and now Package the code in a JavaBean

So which method do we use and when ? As always, it depends on your circumstances. Writing the code within a JSP page is certainly the most straightforward but it does limit the amount of code reuse. Using include statements does lend itself to a certain amount of code reuse and certainly it is the only way to allow reuse of chunks of HTML. By using JavaBeans you can fully separate the business logic from the generation of the display. This is an important philosophy that leads to better structured and more maintainable systems. In our case you would use the JavaServer Page to dynamically generate display and also to handle the user interaction. The JavaBean would take over when you need to perform some complex data processing or when you need to access databases or the file system. The other advantage of using JavaBeans is that the business logic can be used by more than one application. For example, both a client based Java application and a JSP page can access the same JavaBean thus guaranteeing the same functionality. A final point to note is that by using JavaBeans you can split your development team into Java experts and HTML experts. The Java experts would write and develop the JavaBeans and the HTML experts would concentrate of the design of the web application. Example JavaBean More specifically a JavaBean is just a Java class that adheres to the following rules,
it is a public class, it has a public constructor with no arguments it has public get and set methods to read and write to properties.

Properties are always accessed using a common naming convention. For each property two methods must exist: a getXxx() and a setXxx() method where xxx is the name of the property and of a private instance variable. This is an important point as you can easily get tripped up with the syntax. For example, if we want a property called fileName then we would need to define an instance variable called fileName and two methods: getFileName() and setFileName(). Notice the change of case of the f in 'fileName'. The following code is a simple JavaBean
package com.bo.jspBean;

public class employeeBean { private String firstName = ""; private String lastName = ""; //First Name property public void setFirstName(String name) { firstName = name; } public String getFirstName() {

return firstName; } //Last Name Property public void setLastName(String name) { lastName = name; } public String getLastName() { return lastName; } //Full Name Property - Read Only public String getFullName() { return firstName + " " + lastName; } }

This bean is a bit trivial. It has three properties firstName, lastName and fullName. The last property is read only as it doesn't have a set method. Compiling a JavaBean The best way to do this is to get hold of a Java Development tool such as JBuilder which makes the creation of a JavaBean relativley straightforward. It will do the debugging, compiling and packaging all at the click of a mouse! Some Application Servers can only use beens once they have been packaged others can work with JavaBeans unpackaged but still compiled as Java class files. This section gives an overview of the steps involved. Step 1. Compile the class files The installation of the JDK included several utilities that we will use for our JavaBeans. The first utility, javac - the java compiler, is used to compile class files from the java source code files using the following syntax,
javac -verbose *.java

This option will compile all the ".java" files in the current directory. The "verbose" option is used to generate compilation information. There are other options available and are detailed in the JDK documentation. Step 2. Build the JAR Archive File This step is not required by every JSP Engine however it is a good means by which multiple JavaBeans can be packaged in a single file, for example, all the financial JavaBeans are packaged in the finance.jar package. This is where a Java Development Tool is really useful as it can be a bit complex and is very easy to make a mistake. The key is to have the right files in the right locations with the right case sensitive file names. Under our working directory we need to create two other folders, one called "meta-inf" and the second must have the same name as the package name used in our class file definitions. Into this second folder we place all the class files that we want bundled into our JAR archive file. Into the first folder we create a manifest file.

The manifest file is necessary as JSP Containers use this to determine the structure of the JAR file. It is a plain text file typically named "manifest.mf" and is structured like,
Name: packageName/className.class Java-Bean: True

where packageName is the name of the package (and, of course, is also the name of the folder containing the class files) and className is the name of the class we are including in the JAR file. Each class needs it's own entry like this and, note, the last entry must be followed by a carriage return. Next we run the jar utility that will build the JAR file. It takes the following format,
jar cvmf meta-inf\manifest.mf jarName.jar packageName\*.class

This should be entered as a single line and jarName is the name of the JAR file we are building and packageName is the name of the folder in which our class files reside (again it is also the name of the package). The JAR file is usually given the same name as the package. Note if the package name is structured like com.acme.mypackage then the "." need to be replaced with "\" when writing the jar command. For example,
jar cvmf meta-inf\manifest.mf jarName.jar com\acme\mypackage\*.class

The cvmf clause are options available to the JAR utility. The c instructs the utility to create a JAR file, v forces verbose output of the compilation, m indicates that we are providing a manifest file and f indicates that we are providing the JAR file name. These and other options are discuses in more detail in the JDK documentation. So in our example we would enter (as a single line),
jar cvmf meta-inf\mainfest.mf jspBeans.jar jspBeans\*.class

For further details on JAR files see the JAR section of the Java Tutorial at Sun's web site. Step 3. Deploying the JavaBean Once we have created our JavaBean we then need to place the file in a suitable location on our hard drive so that it can be accessed by the Application Server. If you are using the JavaBean unpackaged then place the file under the classes folder of the WEB-INF folder. If you are using a package name such as com.acme.mypackage then you need to create this folder structure under "WEBINF/classes" such as "WEB-INF/classes/com/acme/mypackage/mybean.class".

If you have packaged the JavaBean in a jar file then place the file in the "WEB-INF/lib" folder. You may need to restart your Application Server before the JavaBean recongnised.

**************************************************** JSP Actions for JavaBeans

To use a JavaBean in our JSP page we make use of three JSP actions that we saw earlier. They are, - find or instantiate a JavaBean - sets the property of a JavaBean <jsp:getProperty/> - gets the value of a JavaBean property
<jsp:useBean/> <jsp:setProperty/>

The first of these is used to specify which JavaBean we want to use in our page. The next two actions, as their names suggest, are used to set and get values of properties of the JavaBean. The useBean Action Syntax
<jsp:useBean id="beanID" scope="beanScope" class="package.beanName" />

Where BeanID is the variable you use in your code to reference the Bean, beanScope is the scope the Bean has. It can take one of the following values, Value Description page It lasts until the page completes and there is no storage of state. request The JavaBean instance lasts for the client request and so will remain if the request is forwarded. session The JavaBean lasts as long as the client session. application The JavaBean is instantiated with the application and remains in use until the application ends. and beanName refer to the package and name of the JavaBean you wish to use. Note, some applications servers require that you also use the page import directive to reference the package or class that contains the JavaBean
package

The setProperty and getProperty Actions These are used to set and read property values. Syntax
<jsp:setProperty name="bean" property="propertyName" value="val" /> <jsp:getProperty name="bean" property="propertyName" />

where beanID is the variable name used in the <jsp:usebean/> tag and propertyName is the name of the property you are setting or getting. To use a variable as either a property or a more often as a value then, between the quotes, enter a JSP expression that returns the value of the variable. For example,
<jsp:setProperty name="employeeBean" property="firstName" value="<%= strFirst %>" />

where strFirst is a variable used in the page. Example

The following JavaServer Page illustrates how to access a JavaBean from a JavaServer Page. The JavaBean being used here is the one we saw earlier in the item "Example JavaBean".
<HTML> <HEAD> <TITLE>Example: Simple Java Bean</TITLE> <jsp:useBean id="employeeBean" scope="page" class="com.acme.mybean.EmployeeBean" /> </HEAD> <BODY> <% String last = "Burns"; %> <%-- Set bean properties --%> <jsp:setProperty name="employeeBean" property="firstName" value="Robert" /> <jsp:setProperty name="employeeBean" property="lastName" value="<%=last%>" /> <%-- Get bean properties --%> <P> <jsp:getProperty name="employeeBean" property="fullName" /> </P> </BODY> </HTML>

Note, we can also call the associated property methods directly within Java code using syntax similar to,
employeeBean.setFirstName("Robert"); employeeBean.setLastName("Burns"); String name = employeeBean.getFullName();

JavaBeans and HTML Form Synchronisation Suppose we have a web application updates records against a database, employee information say. We have an HTML Form to display the employee data and to allow the end user make changes as required. We also have a JavaBean that performs the reading and writing to and from the database. Our JSP code will therefore need to consist of a series of statements that read the HTML form data and then set all the parameters in the JavaBean. Although this isn't complex code it is certainly repetitive. Form synchronisation is a feature of JSP that synchronises HTML Forms with a JavaBean thus alieviating much of this repetitive coding. More specifically each Form element will synchronise with a property of a JavaBean that has the same name as the Form element. The following demo illustrates this syncronisation. The scenario here is a JSP page that calculates the interest and repayments made for a bank loan. The two input boxes on the form ask for the amount of the loan and the interest rate. These Form elements synchronise with the equivalent properties in the JavaBean. When this data is submitted the JSP then builds a table of repayment possibilities for 1,2,3,4 and 5 years. Demo Syntax To enable form synchronisation all you need to do is to add the following statement after you declaration of the JavaBean.

<jsp:setProperty name="BeanName" property="*" />

Where BeanName is the name assigned to the JavaBean in the <usebean/> declaration. Then ensure that the Form elements are named the same as the JavaBean properties remembering case sensitivity. Summary JavaBeans are Component based technology Java classes that adhere to a few specific rules Can be synchronised to work with HTML Forms Great way of removing complex business logic code from the display orientated code of a JSP

************************************************************************************************* <% if(!strPassword.equals("password")) { %> <jsp:forward page="Login.jsp"> <jsp:param name="FailReason" value="Wrong Password"/> </jsp:forward> <% } %>

<H2>Welcome!</H2>

******************************************************************************

JavaServer Page Implicit Objects


ObjectiveImplicit objects are a set of Java objects that the JSP Container makes available to developers in each page. These objects may be accessed as built-in variables via scripting elements and can also be accessed programmatically by JavaBeans and Servlets. Overview These objects will be automatically instantiated under specific variable names hence the name implicit. Furthermore, as summarised below, each object must adhere to a specific Java class or interface definition. We have already met one of these objects already - the out object in which we used the println() method to add text to the output stream. Description Page's servlet instance config ServletConfig Servlet configuration information Provides access to all the namespaces associated with a JSP page and pageContext jsp.pageContext access to several page attributes request http.HttpServletRequest Data included with the HTTP Request response http.HttpServletResponse HTTP Response data, e.g. cookies out jsp.JspWriter Output stream for page context session http.HttpSession User specific session data application ServletContext Data shared by all application pages
page jsp.HttpJspPage

Object

Class or Interface

Of these the first three are rarely used. The application, session and request implicit objects have the additional ability to hold arbitrary values. By setting and getting attribute values these objects are able to share information between several JSP pages. This will be discussed later. Request Object The request object retrieves the values that the client browser passed to the server during an HTTP request such as headers, cookies or parameters associated with the request. Among the most common use of the request object is to obtain parameter or query string values. The following demo illustrates how to use the request object for parsing form data. Demo Servlet Class
javax.servlet.HttpServletRequest

The following table summarises the most useful methods available to the request object. For more details consult the Servlet API. Description Returns the value of a request parameter as a String, or null if the parameter getParameter(String name) does not exist. Returns an Enumeration of String objects containing the names of the getParameterNames() parameters contained in this request. Returns an array of String objects containing all of the values the given getParameterValues(String name) request parameter has, or null if the parameter does not exist. Gets the array of cookies found in this request. See below for more details on getCookies() working with cookies. getQueryString() Gets any query string that is part of the HTTP request URI. getRequestURI() Gets the URI to the current JSP page. getHeaderNames() Returns an enumerator of all HTTP header names. Returns the value of an HTTP header such as "QUERY_STRING" or "URL". getHeader(String hdr) The method getHeaderNames() can be used to determine what headers are available. See example below. getAttribute(String) Retrieves the object associated with the named attribute. getAttributeNames() Retrieves the names of all attributes currently associated with the session. setAttribute(String, object) Sets the object to the named attribute. attribute created if it doesn't exist. removeAttribute(String) Removes the object bound with the specified name from this session. Cookie Class The getCookies() method of the request object returns an array of Cookie objects. Cookies are used to allow web browsers to hold small amounts of information or state data associated with a user's web browsing. Common applications for cookies include storing user preferences, automating low security user "sign on" facilities, and helping collect data used for "shopping cart" style applications. Cookies are named and have a single value. They may have optional attributes, including a comment presented to the user, path and domain qualifiers for which hosts see the cookie, a maximum age, and a version. Method

Constructor Summary The following constructs a cookie with a specified name and value.
Cookie(java.lang.String name, java.lang.String value)

See the following section on the response object on how to create cookies.
Cookie

objects have the following methods.

Description Returns the comment describing the purpose of this cookie, or null if no such comment has getComment() 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 targetted. getValue() Returns the value of the cookie. If a web browser presents this cookie to a user, the cookie's purpose will be described using setComment(String) this comment. Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behaviour: the cookie is not stored persistently, setMaxAge(int) 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. 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, setValue(String) colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers. Request Object Examples The following example obtains a list of available cookies.
Cookie[] myCookies = request.getCookies(); for(int n=0; n < myCookies.length; n++) { out.print(myCookies[n].getName() + " "); out.print(myCookies[n].getValue() + "<BR>"); }

Method

This example generates a table of HTTP headers and their respective values.
<table border=1 cellspacing=0 cellpadding=2> <% String strHeaderName = ""; for(Enumeration e = request.getHeaderNames(); e.hasMoreElements() ;) { strHeaderName = (String)e.nextElement(); %> <tr> <td><%= strHeaderName %></td> <td><%= request.getHeader(strHeaderName)%> </td> </tr>

<% } %> </table>

You might also like