Transcript HTML

JSP
Presented by
K.Venkata Ratnam
HOD MCA (Dept)
Newton’s Institute of Engineering
JSP: Java Server Page
JSP helps in generating dynamic content, based on user input,
time of day, or any other runtime conditions.
Web application: a program on the server processes requests
and generates response.
Problems with servlets:
1. Detailed Java programming knowledge is needed.
2. To change the look and feel, change the servlet code and
recompile.
3. Restart the server and run the servlet program
Hello world servlet
public class HelloWorldServlet implements Servlet{
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
PrintWriter out=response.getWriter();
out.println(“<html>”);
out.println(“ <head>”);
out.println (“<title>Hello world</title>”);
out.println(“ </head>”);
out.println(“ <body>”);
out.println(“ <h1>Hello World<\h1>”);
out.println(“ It's ”+ (new java.util.date().toString()) + “and all is well”);
out.println(“ </body>”);
out.println(“</html>”);
}
}
Hello world JSP Page
<html>
<head>
<title>Hello world
<\title>
</head>
<body>
<h1>Hello World<\h1>
It,s <%= new java.util.date().toString() %>
and all is well.
</body>
</html>
What is JSP?
Mostly HTML page, with extension .jsp
Include JSP tags to enable dynamic
content creation
Translation: JSP → Servlet class
Compiled at Request time
(first request, a little slow)
Execution: Request → JSP Servlet's
service method
Anatomy of a JSP Page
A JSP page is a regular web page with JSP
elements for generating the parts of the page
that differ for each request.
JSP separates the request processing and the
business logic code from the presentation.
In servlet, HTML is embedded,
here JSP elements are added to genearate
the dynamic content.
Life Cycle
A JSP page is translated into a Java
Servlet
And then compiled
On Tomcat, the compilation happens the
first time a page is requested
Above three requests are processed in
first request
Afterwards, just as fast as a Servlet
(because it is then a servlet)
Hello World
<html>
<head> <title> Hello JSP </title> </head>
<body>
<p> Hello World:
<%= new java.util.Date() %>
</p>
</body>
</html>
See also: Date_jsp.java – the Servlet this page is
translated to
Date_jsp.java (extract)
This extract shows the part that produces the output – compare it
with the JSP:
out = pageContext.getOut();
_jspx_out = out;
out.write("<html>\r\n");
out.write("<head> ");
out.write("<title> Hello JSP ");
out.write("</title> ");
out.write("</head>\r\n");
out.write("<body> \r\n");
out.write("<p> Hello World:\r\n
");
out.print( new java.util.Date() );
out.write("\r\n");
out.write("</p>\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");
Produced
JSP scripting elements
<%= expression %>
The expression is evaluated and the result is
inserted into the HTML page
<% code %>
The code is inserted into the servlet's service method
This construction is called a scriptlet
<%! declarations %>
The declarations are inserted into the servlet class,
not into a method
Used to declare variables and methods
Example for Expression
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Note:
The <%= ... %> tag is used, because we are
computing a value and inserting it into the HTML
The fully qualified name (java.util.Date) is used,
instead of the short name (Date)
Scriptlets:
It is difficult to do much programming just by putting Java expressions inside
HTML.
JSP also allows you to write blocks of Java code inside the JSP, by placing
your Java code between <% and %> characters (without the = sign at the start
of the sequence.)
This block of code is known as a "scriptlet". A scriptlet contains
Java code that is executed every time the JSP is invoked.
<HTML>
<BODY>
<%
// This is a scriptlet. Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>
Mixing Scriptlets and HTML
<HTML>
<BODY>
<TABLE BORDER=2>
<%
int n=5;
for ( int i = 0; i < n; i++ ) {
%>
<TR>
<TD>Number</TD>
<TD><%= i+1 %></TD>
</TR>
<%
}
%>
</TABLE>
</BODY>
</HTML>
Example for Declarations
<HTML>
<HEAD>
<TITLE> Example for JSP Declarations </TITLE>
</HEAD>
<BODY bgcolor=green text=white>
<%! int x=4;%>
Square root of (x)=<%=Math.sqrt(x)%>
<%
for(int i=1;i<=10;i++)
{
out.print("Hello JSP World!<br>");
}
%>
<%! int mat(int x, int y)
{
return x*y;
}%>
<%
out.println("Multiplication of(x,y)=");
out.println(mat(3,4)+"<br>");
%>
</BODY>
</HTML>
Directives
Instructions to the compiler
Directives affect the servlet class itself
A directive has the form:
<%@ directive attribute="value" %>
The most useful directive is page, which lets
you import packages

Example: <%@ page import="java.util.*" %>
Example for page directive
<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
Date date = new Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>
The include directive
The include directive inserts another file into the file being
parsed
The included file is treated as just one more JSP, hence
it can include static HTML
Syntax: <%@ include file="URL " %>
The URL is treated as relative to the JSP page
If the URL begins with a slash, it is treated as relative to
the home directory of the Web server
The include directive is especially useful for inserting things
like navigation bars
The include directive is used to physically include the
contents of another file (compile-time).
Example:
<%@ include file="header.jsp" %>
Example for include directive
<HTML>
<BODY>
Going to include
time.jsp...<BR>
<%@ include file="time.jsp"
%>
</BODY>
</HTML>
Actions
Actions are XML-syntax tags used to control the servlet
engine
<jsp:include page="URL " flush="true" />
Inserts the indicated relative URL at execution time
(not at compile time, like the include directive does)
This is great for rapidly changing data
<jsp:forward page="URL" />
<jsp:forward page="<%= JavaExpression %>" />
Jump to the (static) URL or the (dynamically computed)
JavaExpression resulting in a URL
Example for <jsp:include>
<HTML>
<HEAD>
</HEAD>
<BODY>
<h1>Example for the <jsp:include></h1>
</BODY>
</HTML>
<jsp:include page="login.html"></jsp:include>
login.jsp
<HTML>
<HEAD> <TITLE>Login User Authentication </TITLE>
</HEAD>
<BODY bgcolor=maroon text=green>
<h2 align=center><font color=blue><i>User Login</i></font></h2>
<center>
<form name=f1 action=“http://localhost:8080/ITWEB/logincheck.jsp”
method="post">
<table border=1 borderstyle=rigid width=20% cellpadding=5 cellspacing=0
bordercolor=white>
<tr rowspan=0><td align=center>
<b>UserName </b>
:<input type="text" name="uname" size=20><br><br>
<b>Password </b>
:<input type="password" name="pwd" size=20><br><br>
<input type="submit" value="Login"></td></tr>
</table>
</form>
</center>
</BODY>
</HTML>
Variables
JSP provides several predefined variables
request : The HttpServletRequest parameter
response : The HttpServletResponse parameter
session : The HttpSession associated with the
request, or null if there is none
out : A JspWriter (like a PrintWriter) used to send
output to the client
Example:
Your hostname: <%= request.getRemoteHost() %>
Request and Response
Each JSP page has access to two special
objects
The Request object carries information passed
by the HTTP request (e.g. made by the browser)
This includes any submitted form data
The Response object is used to pass
information back to the Client (browser)
E.g. response.getWriter() provides an
output stream for direct writing to the client
Example for Request and Response
login.html
<HTML>
<HEAD>
<TITLE>Login User Authentication </TITLE>
</HEAD>
<BODY bgcolor=purple text=white>
<h2 align=center><font color=blue><i>User Login</i></font></h2>
<center>
<form name=“f1” action=“http://localhost:8080/itweb/logincheck.jsp" method="post">
<table border=1 bgcolor=green borderstyle=rigid width=20% cellpadding=5
cellspacing=0 bordercolor=white>
<tr><td align=center>
<b>UserName </b>
:<input type="text" name="uname" size=20><br><br>
<b>Password </b>
:<input type="password" name="pwd" size=20><br><br>
<input type="submit" value="Login"></td></tr>
</table>
</form>
</center>
</BODY>
</HTML>
logincheck.jsp
<HTML>
<HEAD><TITLE>Login User Authentication </TITLE>
</HEAD><BODY bgcolor=purple text=white>
<%
response.setContentType(“text/html”);
String name=request.getParameter(“uname”);
String pass=request.getParameter(“pwd”);
if(name==“venkat” && pass==“sneha”)
{
%>
<jsp:forward page=“welcome.html”></jsp:forward>
<%
}
else{
%>
<jsp:forward page=“login.html”></jsp:forward>
<% } %>
</body></html>
JSP to Servlet Communication Example
login.jsp
<HTML>
<HEAD> <TITLE>Login User Authentication </TITLE>
</HEAD>
<BODY bgcolor=“maroon” text=“green”>
<h2 align=center><font color=blue><i>User Login</i></font></h2>
<center>
<form name=f1 action=http://localhost:8080/ITWEB/LoginServlet”
method=“get">
<table border=1 borderstyle=rigid width=20% cellpadding=5 cellspacing=0
bordercolor=“white”>
<tr><td align=center>
<b>UserName </b>
:<input type="text" name="uname" size=20><br><br>
<b>Password </b>
:<input type="password" name="pwd" size=20><br><br>
<input type="submit" value="Login"></td></tr>
</table>
</form>
</center>
</BODY></HTML>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
out.println("<html>");
out.println("<body bgcolor=orange text=red>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1 align=center>Welcome Mr/Ms:"+name+“ to our website</h1>");
out.println("</body>");
out.println("</html>");
}
}
JDBC – Java Database Connectivity
•JDBC is used for accessing databases from Java applications
•Information is transferred from relations to objects and vice-versa
•databases optimized for searching/indexing
•objects optimized for engineering/flexibility
JDBC Architecture
We will
use this one…
Oracle
Driver
Oracle
Java
Application
JDBC
DB2
Driver
DB2
Network
MySQL
Driver
MySQL
Application
JDBC
Driver
•Java code calls JDBC library
•JDBC loads a driver
•Driver talks to a particular database
•An application can work with several databases by
using all corresponding drivers
•Ideal: can change database engines without changing
any application code (not always in practice)
Seven Steps
•Load the driver
•Define the connection URL
•Establish the connection
•Create a Statement object
•Execute a query using the Statement
•Process the result
•Close the connection
Loading the Driver
•We can register the driver indirectly using the statement
• Class.forName("oracle.jdbc.driver.OracleDriver");
•Class.forName loads the specified class
•When OracleDriver is loaded, it automatically
•creates an instance of itself
•registers this instance with the DriverManager
•Hence, the driver class can be given as an argument of
the application
An Example
// A driver for imaginary1
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// A driver for Oracle
Driver driver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(driver);
//A driver for MySQL
Class.forName("com.mysql.jdbc.Driver");
MS-Access
Oracle
Registered Drivers
MySQL
JDBC DRIVERS
Type 1 Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API.
Type 2 Driver
Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers
convert JDBC calls into database-specific calls i.e. this driver is specific to a
particular database. Ex: Oracle will have oracle native API.
Type 3 Driver
All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server.
The middle-tier then translates the request to the database. If the middle-tier server
can in turn use Type1, Type 2 or Type 4 drivers.
Type 4 Driver
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the
database server.
Get the user details from the Database
getusers.jsp
<%@page import="java.sql.*;"%>
<html>
<body bgcolor="#E2DA6D" text=darkblue>
<h1 align=center><font color=maroon><i>Department of IT</i></font></h1>
<h3 align=center ><font color=navy><u><i>Registered User
Details</I></u></font></h3>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:itweb");
PreparedStatement psmt =con.prepareStatement("select * from registration");
ResultSet rs=psmt.executeQuery();
out.println("<center>");
out.println("<table width=65% border=0 cellpadding=0 cellspacing=2
bgcolor=lightblue>");
out.println("<tr bgcolor=red><th>Name</th><th>Password</th>");
out.println("<th>Email ID</th><th>Phone No</th><th>Sex</th>");
out.println("<th>Date of Birth</th><th>Language</th> <th>Address</th>/tr>");
while(rs.next())
{
out.println("<tr bgcolor=pink><td align=center>");
out.println(rs.getString(1));
out.println("</td><td align=center>");
out.println(rs.getString(2));
out.println("</td><td align=center>");
out.println(rs.getString(3));
out.println("</td><td align=center>");
out.println(rs.getString(4));
out.println("</td><td align=center>");
out.println(rs.getString(5));
out.println("</td><td align=center>");
out.println(rs.getString(6));
out.println("</td><td align=center>");
out.println(rs.getString(7));
out.println("</td><td align=center>");
out.println(rs.getString(8));
out.println("</td></tr>");
}
out.println("</table>");
out.println("</center>");
%>
</body></html>
addcart.html
<HTML>
<HEAD>
<TITLE>Welcome to Amazon.com</TITLE>
</HEAD>
<BODY bgcolor=“darkblue" text="white">
<center>
<form name=“cart” action="http://localhost:8080/ITWEB/addcart.jsp" method="post">
<table border="0" cellspacing="10" width=50% cellpadding="20">
<caption><h1>Enter Book Details</h1></caption>
<tr><td>BookName:</td>
<td><input type=text name="bname" size=25></tr>
<tr><td>Price:</td>
<td><input type=text name="price" size=25></tr>
<tr><td>Quantity:</td>
<td><input type=text name="quant" size=25></tr>
<tr><td>Amount:</td>
<td><input type=text name="amt" size=25></tr>
<tr><td>&nbsp</td><td align=left><input type="submit" value="Add to cart"></td></tr>
</table>
</form>
</center>
</BODY>
</HTML>
addcart.jsp
<%@page import="java.sql.*;"%>
<html>
<body bgcolor="#E2DA6D" text="darkblue">
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:mca");
PreparedStatement psmt =con.prepareStatement("insert into books
values(?,?,?,?)");
String bname=request.getParameter("bname");
String price=request.getParameter("price");
String quantity=request.getParameter("quant");
String amount=request.getParameter("amt");
psmt.clearParameters();
psmt.setString(1,bname);
psmt.setString(2,price);
psmt.setString(3,quantity);
psmt.setString(4,amount);
psmt.executeUpdate();
out.println("Your Books are added to the Cart successfully");
%>
</body>
</html>
THANKQ TO ALL
For Any queries please contact:
K.VenkataRatnam MCA, M.Tech(CSE)
Assoc.Prof & HOD MCA
Email: [email protected]
Mobile:+91 9494470845