Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,423,427 members, 5,437,762 topics. Date: Sunday, 23 February 2020 at 03:01 PM

JSP Web Development - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / JSP Web Development (5238 Views)

100+ Java, JS & JSP Apps With Their Source Code That You Can Make Money With / HTML And Jsp / Java Server Pages (jsp) Or Java Server Face(jsf Which Path To Trend? ? ? ? (2) (3) (4)

(1) (2) (Reply) (Go Down)

JSP Web Development by sbucareer(f): 12:59pm On Mar 15, 2007

This trail is a Beginning, weblog, and so I/we'll show you everything you need to know, from scratch. In order to get the most out of this trail, you'll need to have an understanding of HTML and how to create a static web page. If you don't know HTML you should spend some time familiarizing yourself with HTML before you start to learn about JavaServer Pages.

I/we won't assume that you have any programming experience; this trail will teach you all you need to know in order to create dynamic web application

However, this trail will also suit you if you have some programming experience in a language other than java, and would like to turn your hand towards web programming.

This trail will be one of its kind, we will cover in chronological order these technologies.

1. Starting web Programming
1.1 Installing the require software
1.1.1 Installing Java
1.2 Installing Tomcat
1.2.1 Configuring Your Environment
1.3 Your First Web application

1.4 Brief History of Java and the web
1.4.1 The web
1.4.2 How the web works
1.4.3 Common Gateway Interface(CGI)
1, 4.3.1 Alternative To CGI
1.4.4 Java and the web
1.4.4.1 JavaServer Pages (JSP)
1.4.4.2 JacaScript

2. Storing Data and Performing Calculations
2.1 Variable Name
2.2 Primitive Data typee
2.3 Scriptlet elements
2.3.1 Comments
2.3.2 Expressions
2.3.3 Declarations
2.3.4 Good coding practice

3. Getting data from browser
3.1 Retrieving client  data using HTML forms
3.2 Using HTML controls
3.3 Request processing

4.Introduction JavaBean
4.1 creating component in java
4.2 Introducing javabeans
4.2.1 Properties
4.2.2 Building a JavaBean
4.2.3 Variable Scope and Accessibility
4.2.4 Using JavaBean
4.2.5 Bean Tags

5.Creating Database with Java
5.1 Introducing Database
5.2 Introducing SQL
5.3 Java Database Connectivity
5.4 Populating Tables
5.5 Querying Database with Java

6.Case Study
Designing a local tourism authority- used by tourists who want to browse local attractions and associated events

7.Conclusion
7.1 Milestons
7.2 Achievements and regrets






References and key text can be found at wrox press
Re: JSP Web Development by sbucareer(f): 1:33pm On Mar 15, 2007
[size=16pt]Starting web Programming[/size]



Installing the Software

The first step in writing any software is installing the necessary software and libraries.

Installing Java

You would need the Java Software Development Kit (JSDK). Recently Sun Microsystems has changed it name to Java 2 Second Edition (J2SE). Technically they are both the same thing. It contains all the API's required to develop Java softwar. Although Java is an open source, some communities have adapted their own API's and jar it up and add it into their classpath for the JVM to see it.

Download point your browser to sun microsystems. You would be looking for the lastest version of the Java 2 SDK, standard Edition, disregarding any beta version that may be available. As of this writing, the lastest is 1.6.

Install Java[/b]Download it to a location in your computer and click save. When your browser finishes sucking down java, execute the file.

[b]Insstalling Tomcat

You have got java to develop web application you had need more tools, one of them is Tomcat is an open source servlet container. In java world web container is reponsible for receiving web requests and passing it java web application.

Point your browser here to download Tomcat As of this writing the latest version is 6.0. You can download the binary or zip format. Extract or double click on the download file depending the package download. Install it and make sure you choose port 80 when asked.

Configure the environment

Your tomcat is usually called CATALINA_HOME, which is C:\apache\Tomcat. Your Java is called JAVA_HOME, which is C:\Program Files\Java\jdk1.6.0

CLASSPATH is used to help Java

Re: JSP Web Development by sbucareer(f): 1:42pm On Mar 15, 2007
[size=16pt]Starting web Programming[/size]



Installing the Software

The first step in writing any software is installing the necessary software and libraries.

Installing Java

You would need the Java Software Development Kit (JSDK). Recently Sun Microsystems has changed it name to Java 2 Second Edition (J2SE). Technically there are both the same thing. It contains all the API's required to develop Java softwar. Although Java is an open source, some communities have adapted their own API's and jar it up and add it into their classpath for the JVM to see it.

Download point your browser to sun microsystems. You would be looking for the lastest version of the Java 2 SDK, standard Edition, disregarding any beta version that may be available. As of this writing, the lastest is 1.6.

Install Java[/b]Download it to a location in your computer and click save. When your browser finishes sucking down java, execute the file.

[b]Insstalling Tomcat

You have got java to develop web application you had need more tools, one of them is Tomcat is an open source servlet container. In java world web container is reponsible for receiving web requests and passing it java web application.

Point your browser here to download Tomcat As of this writing the latest version is 6.0. You can download the binary or zip format. Extract or double click on the download file depending the package download. Install it and make sure you choose port 80 when asked.

Configure the environment

Your tomcat is usually called CATALINA_HOME, which is C:\Program Files\Apache Software Foundation\Tomcat 6.0. Your Java is called JAVA_HOME, which is C:\Program Files\Java\jdk1.6.0

CLASSPATH is used to help Java software find extra bits of program code. It contains a list of places to look, seperated by semicolon (wink We have to tell our OS to look for additional jar file like servlet.jar in the C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib

Re: JSP Web Development by sbucareer(f): 1:43pm On Mar 15, 2007
This is the visual of tomcat Window Installer.

Re: JSP Web Development by Taysay(m): 5:26pm On Mar 15, 2007
@Sbucareer,
Good day How is the going? I just want to say a big thank you for the speedy reply and of cos for jump starting our J2ee class. I have already done all my configurations, I have installed my jdk 1.5 I had wanted to upgrade to 1.6 but then I needed to have windows xp service pack 2 or later, and since my windows is legit I didnt want to upgrade with a clone so I let it be for the moment. At the moment I have my Jboss, netbeans, micromedia suite (dreamweaver, flash, fire works ) all configured and running. So do you mind if we get started from this point? waiting to hear from you soon as usual, Bye have a good one. Tanx
Re: JSP Web Development by Taysay(m): 5:37pm On Mar 15, 2007
@Sbucareer,
Pls do you have a soft copy of the reference material I believe it was published by wrox. I will love to have a copy. Tanx plenti
Re: JSP Web Development by sbucareer(f): 8:11pm On Mar 15, 2007

Although the trail is a based on a text reference by wrox most and all the work are independent knowledge by sbucareer.

Taysay you can download the codes and contents or check any Errata  from [url=http://www.wrox.com/WileyCDA/WroxTitle/productCd-076457485X,descCd-tableOfContents.html]Beginning Web Dewvelopment[/url]

You can follow the trails with any preferred servlet container and integration tool, but no support will be rendered if you run into issues during the trail. Follow recommended softwares and tools above.
Re: JSP Web Development by Taysay(m): 8:07am On Mar 16, 2007
@ Sbucareer,
Good day, tanx you so very much for the link, I am in the process of down loading just that since I browse at a cafe, with horrible systems, insufficient band width and epileptic power supply. It might take longer than neccessary, but then I am on it, I just want to know if the down load contains the entire E-book cos I will love to have a copy of the text. Thank you. Have a good one
Re: JSP Web Development by sbucareer(f): 11:11am On Mar 16, 2007

Once you have installed Java and Tomcat and configure the environment like above you should see this page if you type http://localhost or http://127.0.0.1 in your browser

Re: JSP Web Development by sbucareer(f): 11:23am On Mar 16, 2007

So your paths should look like this


JAVA

Varibale name: JAVA_HOME
Variable value: C:\Program Files\Java\jdk1.6.0


[B]Tomcat[/b]

Varibale name: CATALINA_HOME
Variable value: C:\Program Files\Apache Software Foundation\Tomcat 6.0

ClassPath

%CATALINA_HOME%\lib\servlet.jar

PATH
;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

Re: JSP Web Development by sbucareer(f): 12:00pm On Mar 16, 2007
[size=16pt]
Your First Web Application
[/size]

If all goes well, we should be able to write our first web application. For those advanced web developer following this trail you can install and configure ant, download the lastest version excluding beta versions.

Your servlet container is install in this directory C:\Program Files\Apache Software Foundation\Tomcat 6.0. When you go into this directory you will find a sub directory called webapps short for web applications. This is where all your web application should go.

Inside this sub-directory is another sub-directory called ROOT. Here is where you will save all your files for this tutorial. For advanced web developers you can use ant script to deploy your war files.

Newbies, don't worry too much about ant script it would be covered later in this trail when you have got the hang of the servlet container.

Now, create a HTML called HelloWorld.jsp and save it in here C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT

<HTML>
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD>

<BODY>
<CENTER>Hello World!</CENTER>
<P/>
<CENTER>The time is <%= new java.util.Date() %></CENTER>


</BODY>
</HTML>

To run this test, type http://localhost/HelloWorld.jsp in your browser. Your result should look like this
Re: JSP Web Development by sbucareer(f): 5:46pm On Mar 16, 2007
[size=20pt]
Brief history of Java and the web
[/size]
I am not going to bore you with my own version of stories, just visit the links below to get an insight of the history of the Internet.

1. Web history

2. How the web works

3. CGI

4. CGI Alternatives

5. [url=http://www.scit.wlv.ac.uk/~jphb/sst/jsp/intro.html]How JSP works[/url]

6. What is JavaScript

Re: JSP Web Development by sbucareer(f): 6:38pm On Mar 16, 2007
[size=20pt]
Storing Data and Performing Calculations
[/size]
Variable name

A variable is a name given to a place in computer memory. It is a temporary location in the computer memory that allows you to perform some routine or calculation with it. It is volatile in the sense that if the computer is switched off the content of the variable would be lost forever.

This pose some serious issues as we would want to read our emails the next day after, which the computer might have been switched off. To solve this issue computer scientist came up with ideas to persist variable contents into a software called database. Dataase is out of the scope of this trial, but it is a software that can hold information for a long time even after the computer has been switched off.

This is handy particularly for web developers who want to develop application that could be interactive with users. Web page falls into two categories:

1. Static

2. Dynamic

We would not be learning JSP if we where only interested in static pages. They are pages that is hard coded into the HTML. Dynamic is personalized and do not have a fixed view, it depends on your request the site would fetch the appropriate age for you.

Let look at variables.

In java we have eight types of primitive data type namely:

1. int
2. char
3. boolean
4. byte
5. double
6. float
7. short
8. long

For now, this is all you need to know. We have the Object version of these primitive data types, namely:

1. Integer
2. Character
3. Boolean
4. Byte
5. Double
6. Float
7. Short
8. Long

Did you noticed the difference? You should, because your are a clever learner. Java adds another type of Object to it collection of primitive Object  data type called String

To create a variable, you just choose one of the primitive type that perfectly describe your data type. Say for example you are modelling a shoping cart for the web application. You'd known straight away that you would need

int totalPrice = £100

Now we use primitive data type int to represent a location in the memory call totalPrice. Anytime we want to access the total price of our client all we need is to call the variable totalPrice and it would tell us how much is in the cart.

We do not need to know how much is in the cart, by calling the variable totalPrice, it will reveal to us the total price of their shopping so we can bill them by credit card or other means.

Re: JSP Web Development by segebee(m): 6:38pm On Mar 16, 2007
nice work, keep it up
Re: JSP Web Development by sbucareer(f): 7:17pm On Mar 16, 2007
[size=20pt]
Scriplet Elements
[/size]
Comment
In any programming langauge, it is important you learn the syntax for commenting your codes, not only it is a good practice but it would help that poor guy understand your code when you have become like Bill Gates and left the company.

The worst thing you can ever do as a programmer is to try and learn another programmer's code. It is like try to learn how his brain works. But these could even be made simpler if the code was commented and well documented.

In JSP to comment code we use this tag

<%--This is a comment and will be stripped out. --%>

You can also use the normal Java comments within JSP scriplet i.e.

<%
    //Single line comment
   /*
     This is a
     multiple
     line
     comment
   */
%>


Declarations
Declarations are used to define variables and methods for use in subsequent scriplets and expressions or other declarations. The syntax of a declaration is

<%! JavaDeclaration %>

Example

<%!
     int totalPrice = 100;
%>

We can also define method for our use, example

<%!
        int calculateTotalPrice(int price, int qty){
        int toReturn = price * qty;
        return toReturn;
       }
%>

Expression
We have meet expression before when we wrote our first HTML that prints out the date and time. Expression is when you want the output to be included in the standard output, example

<%= new java.util.Date()%>

Another example is if we want to print totalPrice variable to the standard output, we do

<%=totalPrice%>

Scriptlet
Scripptlet is where you include all jsp code to be executed by the servlet container, i.e.

<%
JavaCode


%>

Re: JSP Web Development by sbucareer(f): 7:43pm On Mar 16, 2007
[size=20pt]
Open your editor and type the following code
[/size]

<% -- Varible Declaration --%>
<%! double loanAmount; %>
<%! double interestRate; %>
<%! int numYears; %>

<%-- Method Declaration --%>

<%!
     double calculateInterest( double loan,
                                double interestRate,
                                int numYears        ){
          return numYears * interestRate * loan / 100;
      }

double loanRepayments(double loan,
double interestRate,
int numYears){
return ( calculateInterest(loan, interestRate, numYears) + loan ) / (numYears *12);
}
%>



<html>
<head>
<title>Loan calculation</title>
</head>
<body>
<h2>Loan Calculation</h2>

<%
    loaAmount = 6400;
    interestRate = 40.9; //Too expensive
    numYears = 4;
%>

Loan Amount:  <%=loanAmount%>
<br/>
Interest Rate: <%=interestRate%>
<br/>

*****************************
<br/>
Number of years: <%=numYears%>
<br/>
Total interest: <%=calculateInterest(loanAmount,
                                    interestRate,
                                    numYears)%>
<br/>
******************************
<br/>
Monthly repayments: <%= loanRepayments(loanAmount,
interestRate,
numYears)%>
<br/>

<%-- Change the value of years--%>
<%numYears++;%>

*****************************
<br/>
Number of years: <%=numYears%>
<br/>
Total interest: <%=calculateInterest(loanAmount,
                                       interestRate,
                                       numYears)%>
<br/>

******************************
<br/>
Monthly repayments: <%= loanRepayments(loanAmount,
interestRate,
numYears)%>
</body>
</html>

Save the file as interestRate.jsp. This is how it should look. There is a problem with the JSP, let see if you can resolve it yourself.
Re: JSP Web Development by sbucareer(f): 8:56pm On Mar 16, 2007

Good coding Paractice
So far, what we have seen is a very relatively simple JSP code. If you got your code to work, you are a top geeza! As this is a simpel JSP you can easily follow what is going on in there, and you can modify it to suit your needs.

You can add more methods to reflect your needs. As time goes on you would inevitably create larger and more complex JSP. As that time comes you would be introduce to framework to help reduce the load of maintaining all the JSP codes and probably help with the separation of concern.

If you do not follow a good coding practice it would be difficult to maintain your file and JSP code.
Re: JSP Web Development by sbucareer(f): 8:58pm On Mar 16, 2007
[size=20pt]
Getting data from the browser
[/size]
We are going to look at how to make web application interactive by providing forms into which the client can enter data.

We will be introducing and using various HTML controls, like

1. Radio buttons
2. Checkboxes
3. Select controls and submit and rest buttons.

These are HTML controls. If you have never used before you must visit W3C and look at HTML controls. If you can to capture data from the client and send it to the server, the method usually employed to achieve this is to ask the user to fill in an HTML form, on completion of the form, a submit button will need to clicked, to initiate a request (transfer of data to server)

Form is of thhis form <form>. Form has attributes that are vital to proper and smooth delivery of data. Other Form attributes are:

1. action attribute
2.  name attribute
3. method attribute
4. target attribute

The most important attributes for this trail would be the action, name and method. Lets look at action attribute.

Action attribute is use to specify the page to move to when the submit button is clicked. We need to specify the servlet-side resource. It could be a JSP file or Servlet file.

Method is very interesting, it allows us to specify how to send the data. Usually we have two known methods

1. POST
2. GET

The two are similiar in their functionality but different in operation. GET is considered insecure because it uses pair=value with a clear text in your browser URL i.e http://localhost/login?authen=password=password+username=sbucareer.

If someone has a sniffer listening to that URL he would not find it very difficult to capture your username and password But the POST use more clever way by encryting the pair=value i.e http://localhost/login?authen=password=/?'$5yh@@@@+username=@@'?.x""@jkk

Although, POST is not very strong encrypted someone with a good software can decode the detail. To secure how you transmit data to servlet-side you can use SSL encryption software see VeriSign

Name attribute is a way to identify the form that is sending data to servlet-side. We may have many forms in one page so server side need to know the form sending data.

Re: JSP Web Development by sbucareer(f): 10:33pm On Mar 16, 2007

Let create a simple form and send it to server for processing

<html>
<head>
<title>Order Pizza</title>
</head>

<body>
<center><h1>Order Pizza</h1></center>



<form name="pizza" action="process.jsp" method="POST">

<table border="0">
<tr>
<td><b>Name:</b></td>
<td><input type="text" name="name" size="25"></td></br>
</tr><tr>

<td><b>Address:</b></td>
<td><input type="text" name="address" size="30"></td></br>
</tr><tr>

<td><input type="radio" name="purchaseType" value="Home Delivery"></td>
<td><b>Home Delivery</b></td></tr>

<tr>
<td><input type="radio" name="purchaseType" value="Take Away"></td>
<td><b>Take Away</b></td></tr>

<tr>
<td><b>Select your pizza(s), </b></td>
</tr>

<tr>
<td><input type="checkbox" name="pepperoni" value="Yes"></td>
<td><b>Pepperoni</b></td></tr>
<br/>

<tr>
<td><input type="checkbox" name=hawaiian value="Yes"></td>
<td><b>Hawaiian</b></td></tr>


<tr>
<td><input type="checkbox" name="margherita" value="Yes"></td>
<td><b>Margherita</b></td></tr>

<tr>
<td><input type="submit" value="Place Order"></td></tr></table>
</form>

</body>
</htmL>

Save this file as pizza.jsp. When you open http://localhost/pizza.jsp it should look like this
Re: JSP Web Development by sbucareer(f): 11:48pm On Mar 16, 2007

Creating HTML forms is just one side of the story. Now that we have created HTML form, when a user click the place order button, the data is retrieved to the backend for processing and we have said in the form action that the server side script would be called process.jsp

Now, we are going to create server-side script called process.jsp. Note that JSP is not really a backend component in the sense that JSP Page are use for visual display, front-end. A really backend component is a servlet script.

Ok, let code the process.jsp

<html>
<head>
<title>Process.jsp</title>
</head>

<body>
<b>Name</b>
<% out.println(request.getParameter("name"wink); %>

<br/>
<b>Address</b>
<% out.println(request.getParameter("address"wink); %>

<br/>
<b>Delivery</b>
<% out.println(request.getParameter("purchaseType"wink); %>

<br/>
<b>Pepperoni</b>
<% out.println(request.getParameter("pepperoni"wink); %>

<br/>
<b>Margherita</b>
<% out.println(request.getParameter("margherita"wink); %>

<br/>
<b>Hawaiian</b>
<% out.println(request.getParameter("hawaiian"wink); %>

<br/>
</body>
</html>

Save the file as process.jsp. Run the http://87.194.38.96/pizza.jsp and fill it and click the submit button.
Re: JSP Web Development by sbucareer(f): 12:12am On Mar 17, 2007

Request object is a Servlet API. The actuall Interface is ServletRequest. The container authomatically initializes the container into Servlet Objects making it possible for you to call some methods without declaring it class.

Request is used by the client to request a resource from the server side and Response is used by the server to deliver request to the client. I am going to create a servlet class called Process.java that will do the same thing that the process.jsp did.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.ServletResponse;
import javax.servlet.*;
import java.io.*;
import java.util.*;

public class Process extend HttpSevlet{

 private String name;
 private String address;
 private String purchaseType;
 private String margherita;
 private String hawaiian;
 private String pepperoni;

 public void doGet(
HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
      response.setContentType("text/html"wink;

       PrintWriter out = response.getWriter();
       name = request.getParameter("name"wink;
       //do the rest

}//End doGet

public void doPost(
HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
 doGet(request, response);
}//End doPost

}//End Process

You would need to save this file in this directory C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\classes

Last we need to tell the container where to look for it in web.xml configuration file i.e.



<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">

  <display-name>Pizza Order</display-name>
  <description>
     Welcome of Pizza Order  </description>

</web-app>
<servlet>
   <servlet-class>Process</servlet-class>
   <servlet-name>Process</servlet-name>
</servlet>

<servlet-mapping>
  <servlet-name>Process</servlet-name>
  <url-pattern>/engine.exe</url-pattern>
</servlet-mapping>

This file is in C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\web.xml.

Now in your HTML file you modify the section to

<form action="/engine.exe" method="POST" name="pizza">

Re: JSP Web Development by Taysay(m): 1:42pm On Mar 17, 2007
@Sbucareer,
Goodday I think the error in the Jsp is from the monthly repayments,which returns more than 1 decimals place unlike the others. This make the accuracy of our answers inconsistent.

Loan Calculation
Loan Amount: $6400.0
Interest Rate: 40.9%
*****************************
Number of years: 4
Total interest: $10470.4
******************************
Monthly repayments: $351.4666666666667
*****************************
Number of years: 5
Total interest: $13088.0
******************************
Monthly repayments: $324.8

waiting for your comments .thank you
Re: JSP Web Development by sbucareer(f): 7:16pm On Mar 18, 2007

Taysay use DecimalFormat API to correct that issue. ie.

<%-- Import Additional Java API's --%>
<%@ page language="java" import="java.text.*" %> //This tag is use to import java API's

<%-- Varible Declaration --%>
<%! double loanAmount; %>
<%! double interestRate; %>
<%! int numYears; %>
<%! DecimalFormat perc2; %>

<%-- Method Declaration --%>

<%!
      double calculateInterest( double loan,
                                 double interestRate,
                                 int numYears ){
           return numYears * interestRate * loan / 100;
       }

      String loanRepayments(double loan,
                                 double interestRate,
                                 int numYears){
           perc2 = new DecimalFormat("$#,##0.00;{$#,##0.00}"wink;
           return perc2.format(( calculateInterest(loan,interestRate,numYears) + loan )  / (numYears *12));
     }

%>

Next time I will not spoon feed you. If I make mistake don't correct me come up with your own version of solution(s), I need to learn from you too. Teacher do not always know everything, that shows that you are learning.

Re: JSP Web Development by sbucareer(f): 11:17pm On Mar 19, 2007

We have seen how to retrieve data from the browser to the backend server using HTML controls. Remember, for you to be able to retrieve data from the client (browser) you need to wrap it using forms control.

The submit button triggers the event and the action parameter within the form control consumes the request by the help of the specified JSP page or Servlet file.

Servlet was the first client script or front-end script introduced by Sun Microsystems. It soon became clear that coding client side with Servlet was very cumbersome. Below is example of Servlet that would do the same thing the interestRate.jsp did


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.ServletResponse;
import javax.servlet.*;
import java.io.*;
import java.util.*;

public class InterestRate extend HttpSevlet{

 

   private double loaAmount = 6400;
   private double interestRate = 40.9; //Too expensive
   private int numYears = 4;

  public void doGet(
HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
       response.setContentType("text/html"wink;

        PrintWriter out = response.getWriter();
       
out.println("<html>"wink;
out.println("<head>"wink;
out.println("<title>Loan calculation</title>"wink;
out.println("</head>"wink;
out.println("<body>"wink;
out.println("<h2>Loan Calculation</h2>"wink;

out.println("Loan Amount:"wink;  loanAmount;
out.println("<br/>"wink
out.println("Interest Rate:"wink; interestRate;
out.println("<br/>"wink;

out.println("*****************************"wink;
out.println("<br/>"wink;
out.println("Number of years:"wink; numYears;
out.println("<br/>"wink;
out.println("Total interest:"wink; calculateInterest(loanAmount,
                                     interestRate,
                                     numYears);
out.println("<br/>"wink;
out.println("******************************"wink;
out.println("<br/>"wink;
out.println("Monthly repayments:"wink; loanRepayments(loanAmount,
                                                          interestRate,
                                                          numYears);
out.println("<br/>"wink;

//Change the value of years
numYears++;

out.println("*****************************"wink;
out.println("<br/>"wink;
out.println("Number of years:"wink; numYears;
out.println("<br/>"wink;
out.println("Total interest:"wink; alculateInterest(loanAmount,
                                        interestRate,
                                        numYears);
out.println("<br/>"wink;

out.println("******************************"wink;
out.println("<br/>"wink;
out.println("Monthly repayments:"wink; loanRepayments(loanAmount,
                                                          interestRate,
                                                          numYears);
out.println("</body>"wink;
out.println("</html>"wink;


}//End doGet

public void doPost(
HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
  doGet(request, response);
}//End doPost

}//End Process


Save this file as interestRate.java in this directory C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\classes\InterestRate.java.

Compile it using javac from command line.If all goes well access the file like this http://localhost/servlet/interestRate

Make sure that you enable your servlet invoker from your container web.xml  i.e.


C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf\web.xml and look for this section



<!-- The "invoker" servlet, which executes anonymous servlet classes      -->
  <!-- that have not been defined in a web.xml file.  Traditionally, this   -->
  <!-- servlet is mapped to the URL pattern "/servlet/*", but you can map   -->
  <!-- it to other patterns as well.  The extra path info portion of such a -->
  <!-- request must be the fully qualified class name of a Java class that  -->
  <!-- implements Servlet (or extends HttpServlet), or the servlet name     -->
  <!-- of an existing servlet definition.     This servlet supports the     -->
  <!-- following initialization parameters (default values are in square    -->
  <!-- brackets):                                                           -->
  <!--                                                                      -->
  <!--   debug               Debugging detail level for messages logged     -->
  <!--                       by this servlet.  [0]                          -->

<!--
    <servlet>
        <servlet-name>invoker</servlet-name>
        <servlet-class>
          org.apache.catalina.servlets.InvokerServlet
        </servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
-->

Remove the comment tags surrounding servlet i.e.



<!-- The "invoker" servlet, which executes anonymous servlet classes      -->
  <!-- that have not been defined in a web.xml file.  Traditionally, this   -->
  <!-- servlet is mapped to the URL pattern "/servlet/*", but you can map   -->
  <!-- it to other patterns as well.  The extra path info portion of such a -->
  <!-- request must be the fully qualified class name of a Java class that  -->
  <!-- implements Servlet (or extends HttpServlet), or the servlet name     -->
  <!-- of an existing servlet definition.     This servlet supports the     -->
  <!-- following initialization parameters (default values are in square    -->
  <!-- brackets):                                                           -->
  <!--                                                                      -->
  <!--   debug               Debugging detail level for messages logged     -->
  <!--                       by this servlet.  [0]                          -->


    <servlet>
        <servlet-name>invoker</servlet-name>
        <servlet-class>
          org.apache.catalina.servlets.InvokerServlet
        </servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

Also look for this section and enable the sevlet


    <!-- The mapping for the invoker servlet -->
<!--remove this comment
    <servlet-mapping>
        <servlet-name>invoker</servlet-name>
        <url-pattern>/servlet/*</url-pattern>
    </servlet-mapping>
remove this comment-->


Restart you tomcat.
Re: JSP Web Development by sbucareer(f): 12:21am On Mar 20, 2007

The servlet above is erroneous, if you can get it to work you are my top star and you can post your code here. You have to write a method for calculation and monthlyRepayment below the InterestRate.java class.

The whole point was to emphasis the tedious job web developer phased when developing web application using servlet. JSP was the replacement of servlet. It promises less work and cleaner coding. Servlet was then adapted by developer as controller. It is used to listen to web tier and transfer control to bean or EJB for EIS communication.

We are going to write the same InterestRate solution above using servlet as a listener and use JSP for the client and persist out object in a bean.
Re: JSP Web Development by boloyoung(m): 8:47am On Mar 20, 2007
pls, can u send me ebooks for JSP and Servlets, and software for apache tomcat. i will be very grateful. thanks grin
Re: JSP Web Development by Taysay(m): 10:55am On Mar 20, 2007
@Sbucareer,
Good day pls this is what I made out of the earlire post , as regards the order pizza.jsp and process.jsp.
I will work on the servlet and get back to you, have a goog one.

Re: JSP Web Development by Taysay(m): 11:00am On Mar 20, 2007
@ Sbucareer,
Sorry I mistakenly attched the same file twice, so this is that for the order Akara.jsp tanx have a good one.

Re: JSP Web Development by sbucareer(f): 3:10pm On Mar 20, 2007

Taysay, thank you for your efforts and contributions to the post. You make me to have courage to continue. If you run into problems [email=valentine.obih@gmail.com?sbuject=JSP+Web+Developement]email[/email] me and I would help you on one2one basis.

You are really catching up and I like learners like you, with your new found knowledge I hope one day you will make an impact in Nigeria IT sector and above all make a good living for yourself and family.

However, to continue with the trail, I would like you to try the servlet part of the Akara.java etc. Remember to code the web.xml file.

When I see your answer, then we will continue with the making of servlet as a single controller that listens to request and forward/relay messages to other resources.
Re: JSP Web Development by Taysay(m): 3:58pm On Mar 20, 2007
@Sbucareer,
Thanx Mr lecturer for that word of encouragement, I am on the assignment, the bad news is that I sold my laptop and Iam yet to replace it so I usually come to the cafe with a storage device, download stuff go home work on it before coming to post. So this kind of kills my speed /drive. Well thank God my spirit and passion is tampered with. I really Appreciate your invaluable concern, I hope to be like you some day soon so that I can pass on to the needy the much needed knowledge.
Have a good one.
Re: JSP Web Development by sbucareer(f): 11:04am On Mar 21, 2007
[size=24pt]
Introduction to JavaBean
[/size]

Java bean is a reusable component that can be used in any Java application development environment. JavaBeans are dropped into an application container like tomcat, such as a form, and can perform functions ranging from a simple animation to complex calculations like our calculateInterest function and monthlyRepayment.

The good thing about JavaBeans is that they are pure POJO's (Plain Old Java Object). It is interesting for a java programmer to appreciate POJO's. It is not only immune you from dependent container and necessity for building and compilation, it allows you to write JavaBean independently, compile them and drop it where the container can see it.

EJB (Enterprise JavaBean) is the predecessor of JavaBean. EJB is out of the scope of this trail but if you want to understand EJB visit sun and follow J2EE trails.

EJB and JavaBean somewhat differs in architecture and operations. Javabean can NEVER be accessed from remote location. It can not be downloaded into a machine or outside its codebase. JavaBean cannot modify or change any file system operation and many more. With these limitations EJB was introduced to address these issues. All the negated issues of JavaBean, EJB was introduce to combat them. Most importantly JavaBean can only work on one JVM.

If we are interested in writing a simple application, say collect all the data from a form and save it to some sort of storage form JavaBean is the answer.

Re: JSP Web Development by sbucareer(f): 11:18am On Mar 21, 2007

Lets take an example of a JavaBean. Note, all JavaBean or persistent object most somehow extend serializable interface.

We are going to continue our trail with the Pizza example. So, let create a Pizza JavaBean and access it from the HTML (Front-end)

import java.io.Serializable;

public class Pizza implements Serializable{

private String margherita = "margherita";
private String name;
private String address;
private String hawaiia = "Hawaiia";
private String pepperoni = "Pepperoni";
private String[] purchaseType = {"Take Away", "Home Delivery"};

public Pizza (){}// Default constructor

public void setMargherita      ( String margherita ){this.margherita = margherita;}
public void setName              ( String name){this.name = name;}
public void setAddress          ( String address){this.address = address;}
public void setHawaiia          ( String hawaiia){this.hawaiia = hawaiia;}
public void setPepperoni       ( String pepperoni){this.pepperoni = pepperoni;}
public void setPurchaseType ( String[] purchaseType ){this.purchaseType = purchaseType;}

public String getMargherita ( ){return margherita ;}
public String getName ( ){return nname;}
public String getAddress ( ){return address;}
public String getHawaiia ( ){return hawaiia;}
public String getPepperoni ( ){return pepperoni;}
public String[] getPurchaseType ( ){return purchaseType;}
}//End Pizza class



The HTML code for the above bean.

<%@ page contentType="text/html"%>
<%@ page import="Pizza"%>

<HTML>
<HEAD>
<TITLE>Pizza Bean</TITLE>
</HEAD>
<BODY>
   <jsp:useBean id="pizza" class="Pizza" scope="page"/>

</BODY>
</HTML>

Note, if you where using directories i.e. com.nairaland.beans, your class would look like this. Remember you MUST save this bean in tomcat container under this directories C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\classes\com\nairaland\beans You do NOT need to define any bean class in the web.xml as this is not a servlet class


package com.nairaland.beans;

import java.io.Serializable;

public class Pizza implements Serializable{

private String margherita = "margherita";
private String name;
private String address;
private String hawaiia = "Hawaiia";
private String pepperoni = "Pepperoni";
private String[] purchaseType = {"Take Away", "Home Delivery"};

public Pizza (){}// Default constructor

public void setMargherita      ( String margherita ){this.margherita = margherita;}
public void setName              ( String name){this.name = name;}
public void setAddress          ( String address){this.address = address;}
public void setHawaiia          ( String hawaiia){this.hawaiia = hawaiia;}
public void setPepperoni       ( String pepperoni){this.pepperoni = pepperoni;}
public void setPurchaseType ( String[] purchaseType ){this.purchaseType = purchaseType;}

public String getMargherita ( ){return margherita ;}
public String getName ( ){return nname;}
public String getAddress ( ){return address;}
public String getHawaiia ( ){return hawaiia;}
public String getPepperoni ( ){return pepperoni;}
public String[] getPurchaseType ( ){return purchaseType;}
}//End Pizza class



And your HTML file would look like this

<%@ page contentType="text/html"%>
<%@ page import="com.nairaland.beans.Pizza"%>

<HTML>
<HEAD>
<TITLE>Pizza Bean</TITLE>
</HEAD>
<BODY>
   <jsp:useBean id="pizza" class="com.nairaland.beans.Pizza" scope="page"/>

</BODY>
</HTML>

(1) (2) (Reply)

Retrieving/selecting A Particular Number Of Random Rows From A Database Table / Differences Between Testing And Debugging In Programming Of Software Application / 10 Greatest Computer Programmers In History

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2020 Oluwaseun Osewa. All rights reserved. See How To Advertise. 349
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.