Transcript gvrjsp

What Is JavaServer Pages?
• JavaServer Pages is a technology for developing web pages that
include dynamic content.
• HTML page contains static content that always remains the same
• A JSP page can change its content based on any number of
variable items, including the identity of the user, the user's
browser type, information provided by the user, and selections
made by the user.
• JSP can be used to create web applications like shopping carts
and employee directories.
• A JSP page contains standard markup language elements, such
as HTML tags, just like a regular web page.
• JSP page also contains special JSP elements that allow the server
to insert dynamic content in the page
• JSP elements can be used for a wide variety of purposes,
such as retrieving information from a database or
registering user preferences.
• When a user asks for a JSP page, the server executes
the JSP elements, merges the results with the static
parts of the page, and sends the dynamically composed
page back to the browser
• JSP defines a number of standard elements useful for
any web application, such as accessing JavaBeans
components, passing control between pages, and
sharing information between requests, pages, and
users.
• Programmers can also extend the JSP syntax by
implementing application-specific elements that
perform tasks such as accessing databases and
Enterprise JavaBeans, sending email, and generating
HTML to present application-specific data.
• The combination of standard elements and custom
elements allows for the creation of powerful web
applications.
Dynamic Content With JSP
What is JSP Good For?
• Servlets allow us to easily:
– read data from user
– read HTTP request
– create cookies
– etc.
• It is not convenient to write long static HTML using
Servlets
– out.println("<h1>Bla Bla</h1>" + "bla bla bla bla bla "
+ " lots more here...")
5
JSP Idea
• Use HTML for most of the page
• Write Java code directly in the HTML page
(similar to Javascript)
• Automatically translate JSP to Servlet that
actually runs
6
Benefits of JSP over Servlets
• It is easier to write and maintain HTML.
• We can use standard website development tools.
• JSP’s are translated into servlets.
• Separation of Business Logic from Page Presentation
Relationships
• In servlets: HTML code is printed from java
code
• In JSP pages: Java code is embedded in HTML
code
Java
HTML
8
HTML
Java
JSP Life Cycle
.
2016-08-07
10
Embedding Elements in HTML Pages
<html>
<body bgcolor="white">
<% java.util.Date clock = new java.util.Date( ); %>
<% if (clock.getHours( ) < 12) { %>
<h1>Good morning!</h1>
<% } else if (clock.getHours( ) < 18) { %>
<h1>Good day!</h1>
<% } else { %>
<h1>Good evening!</h1>
<% } %>
Welcome to our site, open 24 hours a day.
</body>
</html>
For example, if the current time is 8:53 P.M., the resulting page sent from the server to the browser
looks like this:
<html>
<body bgcolor="white">
<h1>Good evening!</h1>
Welcome to our site, open 24 hours a day.
</body>
</html>
Integration with Enterprise Java APIs
JavaServer Pages is built on top of the Java Servlets API, JSP has
access to all of the powerful Enterprise Java APIs, including:
• JDBC
• Remote Method Invocation (RMI) and OMG CORBA support
• JNDI ( Java Naming and Directory Interface)
• Enterprise JavaBeans (EJB)
• JMS ( Java Message Service)
• JTA ( Java Transaction API)
• This means that you can easily integrate JavaServer Pages
with your existing Java Enterprise solutions
The JSP Advantage
• JSP supports both scripting and element-based dynamic content,
and allows programmers to develop custom tag libraries to satisfy
application-specific needs.
• JSP pages are precompiled for efficient server processing.
• JSP pages can be used in combination with servlets that handle
the business logic, the model supported by Java servlet template
engines.
JSP Page contents:
Everything in JSP page can be broken into 2 categories:
-> Elements or tags that are processed on the server.
-> Everything other than elements that the JSP engine
ignores(Template data).
2016-08-07
15
• JSP is a Java based language and can utilize the
potential of Java language
• JSP Uses Tags to render pages into HTML code
• JSP Tags can be classified into 5 groups
–
–
–
–
–
Directives
Declarations
Expressions
Scriptlets
Standard Actions
• JSP Tags start with <% and end with %>
• JSP Comments start with <%-- and end with --%>
Directives
• JSP directives serve as messages to the JSP container from JSP.
• They are used to set global values.
General Syntax is:
<% @ directive name attribute =“value” %>
Contd…
Three types of directives:
• Page directive
• Include directive
• Tag lib directive
Contd…
•
Page directive: It defines a number of important
attributes that effect the whole page.
Syntax: <% @ page attribute %>
Attributes:
1.
Import
<% @ page import = “java.sql.*” %>
<%@ page import=“java.util.Collection”%>
2.
3.
Content type (contentType=“text/html;charset=ISO-8859-1)
Session
<% @ page Session = “”true” %>
Directives Cont ..
• These are parsed and translated by the compiler before
the compilation
Syntax: <%@directive attribute=“value” ... %>
Directive can be:
page: use to provide information about it by way of attributes
language=“java” the only supported language as of now
session=“true” session will be created (default=“true”)
errorPage=“errorpage.jsp” Any exception is redirected to it
contentType=“text/html;charset=ISO-8859-1”
isErrorPage=“false” true only for error page
Example:
<%@page language="java"
import="java.sql.*,mypackage.myclass" session=”false”%>
JSP Syntax
Page Directive
• Defines attributes that apply to an entire page
<%@ page [ language=“java” ]
[ extends=“package.class” ]
[ import=“package.class” ]
[ session=“true | false” ]
[ buffer=“none | 8kb | sizekb” ]
[ autoFlush=“true | false” ]
[ isThreadSafe=“true | false” ]
[ info=“text” ]
[ errorPage=“relativeURL” ]
[ contentType=“mimeType” ]
[ isErrorPage=“true | false” ] %>
2016-08-07
21
Directives Cont ..
import attribute: A comma seperated list of classes/packages to import
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="java.util.*,coreservlets.*" %>
contentType attribute: Sets the MIME-Type of the resulting document (default is text/html)
<%@ page contentType="text/plain" %>
<%@ page contentType="MIME-Type; charset=Character-Set" %>
Note that instead of using the contentType attribute, you can write
<% response.setContentType("text/plain"); %>
include: used to include other html/jsp pages here
<%@ include file=“abc.jsp” %>
<%@ include file="relative url" %>
taglib: Used to define new tags and prefixes
<%@ taglib uri=“tlds/taglib.tld” prefix=“mytag” %>
URI for the JSTL Libraries
JSTL consists of five different type of tag libraries , which minimizes the name
collisions among the actions in different categories
----------------------------------------------------------------------------------------------------Library
URI
Prefix
Core
http://java.sun.com.jsp/jstl/core
c
XML processing
http://java.sun.com.jsp/jstl/XML
x
118Nformating
http://java.sun.com.jsp/jstl/fmt
fmt
Database accesses
http://java.sun.com.jsp/jstl/sql
sql
Functions
http://java.sun.com.jsp/jstl/functions
fun
JSP Scripting Elements
• Scripting elements let you insert code into the
servlet that will be generated from the JSP
• Three forms:
– Expressions of the form <%= expression %> that are
evaluated and inserted into the output,
– Scriptlets of the form <% code %> that are inserted
into the servlet's _jspService method, and
– Declarations of the form <%! code %> that are inserted
into the servlet class, outside of any methods
Declarations
• Declarations are used to declare variables, methods etc., which
will be used later in the page.
• JSP Declaratives begins with <%! and ends with %>
• Any amount of Java code can be embed in the JSP Declaratives.
• Variables and functions defined in the declaratives are class level
and can be used anywhere in the JSP page.
• Syntax of JSP is as follows:
<%!
%>
//java codes
• Examples:
– <%! int count = 0; %>
– <%! double sqr(double x) {
return x * x; } %>
– <%! private int int counter ;%>
Declarations
Example:
<%@page contentType="text/html" language=“java”%>
<html> <body>
<%!
int cnt=0;
private int getCnt() { cnt++; return cnt; }
%>
Values of Cnt are:<br><%= getCnt()%><br>getCnt()%>
</body> </html>
Expressions
•
•
•
•
Expressions in JSP are single instructions.
Expressions begin with <%= and end with %>
There is no semicolon after the expression
Examples of expressions are as follows:
<%= i++ %>
<%= myMethod() %>
Expression Translation
<H1>A Random Number</H1>
<%= Math.random() %>
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setContentType("text/html");
HttpSession session = request.getSession(true);
JspWriter out = response.getWriter();
out.println("<H1>A Random Number</H1>");
out.println(Math.random());
...
}
28
Predefined or implicit Variables
are used in Expressions
• The following predefined variables can be used:
– request, the HttpServletRequest
– Represents the client’s request as an object and is a
subclass of HttpServletRequest. It is used to get
client’s form data
– response, the HttpServletResponse
– Response is a subclass of HttpServletResponse and is
used to send out the information from server to
client (browser)
29
Cont..
– session, the HttpSession associated with the request
– Represents a storage space common to all pages of
the client. Anything stored here is available as long as
the session is alive
– out, the PrintWriter (a buffered version of type
JspWriter) used to send output to the client
Represents the write stream of the client and
anything written here will be sent to the browser
30
Other Implicit variable
• PageContext
– Page attributes are available throughout the object
• exception
– Exception details can be obtained through this object
• application
– Variables in this object are available throughout the application,
which means all clients can access the same variable
• config
– Uses to get servlet configuration parameters
• page
– Represents this object
31
Request Object methods:
• Some of the request object methods are as follows:
– <%=request.getMethod()%>
– <%=request.getRequestURI()%>
– <%=request.getProtocol()%>
– <%=request.getPathInfo()%>
– <%=request.getPathTranslated()%>
– <%=request.getContentLength()%>
– <%=request.getQueryString()%>
– <%=request.getContentType()%>
– <%=request.getServerName()%>
– <%=request.getServerPort()%>
– <%=request.getRemoteUser()%>
– <%=request.getRemoteAddr()%>
– <%=request.getRemoteHost()%>
– <%=request.getAuthType()%>
<HTML>
<HEAD> <TITLE>JSP Expressions</TITLE></HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE>
form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
33
Encoded
Unencoded
34
Scriptlets
• Scriptlets are small pieces of Java code that runs
immediately.
• Scriptlets start with <% and end with %>
• These are sections of Java code embedded in the
page Unlike expressions, they do not return a value
• But may write directly to the page
• JSP scriptlets let you insert arbitrary code into the
servlet method that will be built to generate the
page ( _jspService )
• The syntax of a scriptlet is as shown below:
<%
// Any amount of Java code here
%>
Scriptlets
•
Java code,which is inserted into the servlet
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
out.println( userName )
%>
•
Example:
<% for( int int i=0; i<poll. i=0; i<poll.getAnswerCount getAnswerCount();
i++ ) %>
Scriptlet Translation
<%= foo() %>
<% bar(); %>
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setContentType("text/html");
HttpSession session = request.getSession(true);
JspWriter out = response.getWriter();
out.println(foo());
bar();
...
}
37
HTML Code in Scriptlets
• Scriptlets don't have to be entire
Java Staments:
<% if (Math.random() < 0.5) { %>
You <B>won</B> the game!
<% } else { %>
You <B>lost</B> the game!
<% } %>
if (Math.random() < 0.5) {
out.println("You <B>won</B> the game!");
} else {
out.println("You <B>lost</B> the game!");
}
38
Example
<%! int n = 0; %>
Page accessed: <%= ++n %> times
<% if ( (n % 10) == 0 ) {
n = 0;
}
%>
RESULT
JSP Standard actions
• Standard actions: JSP tags
JSP action elements result in some sort of action
occurring while the JSP page is being executed, such as
instantiating a Java object and making it available to the
page .
general tag syntax for JSP standard actions:
<jsp:tag attr1="value1" attr2="value2" ... attrN="valueN">
...body... </jsp:tag>
Standard Actions
• JSP Standard actions are predefined into the JSP
engine.
• JSP Standard actions start with <jsp:actionName and
end with </jsp:actionName>
• Some of the extensively used actions are:
(jsp:useBean, jsp:setProperty, jsp:getProperty – manipulate a
JavaBean)
– <jsp:useBean> -- Creates an object of given type
– <jsp:setProperty> -- Sets variable to a value from HTML
– <jsp:getProperty> -- Gets a variable value into HTML
– <jsp:include> -- Includes another page
– <jsp:forward> -- Redirects the Page
42
Example : Predefined bean
<%@ page language="java" contentType="text/html" %>
<html>
<body bgcolor="white">
<jsp:useBean id="clock" class="java.util.Date" />
The current time at the server is:
<ul>
<li>Date: <jsp:getProperty name="clock" property="date" />
<li>Month: <jsp:getProperty name="clock" property="month" />
<li>Year: <jsp:getProperty name="clock" property="year" />
<li>Hours: <jsp:getProperty name="clock" property="hours" />
<li>Minutes: <jsp:getProperty name="clock" property="minutes" />
</ul>
</body>
</html>
43
Using User Defined Classes
Creating an object of type Abc
<jsp:useBean id=“varname” class = “my.package.Abc” />
Getting value of the bean variables into HTML
<b>The value of count in object is </b> <i> <jsp:getProperty
name=“varname” property=“count” />
Setting Values of Bean:
<jsp:setProperty name=“varname" property="*" />
<jsp:setProperty name=“varname" property=“count"
param=“html_count" />
<jsp:setProperty name=“varname" property=“count"
value=“100" />
44
Standard Actions
The jsp:include Action
• This action lets you insert files into the page being
generated
• The file inserted when page is requested
• The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
<jsp:include page=“abc.jsp” />
45
The jsp:forward Action
• Forwards request to another page
<jsp:forward page="relative URL"/>
<jsp:forward page=“abc.jsp"/>
• Page could be a static value, or could be
computed at request time
• Examples:
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression %>" />
46
Create a web application using JSP to show welcome message to the user
<html>
<body bgcolor="wheat">
<form action=“wel.jsp">
<center>
Name<input type="text" name="t1">
<input type="submit" value="send">
</center>
</form>
</body>
</html>
Wel.jsp
<html>
<body bgcolor="yellow">
<h1>Hello
<%=request.getParameter("t1")%>
Welcome to our website!</h1>
</body>
</html>
Create a web application using JSP to show current date and time.
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
hello! the time is now <%=new java.util.Date()%>
</body>
</html>
OUTPUT
hello! the time is now Thu Apr 05 09:11:58 CEST 2012
JSP Example
.
Result
Write a JSP which does the following job:
Insert the details of the 3 or 4 users who register with the web site (week9) by using
registration form. Authenticate the user when he submits the login form using the
user name and password from the database
CREATING TABLE : register
QUERY: create table register(name varchar2(20),password
varchar2(20));
:insert into register values(‘user’,’pass1’);
: insert into register values(‘user2’,’pass2’);
: select * from register;
VAL.Html
<html>
<head>
<title>Login</title>
</head>
<body>
<center>
<form name="a" action="http://localhost:9090/week10/val.jsp">
<table>
<tr>
<td>UserName:</td><td><input type="text"
name="uname"/></td></tr><tr>
<td>Password:</td><td><input type="password"
name="pass"/></td></tr><tr>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</center>
</form>
</body>
</html>
ERROR.HTM:
<html>
<head><title>Login</title></head>
<body><form name="a" action="http://localhost:9090/week10/val.jsp">
<center><p style="color:red">Enter password or username are incorrect</p>
<table>
<tr>
<td>UserName:</td><td><input type="text"
name="uname"/></td></tr><tr>
<td>Password:</td><td><input type="password"
name="pass"/></td></tr><tr>
<td><input type="submit" value="Login"></td></tr>
<table>
</center>
</form>
</body>
</html>
Val.jsp
<%@page import="java.sql.*,java.io.*"%>
<%! Connection con; Statement st;
ResultSetrs; boolean flag=false;
%>
<%
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
try
{ con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:db","scott","tiger”);
System.out.println(con);
st=con.createStatement();
rs=st.executeQuery("select * from register");
String name=request.getParameter("uname");
String pass=request.getParameter("pass");
System.out.println("outside");
while(rs.next())
{
System.out.println(1);
if(name.equals(rs.getString(1)))
{
if(pass.equals(rs.getString(2)))
{
flag=true;
break;
}
}
}
if(flag)
{ %>
<%=name+“Welcome to J.N.T.University "%>
<%
flag=false;
}
else
{%>
<%="Enter Username or password are invalid please try again"%>
<%
response.sendRedirect("error.html");
}
}
catch(Exception e)
{
}
%>