Professional Documents
Culture Documents
Can be created and stored in web Can NOT be created and stored in web
server in advance as HTML file. server in advance as HTML file.
Static page does not change with user Dynamic page changes as per the user
and/or time. and/or time.
For delivery of static page, all we For delivery of dynamic page, apart
require at server side, HTML files in from Web Server, we require program
Web Server. to generate dynamic content.
The software component that runs the server side program to generate
the dynamic content is known as the Web Container
Generation of Dynamic Pages
Web Server
4. Compose HTML
output
Applets Servlets
Applets are applications Servlets are Java based
designed to be transmitted analog to CGI programs,
over the network and executed implemented by means of
by Java compatible web servlet container associated
browsers. with an HTTP server.
An Applet is a client side java Servlet is a server side
program that runs within a component which runs on
Web browser on the client the web server.
machine. The servlet does not have a
An applet can use the user user interface.
interface classes like AWT or Servlet Methods: doGet(),
Swing. doPost()
Applet Life Cycle Methods:
Example of servlet code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Hello
WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" +
"</BODY></HTML>"); } }
Output
<form action="login" method="post">
<table>
<tr>
<td><font face="verdana" size="2px">Name:</font></td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td><font face="verdana
size="2px">Password:</font></td>
<td><input type="password" name="userPassword"></td>
</tr>
</table>
<input type="submit" value="Login">
</form>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
String user=req.getParameter("userName");
String pass=req.getParameter("userPassword");
if(user.equals("java4s")&&pass.equals("java4s"))
pw.println("Login Success...!");
else
pw.println("Login Failed...!");
pw.close();
JSP
JSP
Bits of Java code embedded in HTML
Suitable for coding the presentation layer of an
enterprise application
Created and maintained by web designers
JSP
Internally, the JSP Container converts the JSP
into a Servlet when a user requests for a JSP for
the first time
This Servlet would produce the output that the JSP
file is supposed to produce
Equivalent
Servlet
JSPContainer (Tomcat)
JSP .java file
JSP Scriptlet tag (Scripting elements)
JSP comments tag
JSP Comments
JSP comment marks text or statements that the JSP
container should ignore. A JSP comment is useful
when you want to hide or "comment out" part of
your JSP page.
<%-- This is JSP comment --%>
Html comments
An HTML comment. Ignored by the browser.
<!-- comment -->
JSP directives tag
The jsp directives are messages that tells
the web container how to translate a JSP page
into the corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive
<html> JSP page directive
<body>
</body>
</html>
<html> Jsp Include Directive
<body>
</body>
</html>
<html>
<body> JSP Taglib directive
<mytag:currentDate/>
</body>
JSP Declaration Tag
The JSP declaration tag is used to declare fields
and methods.
<%!fieldormethoddeclaration%>
<html>
<html> <body>
<body> <%!
<%! int data=50; %> int cube(int n){
<%= "Value of the variable is:"+data %> return n*n*n*;
</body> }
</html> %>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
index.html welcome.jsp
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String
<input type="submit" name=request.getParameter("uname");
value="go"><br/> out.print(Welcome "+name);
</form> %>
</body> </form>
</html> </body>
</html>
JSP expression tag
The code placed within JSP expression tag
is written to the output stream of the
response. So you need not write out.print() to
write data. It is mainly used to print the values
of variable or method.
<%=statement%>
JSP expression tag
index.html welcome.jsp
<html>
<html> <body>
<body> <%= "Welcome
<form action="welcome.jsp"> "+request.getParameter("uname") %>
<input type="text" name="uname"><b
r/> </body>
<input type="submit" value="go"> </html>
</form>
</body>
</html>
Java Beans
JavaBean is a Java class that is mainly
responsible for holding on to some data without a
large degree of functionality built into the class.
A Java Bean is a java class that should follow
following conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of
the properties, known as getter and setter methods.
JavaBeans Properties
A JavaBean property is a named attribute that can be
accessed by the user of the object. The attribute can
be of any Java data type, including classes that you
define.
A JavaBean property may be read, write, read only, or
write only. JavaBean properties are accessed through
two methods in the JavaBean's implementation class
A read-only attribute will have only a
getPropertyName() method, and a write-only
attribute will have only a setPropertyName()
method.
Why use Java Bean?
According to Java white paper, it is a reusable software
component. A bean encapsulates many objects into one object,
so we can access this object from multiple places. Moreover, it
provides the easy maintenance.
JavaBeans example
public class StudentsBean implements public int getAge(){
java.io.Serializable return age;
{ }
private String firstName = null; public void setFirstName(String
firstName){
private String lastName = null; this.firstName = firstName;
private int age = 0; }
public void setLastName(String
lastName){
public StudentsBean() { this.lastName = lastName;
} }
public String getFirstName(){ public void setAge(Integer age){
this.age = age;
return firstName;
}
} }
public String getLastName(){
return lastName;
JavaBeans example
<html>
<head> <p>Student First Name:
<jsp:getProperty name="students"
<title>get and set properties Example</title>
property="firstName"/>
</head> </p>
<body> <p>Student Last Name:
<jsp:getProperty name="students"
<jsp:useBean id="students" property="lastName"/>
class="StudentsBean"> </p>
<p>Student Age:
<jsp:setProperty name="students"
<jsp:getProperty name="students"
property="firstName"
property="age"/>
value="Zara"/> </p>
<jsp:setProperty name="students"
property="lastName" </body>
</html>
value="Ali"/>
<jsp:setProperty name="students"
property="age"
value="10"/>
</jsp:useBean>
A Simple JSP
<!-- CurrentTime.jsp -->
<HTML>
<HEAD>
<TITLE>
CurrentTime
</TITLE>
</HEAD>
<BODY>
Current time is <%= new java.util.Date() %>
</BODY>
</HTML>
<!-- ComputeLoan.html --> Example 35.2
<html> Computing Loan
<head>
<title>ComputeLoan</title>
Write an HTML page that prompts
</head>
the user to enter loan amount,
<body> annual interest rate, and number of
Compute Loan Payment years. Clicking the Compute Loan
Payment button invokes a JSP to
<form method="get" compute and display the monthly
and total loan payment.
action="http://localhost:8080/examples/jsp/ComputeLoan.jsp">
<p>Loan Amount
<input type="text" name="loanAmount"><br>
Annual Interest Rate
<input type="text" name="annualInterestRate"><br>
Number of Years <input type="text" name="numberOfYears"
size="3"></p>
<p><input type="submit" name="Submit" value="Compute Loan
Payment">
<input type="reset" value="Reset"></p>
</form>
</body>
<!-- ComputeLoan.jsp -->
<html>
<head>
<title>ComputeLoan</title>
</head> Predefined variable
<body>
<% double loanAmount = Double.parseDouble(
request.getParameter("loanAmount"));
double annualInterestRate = Double.parseDouble(
request.getParameter("annualInterestRate"));
double numberOfYears = Integer.parseInt(
request.getParameter("numberOfYears"));
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate /
(1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12; %>
Loan Amount: <%= loanAmount %><br>
Annual Interest Rate: <%= annualInterestRate %><br>
Number of Years: <%= numberOfYears %><br>
<b>Monthly Payment: <%= monthlyPayment %><br>
Total Payment: <%= totalPayment %><br></b>
</body>
</html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
<form action="reg.jsp" method="post">
</form>
</body>
</html>
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String user=request.getParameter("userid"); JSP to database
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost/login","root","");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values
('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"')");
if(i>0)
{
%>
You are successfully registered..Click <a href="Login.html"> Here </a> to login
<%
}
%>
</body>