natraj jsp
TRANSCRIPT
-
8/17/2019 Natraj Jsp
1/87
“JSP” Web application is collection of web resource program generating web page.
Based on content that is generated there are two types of web resource prog.
a) Static web resource prog
Generates the static web pages.
b) Dynamic web resource prog.
Generate the dynamic web pages.
Based on the place of execution there are two types of web resource prog
a) Client side web resource prog (eg:- html, java script)
These programs go to browser window for execution.b) Server side web resource prog (eg: servlet , jsp prog)
These program execute by residing in the server
Note: - Decide whether web resource program is client side or server side based
on the place where it executes, not based on the place where it resides.
Client side web Technology:-
(useful to develop client side web resource program/components)
-
8/17/2019 Natraj Jsp
2/87
Html
javaScript
Ajax
Jquery Angular JS
And etc……..
Server side web Technologies:-
(Useful to develop server side web resource prog/components)
Servlet (SunMicro system)
Jsp (SunMicro system)
SSJS(Server side java script) (from Netscape)
PHP (from Apache)
Asp
Aps.net (from Microsoft)
Aps.net MVC
Q:-Why SunMicro system has given JSP even they already got aserver side technology called servlet ?
o In the initial day of servlet the Microsoft ASP programmer have not liked
servlet even though it is having more features than ASP, because ASP
supports tags based programming whereas to work with servlet strong java
knowledge is required.
To overcome above problem SunMicro system has given a
tag based technology called JSP having all the features of
servlet to attract asp programmers.
Limitations of servlet :-o Strong java knowledge is required not suitable for non-java
-
8/17/2019 Natraj Jsp
3/87
programmer placing html code in servlet is quiet complex and
error prone process.
o In servlet programming the java code business logic (html code)
and presentation logic will be mixed up.
o Configuration of servlet prog in web.xml is mandatory.
o Exception handling should be taken care by programmer.
o The modification done in servlet program will be reflected only
after recompilation of servlet program and reloading the web
application.
o No implicit obj support.
o Learning and applying the servlet is complex.
Note: - The object that is created by underlying environment…. And no
code is required to access the obj is called implicit obj…..
Note: - In servlet programming request, response, servletConfig etc.. are
container created built-in objs but not the implicit obj because we need to
write additional code to access those objs.
this, super are the implicit objs/reference variables of java application.
length, class are the implicit obj properties/member variables of java application.
Class c=Test.class;
Here “class” (the implicit member variable) creates and returns
object of java.lang.Class holding “Test” class data of the object.
In java :-
“class” is a oops terminology.
“class” is a keyword.
“ java.lang.Class” is a pre-defined class.
“class” is a built in property.
17-jul-15
-
8/17/2019 Natraj Jsp
4/87
Feature of jsp:-
Allows tags based programming.
Strong java knower is not required, so it is suitable for both java andnon-java programmers.
Gives 9 implicit objects.
Allows to separate presentation logic (html) from business logic(java code).
The modification done in jsp will be reflected without any
recompilation and reloading web application.
Configuration of jsp in web.xml file is optional. Use built in tag and also allows working with third party tag or custom
tag.
Easy to learn and use.
Exception handling is optional.
Allow to work with all the feature of Servlet.
Every “.jsp” file is called as jsp prog/jsp comp/jsp page/jsp file.
Jsp page runs based on page compilation principle i.e. every jsp page
will be converted into an equivalent servlet prog.
To execute jsp page jsp container is required. This Container supplies to jsp
page compiler to translate jsp page into equivalent servlet prog and this
servlet prog executes with the support of jsp container + servlet container.
Every server supplies 1 built-in jsp page compiler as part of its jsp container.
What is difference between servlet and jsp?
Servlet Jsp Strong java knowledge is required so suitable
for java programmers.
Strong java knowledge is not required so
suitable for both java and non-java
-
8/17/2019 Natraj Jsp
5/87
-
8/17/2019 Natraj Jsp
6/87
Template text = ordinary text + html
Jsp page generate dynamic web page the fixed content of dynamic web page
will be generated through template text and the dynamic values will be
generated through java code of scriptlet .
-
8/17/2019 Natraj Jsp
7/87
Place jspApp folder in \web apps for deployment.
Request url: http://localhost:3030/jspApp/Abc.jsp>
20-Jul-15
Q: - How many object can be there in jsp?
o
Two types of object in jsp.
1. Explicit object
It is created by programmer manually.
Eg:
2. Implicit object
Created in JES automatically.
Jsp gives 9 implicit objects.
1. out
2. request
3. response
4. exception
5. application (ServletContext object.)
6.
config7. session
8. page
9. pageContext
What is the difference between html and jsp?
http://localhost:3030/jspApp/Abc.jsphttp://localhost:3030/jspApp/Abc.jsphttp://localhost:3030/jspApp/Abc.jsp
-
8/17/2019 Natraj Jsp
8/87
Html Jsp
It is client side web technology. It is server side web technology.
These programs generate static web page. These programs generate dynamic web
pages.To execute html, interpreter is needed. To execute jsp code, we need jsp
container/jsp engine.
Does not allow to place java code. Allows to place java code.
Html code is not a strictly typed code. Jsp code is strictly typed code.
Tags and attribute are not case sensitive. Tag and attributes are case sensitive.
Servlet prog/component life cycle methods are :
1. init(ServletConfig)
2. service(ServletRequest, ServletResponse)
3. destroy()
o init(), service(HttpServletRequest ,HttpServletResponse), doxxx(-) are not life
cycle methods. They are convenience methods given to programmer.
o Every jsp prog/page internally gets an jsp equivalent servlet prog/component
for execution , so there will not be any separate life cycle methods for jsp sothe servlet life cycle methods itself acts jsp life cycle methods. But different
convenience methods are given for jsp.
They are:-
jspinit()/_jspInit() will be called from init(-) life cycle
method .
_jspService(-,-) will be called from service(-,-) life cycle
method.
jspDestroy()/_jspDestroy() will be called from destroy()
life cycle method.
In tomcat server Jsp Equivalent Servlet(JES) class source file and class file for
ABC.jsp is -
-
8/17/2019 Natraj Jsp
9/87
o ABC_jsp.java , ABC_jsp.class and the location is
\localhost\jspApp\org\apaceh\jsp
Here jspApp is projce name
org\apache\jsp is package name
Every JES class is
a. HttpServlet class based servlet prog
b.
Contains only _jspService(-,-), _jspInit(), _jspDestroy() methods
and does not contains jspInit(), jspDestroy() methods.
c. Extends from jsp Container supplied class which extends from HttpServlet. This
supplied calls jspInit()/_jspInit(), _jspService(-,-) , jspDestroy()/_jspDestroy()
methods from servlet life cycle methods in tomcat server this class name is
“HttpJspBase”.
-
8/17/2019 Natraj Jsp
10/87
d. Template text code, scriptlet code placed in jsp automatically goes to
_jspService(_,_) methods to create and use implicit objects and etc…..
Q: - When JES class obj is created by container?
o Calls init(ServletConfig obj) on JES class object.
Since not found, init(ServletConfig) of super class (HttpJspBase)
executeds and that methods internally calls jspInit(), _jspInit()
methods.
When request processing event occurs.
Calls service(ServletRequest ,ServletResponse) on JES class obj. Since not found same service(-,-) of GenericServlet executes
This calls service(HttpServletRequest, HttpServletResponse) of HttpJspBase class.
Service(-,-) of HttpJspBase class internally calls _jspService(-,-) methods.
When Destruct event is raised:
Calls destroy () on JES class obj.
Since not found destroy () of super class HttpJspBase executes.
This destroy () internally calls jspDestroy ()/_jspDestroy () method.
“_” (Underscore) symbol in methods name indicate that they are generated
methods in JES class i.e. we cannot place same methods in JES class through jsp
page/program.
jspInit()/_jspInit(),_jspService(-,-),jspDestroy()/_jspDestroy() methods are
convince methods given by jsp api i.e. these are not life cycle methods of jsp
because they are not called by a container directly and they are called through
servlet lifecycle method internally.
When life cycle life event is occurred is called life cycle method. The method that
is called through life cycle method is not called life cycle method.
-
8/17/2019 Natraj Jsp
11/87
21-Jul-15
In weblogic server JES class for ABC.jsp will be generated as _ _ABC.class and also
destroyed the .java file or JES class once the .class file is created.
Two phases of jsp execution
A. Translation phase
In this phase the jsp page/program will be converted into an equivalent servlet
source file and compiled file.
B. Request processing phase/ Execution phase.
In this phase JES class will instantiated and _jspService(-,-) method executes to
process the request and to send the response to browser.
The request given to jsp program/page directly participates in “request
processing phase” if the source code of jsp page/program is not modified whencompared to previous request and .class file of JES class is available otherwise
request given to jsp page participates in both translation phase and request
processing phase.
-
8/17/2019 Natraj Jsp
12/87
Jsp container internally remembers the source code of jsp program/page for
every request until next request comes to that jsp page/program and uses the
comparison tools like Araxis or WDiff to compare both source codes.
Note: if the .java file JES class is deleted then the request given to jsp file will notparticipate in translation phase.
Note:- the modification done in the source code of JES class does not reflect to
the output.
WEB-INF and its sub folders are called private area of web application i.e. only
underlying serve/container can use the content of that web application.
If any web resource is placed inside WEB-INF then configuration of web.xml is
mandatory otherwise optional.
In some special cases we prefer to place jsp program or page in side WEB-INF
for the following benefits:-
i. To hind technology of the web site from the visitors.
ii. To avoid ugly messages displayed by jsp when we give
direct request to jsp when it is having logic to read and
display request attribute value given by servlet.
To overcome above problems place jsp program inside WEB-INF folder,
configure in web.xml file and Access jsp prog either through servlet/servlet filter.
o Example
A
/WEB-INF/pages/ABC.jsp
-
8/17/2019 Natraj Jsp
13/87
A
/test
Request url
o http://localhost:3030/jspApp1/ABC.jsp (wrong)
o http://localhost:3030/jspApp1/test (correct)
22-jul-15
When jsp page outside WEB-INF, configuration file is optional
When jsp pages are placed inside WEB-INF folder its configuration in web.xml
file is mandatory.
Jsp Tags/Elements
1. SCRIPTING TAGS:-
a. Scriptlet ()
b.
Declaration ()
c. Expression ()
Note:- These tags are given to place java, in jsp. The java code placed in jsp is called script code.
2. JSP COMMENTS ()3. DIRECTIVE TAGS/ELEMENTS
a. page directive ()
b. include directive ()
c.
taglib directive ( )
4. STANDARD ACTION TAGS.
http://localhost:3030/jspApp1/ABC.jsphttp://localhost:3030/jspApp1/ABC.jsphttp://localhost:3030/jspApp1/testhttp://localhost:3030/jspApp1/testhttp://localhost:3030/jspApp1/testhttp://localhost:3030/jspApp1/ABC.jsp
-
8/17/2019 Natraj Jsp
14/87
1. Scripting Tags:-
1. (a) Scriptlet:-
Standard syntax:-
Xml syntax:
...................
...................(java code)
Code placed in scriptlet goes to _jspService () method of JES class.
Variables declared in scriptlet becomes local variables to _jspService (-,-) method of jsp.
In jsp
in JES class
public class ABC_jsp extends …..
{
public void _jspService(-,-)
{
int a=20;}}
We can use scriptlet for placing request processing logic, because its code
goes to _jspService(-,-) method of JES class.
in jsp
-
8/17/2019 Natraj Jsp
15/87
out.println(“sum=”+c);
%>
int b=30;
int c=a+b;
out.println(“sum=”+c);
}}
Using xml syntax:-
Welcome to jsp
Out.println(“system date “+ new java.util.Date());
While working with less than symbol “
int b=30;
if(a
-
8/17/2019 Natraj Jsp
16/87
the body as ordinary text (java code), so “
But greater than symbol does not have such problem:
int a=20;
int b=30;
if(a>b).
out.println(a +” is less than”+ b);
elseout.println(b +” is less than”+ a);
N OTE : - less than symbol is not there with standard syntax and greater than symbol not goes this
problem in any syntax.
Implicit object are local variable to _jspService(-,-) method in JES class, and the code
placed in scriptlet also goes to _jspService(-,-) of JES class so we can use implicit objs in
scriptlet.
// here out and request is implicit object.
java does not support nested method support so we cannot place method definition in
scriptlet, because it becomes nested method definition of _jspService(-,-) method.
Jsp code
// it will gives error because it will become
nested method in _jspService(-,-) method.
In JES class
public void _jspService(-,-) throws
Se,IOE
{
public int sum(int x,int y)
return x+y;
}
}
-
8/17/2019 Natraj Jsp
17/87
Note: - we cannot place interface definition in a method definition that mean we cannot place
interface definition in scriptlet.
But we can place class definition in the above context.
java support nested class definition, nested interface definition.
We can place interface definition inside the class and class definitioninside the interface.
1.
(b) Declaration Tag:-
The code placed in eclaration tag goes outside to _ jspService method of JES class.
So we can use this tag for global variables declaration, method definition,
class/interface definition (nested), jspInit(), jspDestroy() method
definitions and etc……
Standard syntax:-
Xml syntax:-
……. …….
Variable declared in Declaration tag will come as global variable of JES class.
In JES
In JES class
public class ABC_jsp extends ……
{
int a=10;
}
Q: - How can we differentiate declaration tag variable from scriptlet tag variable
being from scriptlet when both have got same name.
-
8/17/2019 Natraj Jsp
18/87
23-Jul-15
Ans:- Use either implicit object “page” or “this” as shown below:-
We can place user defined method in declaration tag.
JSP program
{
if (x
-
8/17/2019 Natraj Jsp
19/87
Implicit object of jsp cannot be used in declaration tag because implicit object
are the local variable of _jspService(-,-) method and declaration tag code not goes to
_jspService(-,-) in JES class.
By default JES class gives _jspInit (), _jspDestroy () and _jspService () method,
but we can use declaration tag support to place jspInit() and jspDestroy()
method as shown below.
-
8/17/2019 Natraj Jsp
20/87
1) Complete translation phase on jsp program.
2)
Create JES class objects using 0-params constructor.
3) jspInit() methods executes.
So the first request given to jsp directly participates in request processing.
a
/ABC.jsp
1
a/abc
Note: - we need to request to jsp by using its url pattern.
Note: - jsp configuration in web.xml benefits will come only when jsp is requested through
URL pattern.
Q: - can we placed _jspInit (), _jspDestoy (), _jspService () method indeclaration tags of jsp?
Ans:- not Possible, because they become duplicate method of JES class and java does not
support duplicates.
We can place class, method, and interface definition in declaration tag, they will
become nested class or nested interface of JES.
Jsp:
JES class
public class ABC_jsp extends HttpJspBase
{
class Test{}
interface xyz{}
}
-
8/17/2019 Natraj Jsp
21/87
In one jsp program we can place multiple tags in any order having only xml syntax and
mix of both.
In one declaration tag we can declare multiple global variables and we can place
multiple method definitions.
24-Jul-15
1. (c) expression:-
Anything that returns values after the evaluation is called expression.
Arithmetic, logical, methods call comes under expression.
Expression tag evaluates the given expression and displays the generated results on
browser as the webpage content.
Standard syntax:-
Xml syntax:-
…………
We can use expression tag to display variable values.
Bad practice because we are mixing up html code and java code…
value =
Here will display variable “a” value.
-
8/17/2019 Natraj Jsp
22/87
Jsp program
value :
---displaythe variable “a” value.
JES class
public class ABC_jsp extends –
{
public void _JspService(-,-)
{
int a=10;
out.print(“ value:);
out.print(a);
out.pritn(
);out.println(“result);
out.println(a*a);
}
}
The code placed in expression tag goes to _jspService(-,-) of JES class and
becomes the argument value of out.print() method. If we use expression tag effectively there is no need of working with out.println()
method jsp.
All implicit object of jsp are visible in Expression tags.
in jsp class:
Browser
Name:
In JEs class:
out.println(“Browser”);
out.println(request.getHeader(“user-
agent”));
We can use expression tag to call both pre-defined and user-defined methods but those
methods must return value.
Sum of: is
Length of is
-
8/17/2019 Natraj Jsp
23/87
Date and Time:
Date and Time new java.util.Date()
Even cannot solve the “
not be solved by using CDATA
One expression tag can evaluate only one expression at a time.
If we want to evaluate more than one expression we can use String
concatenation support.
//wrong
//wong
// correct
Note:- We cannot place class definition, method definition, and interface definition in expression tags.
Procedure to jsp page based web application in Eclipse IDE?
Step-1) configure tomcat 8 with eclipse ide.
Step-2) window serverrun time environmentaddapache tomcat
8nextlocation of tomcat serverfinishok.
Step-3) create dynamic web project.
filenewdynamic web project
step-4) add first jsp to web content folder of the project.
-
8/17/2019 Natraj Jsp
24/87
//get system data
java.util.Calendar c1=java.util.Calendar.getInstance();
//get current hour of the day(24 hrs formate)
int h=c1.get(java.util.Calendar.HOUR_OF_DAY);
//generate wish messageif(h
-
8/17/2019 Natraj Jsp
25/87
-
8/17/2019 Natraj Jsp
26/87
Compiler or interpreter recognizes the comments and places white space
character in the place of commented code due to this commented code
does not participate in execution.
Jsp supports three type of comments
1.
Jsp comments ( )//hidden comments
2. Html comment() //output comments
3. java comments(// or /* */) //scripting comments.
Jsp comments are useful to comment jsp code/tags of jsp program.
These tags will be recognized by jsp page compiler.
Html comments are useful to comment html code/ tags of jsp prog.
These tags will be recognized by html interpreter.
java comments are useful to comment java code of jsp program.
Theses comment is recognized by java compiler (javac).
Comment Visibility
.jsp In JES
source
In JES
compiled
Code that
goes to
browser
Jsp comment
Yes No No No
Html comment Yes Yes Yes Yes
java comments Yes no No No
jsp comments not visible in any phase of jsp execution so they are called as “hidden
comments”
Html comments go to the output code that goes to browser so they are called “output
comments”
-
8/17/2019 Natraj Jsp
27/87
Technically speaking in jsp implicit object are not there but implicit reference
variable are there pointing to various object of web application.
“config” is the implicit reference variable pointing to ServletConfig
object.
“application” is reference variable pointing to ServletContext object.
Since these implicit reference variable are local variable of _jspService(-
,-) method. We cannot use them in declaration tag code. But we can
create other reference variable accessing same object in declaration tag
by using servlet API support.
Example :-
o We can access ServletContext, ServletConfig obj in jspInit() or
other methods declaration tags as shown below.
user
scott
a
one.jsp
p1
val1
-
8/17/2019 Natraj Jsp
28/87
A
/test1
30-Jul-15
page scope means item is specific to current jsp page/program.
request scope means item is visible through request and it is specific to each request.
Session scope means item is specific to each browser but it is visible in all web resources
programs.
application scope means item is visible in all web resource programs of web applicant
irrespective of any condition.
Implicit object Reference object Scope
Out javax.servlet.jsp.JspWriter (AC) Page
pageContext javax.servlet.jsp.tagext.PageContext(Ac) Page
Config javax.serlvet.servletConfig (I) Page
application javax.serlvet.ServletContext (I) Application
Request javax.servlet.HttpServletReqeuest (I) Request
Response javax.servlet.HttpServletResponse (I) Response
Exception java.lang.Throwable (C) Page
session javax.serlvet.HttpSession (i) Session
page java.lang.Object ( C) Page
The above implicit objects are not objects technically, they are reference variablespointing to various implementations class object or sub-class object that are given
above.
To know the class name of any implicit object, use getClass() method as shown
below.
Response object class name
Request object classname
JspWriter object of class name
“out” is the object of class given by jsp container extending from JspWriter (AC)
class, that class name in Tomcat is org.apache.jasper.runtime.JspWriterImpl, thisclass is actually extends from JspWriter.
JspWriter out=new JspWriterImpl();
Html to jsp to DB s/w communication
-
8/17/2019 Natraj Jsp
29/87
For html to jsp communication we need to use jsp file or url pattern as href value of
tag or action attribute values of tag.
For jsp to DB s/w communication place jdbc code in jsp page/program.
In this we can get jdbc properties from web.xml file either as context
param values or as init() parameter values.
-
8/17/2019 Natraj Jsp
30/87
Imp points;-
Above application involve in all the three life cycle convenience method.
We need to differentiate logic for submit, hyper-link related request generation.
Gather jdbc properties as init() parameter values from web.xml file to achieve the
flexibility of modification, for this access ServletConfig object through servlet api code
in jspInit().
For above diagram based application source code refer application-4 of page no 264 to
267.
The code placed in jsp which goes to _jspService()method in that case exception is
option but form remaining situation exception handling is mandatory.
31-Jul-15
-
8/17/2019 Natraj Jsp
31/87
Placing jdbc property in web.xml file gives flexibility of modification that means we can
change username, password and etc…. details based on the change done by database
administrator.
Directive tags:-
These tags are given to provide instructions or guidelines to jsp page compiler to
generate the code in JES class.
There are 3 directive tags:-
a.
Page directive () It provides Global info to jsp page.
b. Include directive ()
It is use to include the content of destination file
c. Taglib Directive (
-
8/17/2019 Natraj Jsp
32/87
session=”true”
Default is ”true”
import =”java.util.*”
No any default value.
extends=”super class name of JES”
No any default value.
buffer=”10kb”
Default is 8kb.
autoFlush=”true”
Default is true.
errorFlush=”true”
Default is true
isErroPage=”true”
Default true
isELIgnored=”false”
Default false language=”java”
Default java.
isThreadSafe=”true”
default true.
language :-
Allows to specify the language that can be used to write script code in jsp.
“java” is default or only language that can be specified there.
This attribute effect will not appear in JES class. Example
(valid)
(invalid)
-
8/17/2019 Natraj Jsp
33/87
setContent :-
Allow to specify the response contentType.
res.setContentType(-) default value is “text/html” , if we have multiple values as the
“, “ separated list then final values will be applied. Eg:-
session :-
It specifies whether the implicit object session should be created or not.
Create implicit object session
Does not create implicit object session default values: true.
o Note:- We need “session” obj only when session tracking is enable otherwise not
required.
01-Aug-15
info: Given to place short description about jsp page. This helps to know about
jsp page by seeing the header section of jsp pages.
In JES class getServletInfo() method will be overridden having this short
description.
ABC.jsp
……. ………
IN JES class
public String getServetInfo()
{
return “jep page that gives emp Report”; }
-
8/17/2019 Natraj Jsp
34/87
extends
Allows to specify the class that should be taken as the super class of the
JES class, but this class must extends from HttpServlet (class) and must
implements HttpJspPage (Interface), otherwise exception will be raised.
This is not an important attribute to use because every jsp container
generates proper JES class extends from the jsp container supplied super
class, So there is no need of specifying user defined class as the super
class.
Jsp
In JES class
public class ABC_jsp extends Test{
………
……… }
import:-
Given to specify the packages that should be imported in JES class. We
can specify multiple values as the “,” list of values.
By default JES class import javax.servlet, javax.servlet.http,
javax.servlet.jsp packages.
Example:
isThreadSafe:-
The jsp page that allows multiple simultaneous requests, represent
multiple threads is not thread safe jsp.
The jsp page that allows one request/thread at a time is called thread
safe jsp.
“isThreadSafe” attribute allows us to specify whether our jsp page is
thread safe page or not.
-
8/17/2019 Natraj Jsp
35/87
“isThreadSafe=”true” “ makes jsp page allowing multiple simultaneous
requests, So jsp page is not thread safe.
“isThreadSafe=’false’” makes jsp page to allows one thread/one request at
a time on to the jsp page.
For this JES class implements javax.servet.SingleThreadModel(Interface).
Any class that implements javax.servet.SingleThreadModel(interface) is
thread safe because we can start 1 thread at a time on that class object.
By default jsp page is not thread safe because the default value of
“isThreadSafe” attribute is “true”.
Example:-
//jsp is thread safe.
//jsp is not thread safe.
Buffer is temporary memory that holds data for temp period.
Servlet program uses pw.println() to writer output. (PrintWriter), this PrintWriter directly give output to the response object without taking buffer support .
In jsp programming “out ” object type is JspWriter and this uses buffer support
while writing the output of jsp program to response object.
To specify the buffer size of jsp program we can use buffer attribute, this attribute
default value is 8 KB and we can specify any other value or “ none” .
//enable buffer.
//disables the buffer
What is the difference between PrintWriter and jpsWriter?
PrintWriter JspWriter
Class of jdk api. Class of jsp api
Does not support buffering Supports buffering
-
8/17/2019 Natraj Jsp
36/87
Useful in servlet programming. Useful in jsp programming as the type of “out”
object.
Note: - When buffering is disable in jsp (buffer=”none”) the jsp writer internally uses
PrintWriter object to write the content.
autoflush
Flushing buffer means sending the content of buffer to its destination. In
case of jsp the destination is response object.
Jsp page automatically flushes the buffer in the following situation.
When buffer is filled up when jsp page is complete its execution,
Auto flush attribute is given to specify whether autoFlushing
should be enabled or disabled on the buffer.
autoFlush=”ture”
enable auto flushing (default value) autoFlush=”false”
disable autoFlushing.
This attribute should be used in combination with “buffer” attribute.
Example:-
-
8/17/2019 Natraj Jsp
37/87
Gives exception indicating bad combo.
Does not gives exception, but not a good practice.
-
8/17/2019 Natraj Jsp
38/87
isELIgnored:-
Writing java code in jsp is not industry standard but performing arithmetic and logical
operation in jsp without java code is not possible. To overcome this problem we can use EL
(Expression language).
${}
isELIgnored specified whether EL in jsp should be recognized or ignored.
Sum is :${1+2} ouput is Sum is :$(1+2) Sum is :${1+2} ouput is Sum is :3
errorPage:-
The page that executes only when exception is raised in other jsp pages is
called error page. This is useful to display non-technical guiding
messages on the browser when exception is raised.
“errorpage” attribute can be used to specify that error page in any jsp
page.
Example:
%@page errorPage=”err.jsp” %
isErrorPage:-
Makes page compiler, jsp container to take the current jsp page as error
page. This page gets one extra implicit object called “exception” to display
exception related details.
Example:
Err.jsp
Note:- This implicit object “exception “ is visible only in error page.
mailto:%25@page%20errorPage=mailto:%25@page%20errorPage=mailto:%25@page%20errorPage=
-
8/17/2019 Natraj Jsp
39/87
Exception handling in jsp Or error page configuration in jsp: -
Note: Even though JES takes care of exception handling it display technical, ugly message onbrowser window when exception raised.
There are two ways to perform erropage configuration in jsp.
Local Error page configuration:-
It is specific to one jsp program/page. Use “erroPage,isErrorPage”
attribute of for this.
Global error configuration:-
Common for all jsp program/pages of web application use tag of web.xml file.
-
8/17/2019 Natraj Jsp
40/87
Main.jsp
Value :
err.jsp
internal Problem . Try again !!!!
Message :
request url: localhost:3030/JspApp3/Main.jsp
We can take html page as error page but it is not recommended to use because it does
not allow using the implicit object “exception”.
The above errorPage configuration cannot be uses for servlet programming for that weneed to go for rd.forward() based error servlet configuration.
Displaying non-technical guiding messages when IRCTC website gets technical
problem in the middle of utilization. Like network failure and database crashed.
04-aug-15
Global Error Page Configuration:-
This global error page will respond for all the exceptions that are raised in multiple jsp pages of a
jsp page of a web application. Use tag web.xml file.
JspApp4
|----------------------->WEB-INF
|------->Main1.jsp |------->web.xml
|------->Main2.jsp
|------->error.jsp
java.lang.Exception
/err.jsp
//error page configuration for any exception
raised in jsp pages
-
8/17/2019 Natraj Jsp
41/87
Internal problem. Try again
from Main1.jsp
Value=
From Main2
current month is:
Resource url: http://localhost:3030/jspApp4/Main1.jsp
Note: we can place multiple tags in web.xml file to configure multiple error
pages for multiple exception raised in the multiple jsp page of jsp application.
If we configure local and global error page for certain main jsp program then local
error page will be executed when an exception is raised in jsp page.
Observation about page directive tag:-
1. Page directive tag name and attribute name are case sensitive.
2.
In valid attributes are not allowed.
3. Except import, contentType attributes, no other attribute is allowed to have
multiple values as the “,” separated list of values.
4.
Except import attribute no other attribute can be repeated for multiple times with
diff values either in same page directive or in different page directive tags.
http://localhost:3030/jspApp4/Main1.jsphttp://localhost:3030/jspApp4/Main1.jsphttp://localhost:3030/jspApp4/Main1.jsphttp://localhost:3030/jspApp4/Main1.jsp
-
8/17/2019 Natraj Jsp
42/87
Directive include:-
Xml Syntax:
Includes the content/code of Destination file to the code of source jsp page’s in JES class
at translation phase. Separate execution does not take place for Destination
page/file/program.
mailto:%25@include%20file=mailto:%25@include%20file=
-
8/17/2019 Natraj Jsp
43/87
No JES class will be generated for B.jsp but B.jsp code will be included to the JES class of A.jsp.
Note: this tag does not use rd.include() internally.
From the beginning of A.jsp
end of jsp
from b.jsp
Note:- in the above example in the JES class of a.jsp contains the code of A.jsp and B.jsp.
Action tag:-
These tags are given to use servlet api functionalities dynamically
at run time or request processing phase to complete the
requirement.
There are two type of Action tag
a. Standard Action tag.
Given by jsp technologies directly.
-
8/17/2019 Natraj Jsp
44/87
Eg. and etc……..
b. Custom action tag.
Developed by programmer or third party vendors.
Note: - Action tags contain only xml syntax to use.
Action include:-
Syntax:-
Uses rd.include(-,-) internally use to include the output of Dest file/page/program to the
output of source jsp page dynamically at runtime/request processing phase.
05-Aug-15
page=”Destination page”
flush=”true/flush” => specified whether the buffer of source jsp page should be
flushed or not before including the output of destination program /file.
-
8/17/2019 Natraj Jsp
45/87
here source and destination jsp pages executes separately by generating two different
JES classes but Destination jsp page output will be included to the output of source jsp
page by rd.inclde(-,-) internally .
JapApp6
|----->A.jsp
|----->B.jsp
From the begnig A.jsp
End of
From B.jsp
What is the difference between
Directive Action
-
8/17/2019 Natraj Jsp
46/87
Perform code inclusion Perform output inclusion.
Performs inclusion at translation phase so
it is called static binding or compiles time
binding.
Performs output binding/inclusion at run
time so it is called dynamic binding
runtime binding.
Does not use rd.include() internally. Uses rd.include() internally.
This tag contains both standard, xml
syntax.
Only xml syntax.
Does not allow servlet program as the
destination program.
Allows
Does not allow specifying destination page
through expression.
(error)
Allows to specifies
Not a error
It does not generate separate JES class if
destination program is jsp program.
Generates Separates JES class.
Useful when destination program is static
web resource program.
Eg:- html page.
Useful when dest prog is Dynamic web
resource program.
Eg: servlet prog, jsp prog
-
8/17/2019 Natraj Jsp
47/87
-
8/17/2019 Natraj Jsp
48/87
Page2.jsp is same as page1.jsp but replace home.jsp with weather.jsp.
Page3.jsp is same as page1.jsp but replace Home.jsp with sports.jsp.
http://localhost:3030/jspApp7
jsp chaining/request dispatching/communication.
Taking request from client and processing that request by using multiple
jsp’s in a communication is called jsp chaining request/
dispatching/communication.
http://localhost:3030/jspApp7http://localhost:3030/jspApp7http://localhost:3030/jspApp7
-
8/17/2019 Natraj Jsp
49/87
For this we can use / tag.
In this changing source jsp page and the destination jsp use same
request, response obj so the request data coming to source jsp is visible
and accessible to destination jsp.
====> perform forwarding request operation
==> perform including response operation .
o Perform forwarding request operation by using rd.forward(-,-) internally. It
discard the output of source jsp page and send only the output of
destination page to browser through source jsp page as final response. It is
recommend to place in source jsp page as a conditional
statement to execute.
Syntax:-
o Note: there is no directive forward tag.
A.jsp
from the start of A.jsp
From end of A.jsp
B.jsp
form B.jsp
Date and time:
In servlet programming the statement placed after rd.forward() in source servlet
program will be executed but there html output will be discarded.
-
8/17/2019 Natraj Jsp
50/87
In jsp programming statement placed after tag will be not be executed
because in the JES class of source jsp “return” statement will generated followed by
rd.fordward().
In the above application separate JES class for A.jsp and separate JES for B.jsp will
generated. But rd.forward() will be utilized internally to forward the request.
-
8/17/2019 Natraj Jsp
51/87
Q: - Why there is no directive forward tag?
Directive tag performs code inclusion at translation phase due to this the output
discarding become not possible so there is no directive forward tag;.
Can be used as the sub tag of /
07-Aug-15
Some points are left :-
A.jsp
//val1 is param
values //val2 is
paramvalue
B.jsp
Additional req param values:
-
8/17/2019 Natraj Jsp
52/87
Bill.jsp uses tag to forward the control to discount.jsp and it also uses
jsp:param tag to pass bill amount to Discount.jsp
Refer page: 273-4 for exercise
Send redirect:-
There is no tag in jsp to perform send re
direction. So we need to write response.sendRedirect() method in source jsp page as
shown below……..
Test.jsp
If source jsp page uses sendRedirection to communicate with destination then it talks
with its destination by having one network round trip with browser. So this concept is
useful when destination are remote internet website and un-known technology
websites.
http://www.google.co.in/http://www.google.co.in/http://www.google.co.in/http://www.google.co.in/
-
8/17/2019 Natraj Jsp
53/87
-
8/17/2019 Natraj Jsp
54/87
“application” attribute scope is application scope i.e they are visible with in the
application.
“request” attribute created in A.jsp is accessible in B.jsp, C.jsp programs.
“session” attribute created in A.jsp by getting request from browser b1 is
accessible in other jsp only when they request from same browser b1.
“application” attribute crated in A.jsp is accessible in all jsp’s irrespective any
conditions.
Instead of using “request”, “session”, “application” objs separately to crate request scope,
session scope, application scope attribute respectively we can use single
“ pageContext ” obj to crate all the scopes of attributes (4 scopes: page, request,
session, application)
To create “pageContext” attribute use setAttribute(-,-) method.o pageContext.setAttribute(“attr1”,”val1”);//here attr1 is attribure name and val1 is value.
creates attr1 as page scope attribute.
o
pageContext.setAttribute(“attr2”,”val2”,pageContext.SESSION_SCOPE);
// pageContext.SESSION_SCOPE to set scope.
creates attr2 as session scope attribute.
To modify “pageContext” attribute value use setAttribute() methodo
same setAttribute(…) method.
-
8/17/2019 Natraj Jsp
55/87
To read “pageContext” attribute values use getAttribute(-) method.
String s1=(String)pageContext.getAttribute(“attr1”);
//get attr1 values from page scope
String s2=(String)pageContext.getAttribute(“attr2”,pageContext.SESSION_SCOPE);
//get attr2 vales from session scope
To remove “pageContext” attribute use removeAttribute(-) method.
pageContext.removeAttribute(“attr1”);
pageContext.removeAttribute(“attr2”),pageContext.SESSION_SCOPE);
To find attribute use findAttribute(-) method.
String s1= pageContext.findAttribute(“attr1”);
searches and gets given attribute in multiple scope.
What is the difference between “getAttribute” and “findAttribute” method?
“getAttribute” search for the given attribute only in
the specified scope.
“findAttribute” searches for the given attribute in
multiple scope in an order (“page”=>
“request”=>”session”=>”application” scope.
Example application:-
Give first request to A.jsp and other request and other jsp pages from same or different browser
windows to absorb scopes of the attribute.
Instead of using “pageContext” object to crate “ page” attribute scope it is recommendedto use instance variable that is specific to each jsp page.
Q: - How can we pass data between various web resource programs of the web
application?
If source jsp page and destination program reside in the same web application
-
8/17/2019 Natraj Jsp
56/87
1. If source jsp and destination program uses same request object .
a)
“request” attributes
b) “pageContext” request scope attribute.
c) As additional request param values using tag.
2. If source jsp and destination program gets request from same browser .
a)
“session” attributes
b) “pageContext” session scope attributes.
3. If above two conditions are not satisfied
a)
“application” attributes.
b) “pageContext” application scope attributes
If source jsp page and destination program reside in two different webapplication
Append query string to url of res.sendRedirect(-) method.
res.sendRedirect(http://www.google.co.on/search?p1=val1&p2=val2);
Session tracking in jsp:-
Same as servlet but we can use implicit object “session” for session tracking.
10-Aug-15
This tag are given to display applets on browser.
This tag allow one tag to display error message when browser does
not support applets.
Applets are outdate because of their performance so there is no much important of this
tag moreover current browser need plugin to display applets.
JspApp11
|------->webcontent
|------->plugin.jsp
|------->TestApp.jsva/.class
(applet)
http://www.google.co.on/search?p1=val1&p2=val2http://www.google.co.on/search?p1=val1&p2=val2http://www.google.co.on/search?p1=val1&p2=val2http://www.google.co.on/search?p1=val1&p2=val2
-
8/17/2019 Natraj Jsp
57/87
If applets are used to display/design animation/logos then is useful. This
tag attributes are:-
type->”applet/bean”
code->Applet class name
codebase-> folder where the applet class is available.
width->
For example application -06 of page 269
Note: - after the arrival of adobe, flex, flush and javaFx the industry is not using applets to
design logo.
tag internally uses or tag and tag
internally uses tag.
o (for more info search in workspace “pluging’ and analysis code)
To pass additional data as params from “ plugin.jsp” to Applets we can use
, tag.
Pluging.jsp
TestApp.java
public class TestApp extends Applet
{
Pubic void paint(Graphics g)
{
-
8/17/2019 Natraj Jsp
58/87
String name= getParameter (“orgName”);
//super class method can directly called in sub class directly getParameter() is paint class
method.
g.drawString(name,200,200);
}}
Java bean is a java class that is developed with some standards.
Setter methods/setxxx(-,-) methods are usefule to write data to bean property.
Getter methods/getxx(-,-) are useful to read data from bean property.
The javaBean whose object holds input value given by end user nothing but form data is
“VO” class.
The java bean whose obj holds data to transfer from one resource to another resource is
called DTO class. This class implemetns Serilizable(interface).
The java bean whose object holds data as required for the persistence operations is
called BO class.
Java bean is always useful as heloper class to transfer data from one layer red to another
layer.
For servlet to javaBEan communication we need to create java bean class obj is serletand cll various setXXX(0,0) and getxxx(-,-) methods.
For jsp to jsvaBean communication we can use
o , , , tags …..
Example java Bea
------
Public class StudentBean
{
Private int sno;
Private String name;
Private String address;
{
//getter and setter
}}
-
8/17/2019 Natraj Jsp
59/87
Useful to create /locate bean class object.
o
Attributes
“id ””become reference variable name of bean class object”.
“class” ”fully qualified bean class name”.
“scope””page/request/session/application”
Default scope is page.
“beanName” ”Allows to specify the extra logical name”.
“type” “allows to specify the super class name as reference type”.
Example:-o
Create “StudentBean” class object referred by “st” and keeps in session
scope having the attribute name “st”.
If(pageContext.getAttribte(“st’,pageContext.SESSION_SCOPE)==null)
StudentBean st=new StudentBean();
pageContext.setAttribute(“st”,st,pageContext.SESSION_SCOPE);
}
else
{
St=pageContext.getAttribute(“st”,pageContext.SESSION_SCOPE);
}
Example:-
com.nt.Person” is refrence type and com.nt.studentBean is object type. Note:- StudentBean must be the sub class of Person.
Note: if “type” attribute is not specified then the “class” attribute values acts as refrence type
and object type.
-
8/17/2019 Natraj Jsp
60/87
11-Aug-15
calls setxxx() of java bean class to set given values to bean properties.
o
Attributes:-name=” “ Bean id(id attribute values of tag)
property=” “bean property name or xxx or setxxx(-) method.
Value=” “value of bean property.
Param=””->request param name whose values should become request .
. param value.
Note:- use either value or param attributes at a time.
Eg1:- java resources|---------src
|---------com.nt
|---------studentBean.java
|---------webcontent
|---------setValues.jsp
|---------getValues.jsp
-
8/17/2019 Natraj Jsp
61/87
|---------WEB-INF
|---------web.xml
For above code based example application refer application-7 of page no 270.
Loacalhost:3030/jspapp12/setvalue.jsp
Getvalue.jsp
JavaBeans of web application need not be configured in web.xml file.
There are three type of bean properties:-
1. Simple Bean properties
o Allow to set one values at a time.
Eg:
private String name;
public void SetName(String name){
This.name=name;
}
Public string getName()
{
Return name;
}
2. Boolean bean properties.
Allows to set 1 boolean value at a time
Eg:-
private boolean married;
public void setMarrired(boolean married)
{
This.married=married;
}
Public boolean isMarried()
{
Return married;
}
3. Indexed properties
Allows to set multiple values to each property.Eg:-
Private string color[];
Public void setColors(String [] colors)
{
This.colors=colors;
}
Public String[] getColors()
-
8/17/2019 Natraj Jsp
62/87
{
Return colors;
}
The above tag useBean setProperties and getpropteries are useful when jsp want to send
multiple values of form page to service class or DAO class in the form of Bo or DTO class or Vo
class object.
DAO uses Bo class object.
Service class can use either BO class or DTO class object.
Gudces
12-aug-15
Java web application contains
Request data gathering
Reading request parameter, header, miscellaneous details)
Form validation logic.
Checks format, pattern of from data(main logic that generate
result)
B.logic/service logic/request processing logic
The logic that gives user interterface.
Presentations logic
Logic that performs database operation example jdbc code.
Session management logic
Cookies, hidden form fields and etc…)
Middleware services.
Additional services like security, logging, pooling and etc..)
Model-1 Model-2Here we use either only servlets or only jsp todevelop java application, i.e if servlets are usedin web application the jsp will not be used any
vice versa.Model-1 architecture is mainly using jsp
-
8/17/2019 Natraj Jsp
63/87
application.Here every main web resource pro likeservlet/jsp program contains all the logic of
web application development.
Model-1 architecture:-
Working with only jsp or servlet comes under model architecture.
The application that we have developed so far using only servlet or jsp comes under
model one architecture.
Disadvantage of model-1 architecture:-
Since every web resource program contains multiple logic we can say there is cleanseparation between logics.
The modification done in one logic will disturb the other logics.
Parallel development is not possible, so the productivity is very poor .
Enhancement and maintained of the project becomes very complicated.
Certain middle ware services must be developed by the programmer manually.
This improves burden on the programmer.
Advantages:-
Knowledge on only servlets or only jsp is enough to develop web application.
Since parallel development is not possible, so multiple programmers are not required.
Note:- Doing more work in less time with good accuracy is called productivity.
Note:- model1 is good to develop small scale java web application less than 10 pages.
MVC – MModel Layer represents B.logic +persistence logic. (Accountants
-
8/17/2019 Natraj Jsp
64/87
(Generate Data)
V View layer represents presentation logic (Beautician)
Ccontroller layer represents integration logic. (super viser)
Integration logic controls and monitors all the activities of application development. This
logic takes the request from client, passes the request to model comp, gathers the results
from model comp and passes the result to view comp.
In MVC1 single servlet/jsp component contains view, controller layer logics and separate
components will be taken as model components.
In MVC-2 we Take separate jsps as view layer comps, separate servlet as controller comp
and separate other components as model layer components
Since we are write model layer logic in separate logic in separation components.
It give clean separation between logics then go for MVC-2 arch
MVC-1 architecture is good to develop medium size application. 10 to 20 pages.
Advantages –
Since there are multiple layer we can get clean separation between logic the modification
done in one layer logic does not affect other layer logic. Provides easiness in enhancement, maintenance of the web application.
Parallel development is possible so productivity the productivity is good (view,
controller logics and model layer logics can developed parallel)
It is defacto standard to develop large scale java websites.
While using EJB, spring in Model layer we can use built in middle ware services.
-
8/17/2019 Natraj Jsp
65/87
Disadvantage-
Knowledge on more technologies is required.
For parallel development more programmers are required.
13-aug-15
MVC-2 rueles/principle
Every layer is designed to have specific logic so just place those logic and don’t place
any additional logics in each layer.
All the operation of the application must be handled under the control of controller
servlet.
They can be multiple resources in model layer and view layer but we must take single
servlet or servlet filter as controller.
The view layer component should not interact with model layer comp
directly, thy must interact with each other through controller servlet.
The controller servlet should have ability of trapping request wrapping request data to
object and validating request data and etc…operations.
Can we change the roles of various technologies uses in MVC-2 architecture based
application?
Servlet as view:-
-
8/17/2019 Natraj Jsp
66/87
Presentation logic of web application changes as regular interval and changing code in
servlet programing needs recompilation of servlet and relocating of web application.
The modification done in jsp will reflect directly, so jsp are good as view.
Jsp as controller:-
Write java code in jsp is not industry standard but as a controller jsp should have java
code to interact with model components. Placing java code in servlet to interact with
model component is good practice so use servlet as controller.
Hibernate app/EJB comp/spring app as view, controller layer
components:-
They cannot take requests and they cannot response, so they cannot be taken as view,
controller layer components.
Project:-
Add rotator. This application display advertisements in the web pages.
There are three type of adds :-
a) Sequential advertisements
Comes one by one in a sequence.
b)
Random advertisements
Displays the adds randomly
c) Direct advertisements
Displays adds based on the actions of programs.
Eg: while searching for seven wonders it displays adds about tours
and travels)
Our AddRotator application
a) Develop based on MVC-1 architecute(jsp java bean/class)
b) Should display random add for every 2 seconds.
c) Should add as graphical hyperlinks
-
8/17/2019 Natraj Jsp
67/87
jspApp13:
|------->java resources
| |------->com.nt
|------->Rotator.java (bean class)
|------->webcontent
|------->Addrotator.jsp
|------->1.jpg, 2.jpg, 3.jpg
|------->WEB-INF
|------->web.xml
Refer app-8 of page
no-271
14-Aug-15
Mini project discussion
We can send only serializable object over the network. We can say the obj is serializable
object only when the class of the Object implements java.io.Serializable interface.
ResultSet obj is not a serializable object so we cannot send that object over the network.
To overcome that problem use
RowSet instead of ResultSet.
Note- all RowSets are serializable obj by default.Note: very few jdbc driver support RowSets.
Copy ResultSet object record to collection and send that collection over the network.
Note: - all collections are serializable object by default.
Note: - if you want to perform only read operation on the collection then use non-
synchronization data structure that gives performance. If want to perform both read
and write operation on collection then use synchronized data structure for thread
safety.
Understanding problem to copy records of ResultSet to the elements of ArrayList.
Each element of ArrayList allows one object at time but each record of ResultSet
contains multiple value/objects. So we can’t place each record of ResultSet to each
element of ArrayList
-
8/17/2019 Natraj Jsp
68/87
To overcome this problem copy each record to one class of BO class object and that BO
class object to ArrayList element.
Note:- In order to send collection over the network the object added to collection must
also be taken as serilizable object.
BO class
public class Student implements java.io.Serializable
{
private int sno;
private String sname;
prviate String sadd;
//setter and getters}
ArrayList al=new ArrayList();
ResultSet rs=st.executeQuery("select * from studetn"0;
while(rs.next())
{
// copy each record of ResultSet to Eache Bo calss object.
Student st=new Student();
st.setSno(rs.getInt(1));
st.setSname(rs.getString(2));
st.setSadd(rs.getString(3));//add Each BO object to each ArryList element
al.add(st);
}
-
8/17/2019 Natraj Jsp
69/87
-
8/17/2019 Natraj Jsp
70/87
MVC2 Architecture based Mini project:-
M---->Model ---->java class(B.logic +persistence logic)
V---->view ---->jsp/html (presentation logic.)
C---->Controller----> integration logic. (servlet)
17-aug-15
Key points:
The above application uses BO class (java bean) support to transer the records of
ResultSet to ArrayList and sends this ArrayList
Over the network to servlet.
Servlet uses rd.forward(-,-) to pass control to jsp program of view layer
Uses java script for form validation and also for submitting request.
Servlet program identifiers the button that is used to submit request based on the values
sent from hidden box.(source)
Servlet program pass the ArrayList obj as request attribute values to jsp program to pass
the result given by Model layer java class to jsp program.
Provision is placed to take the print out the web page.
Provision is placed to download the excel sheet.
For source code project given in page no-300
-
8/17/2019 Natraj Jsp
71/87
18-Aug-15
Mini project 2:-
The process of sending the files of client machine file system to server
machine file system is called file uploading and reverse is called file
downloading.
There are two types of file downloading:-
a) Response downloading:-
Here the output of web resource program will be send to browser
as downloadable file.
b) Resource downloading:-
Here the resource (file) of server machine file system will be
downloaded to browser.
We use java zoom API for file downloading. In real time the
uploaded files will not be saved in directly in DB table cols. They
will be saved in server machine file system and their address path
will be saved in DB table cols as string values.
o Eg: www.youtube.com
19-Aug-15
For more mini project refer page-285 to 300 of the booklet.
Custom tag library(custom jsp action tag)
Writing java code in jsp is not industry standard we should always develop jsp as
scriptlet jsp page for this we should place only tags in jsp and we should avoid scriptlet,
expression, declaration tags.
http://www.youtube.com/http://www.youtube.com/http://www.youtube.com/http://www.youtube.com/
-
8/17/2019 Natraj Jsp
72/87
Develop java code less jsp gives following advantages.
a) Increases readability of jsp.
b)
Improves the reusability of java code represented by tags.
c) Both java and non-java programmer can work easily and etc……
To develop jsp as scriptlet jsp we can use following tags.
o Html tag, jsp built-in tags, custom action tags, JSTL tags and third party supplies
tags.
Custom jsp Tag library:-
Terminology:-
a) Jsp Tag Library
It is a library that contains set of jsp tags. It is similar to java package.
There are three type of tag library.
a)
Jsp built-in tag libraries
b) Jsp custom tag libraries
c) Third party jsp tag libraries.
b) Tag handler class:
The java that extends from javax.servlet.jsp.tagext.TagSupport class and defines the
functionality of jsp tag.
a) TLD file
The xml file with extension .tld having the cfg jsp tags of jsp taglibrary like tag name,
tag handler class name, attributes and etc info.s
20-aug-15
Procedure to develop custom jsp tag library
Step-1) Design Jsp Tag library.
-
8/17/2019 Natraj Jsp
73/87
HCLTaglibrary
|------->,
Step-2) Develop tag handler classes in WEB-INF/classes folder
xyzTag.java
Package tags;
Public class Xyz extends TagSupport
{
Public class XyzTag extends TagSupport
{
//logic related to open tag, attributes and body processing
}
Public int doEndTag()
{
//executes for tag.//logic related to closing tag.
}
}
ABCTag.java
===========
public class ABCTag extends TagSupport
{
public int doStartTag()
{
:::::::::::::::::::::::::::::
}
}
Step-3) Develop tld file having configuration of jsp tags.
Note:- step-1 to step-3 indicates the development of jsp tag library.
WEB-INF/hcl.tld (xml file ===> Sample cole)
ABCABCTag.class
XYZXYZTag.class
Step-4) configure jsp tagLibrary in web.xml file having taglib uri.
(d)
-
8/17/2019 Natraj Jsp
74/87
demo//here demo is taglib uri
/WEB-INF/hcl.tld// /WEB-INF/hcl.tld is the name and
loaction of tld file (e)
Step-5) Use the tags of jspstaglibrary in jsp page/program.
Test.jsp
=========
---c----------
(b)(prefix taken
(a)
Note: - step-4 and step-5 talks about utilization of jsp tag library.
is useful touse jsp taglibraries in the jsp pages/program.
Follow of execution:
a)
In the execution of jsp the total h:abc tag is encountred
b)
Form that tag prefix “h” will be taken.
c) Based on the prefix the tag lib uri will be gathered.
d) And (e) Based on configuration done in web.xml file tld file will be gathered by using
taglib uri.
f) From tld file the name of the tag handler class will be gathered.
g) Containers calls doStartTag(), doEndTag() method of tag handler class. As call back
method to generate the output.
h) the generated output goes to browser through response, web server
En every tag handler clas we get the pageContext as
-
8/17/2019 Natraj Jsp
75/87
doStartTag(), doEndTag() are the call back methods of Tag Handler class. jspContainer
automatically calls these methods for every Open tag, closing tag encountering.
These method returns int constants giving instruction jsp container. They are
SKIP_BODY skip the evaluation of the tag.
EVAL_PAGE Evaluate the remaining jsp page.
SKIP_PAGE Skip the evaluation of total jsp page.
EVAL_BODY_INCLUDE Evaluate the tag by including the body.
For example application for custom jsp` tag library development refer page no:-282 of the
booklet.
The prefixes will use in jsp tag library are very useful to differentiate two tags belongingto two different tag library having same name.
21-Aug-15 EL( Expression Language)
In order to avoid java code in jsp we can use EL. It is specially useful to
perform arithmetical and logical operations without java code. It can be
used on template tag or it can used with any jsp tags like JSTL tags, customtags and etc………
Syntax:-
${……………}
o Ignore EL
o Does not Ignore EL
EL operators:Same as java
ELImplcit objects:-
Param
paramValues
header,
headerValues
-
8/17/2019 Natraj Jsp
76/87
cookie
initParam
requestScope
pageScope
SessionScope
appliationScope and etc…….
Note:- These object can be used along with a implicit object of jsp.
Sum is : ${4+5}
4>5? ${4>5}
request param usname value: ${param.uname}
Current browser name: ${header['user-agent']}
Request Attribute value:${requestScope.course}
Cookie name ${cookie.JSESSIONID.name}
Cookie value ${cookie.JSESSIONID.value}
For related info on EL refer page no 347 to 357
JSTL (jsp standard tag library):-
Writing java code in jsp is not industry standard, but built in tags are not sufficient,
custom tags development are very complex.
El is having limited scope of utilization in order to all these problems we can use JSTL.
JSTL tags are designed by SunMicro system as specification but all servers vendors are
providing the implementation in their own ways, so we can use all JSTL tags in a
common ways in our jsp pages……
If you work with JSTL tag write from variable declaration to database connectivity and
formatting of data can be done through tags.
23-aug-15 Annotations based servlet programming
Data about data is called Meta data. It is all about gathering info about the already
available info.
-
8/17/2019 Natraj Jsp
77/87
In java we can use multiple portions for MetaData operations.
a)
Using comments
//hold s person age
Private int age;
b)
Using modifier
Private static final int PI=3.14;
c)
Using xml file
Xml file gives good flexibility of modification, but gives bad performance.
Because to read and process xml file we need heavy weight xml parser.
d) An no ta tio ns :-
Annotations are java statement that can be place in java source code
directly.
Annotations give good performance but gives bad flexibility of
modification.
Resource configuration is also one kind of Meta data operation.
Eg: configuration of servlet program in web.xml file.
Annotation syntax:--
@(param1=val1,param2=val2,……….)
In java we have two types of annotations:-
a) An no ta tio ns fo r Do cu me nt at io n
Useful for api documentation.
Eg:- @author, @return, @param, @see, @since, and etc….
b) An no ta tio ns fo r program mi ng (from jdk 1. 5)
@Override( it indicate method is overridden method), @suppresswarning(it is
used to suppress warnings from compiler )…….
-
8/17/2019 Natraj Jsp
78/87
Servlet Annotations:-
Given from servlet api-3.0 (computable servers are : Tomcat 7,8)
Alternate to web.xml file based configuration like servlet configuration, filterconfiguration……….
If you configure certain thing by using annotation and xml file then the configuration
done in xml file will be overridden with annotation configuration or both are merge.….
As of now limited annotations are given in servlet api and they are adding annotations
in api incrementally.
o Servlet 3.x api pkg are
Javax.servlet, javax.servlet.http, javax.servlet.annotation, java.servlet.descirptor.
The servlet Annotations are :
@WebServletto configure servlet program
@WebFilterto configure servlet filter prog
@WebInitParam to configure servlet init param
@WebListenerto configure servlet listener
@HandlerTypes
@ServletSecurity
@Multipartconfig (Relegated to servlet security configurations
@HttpConstaint
@HttpMethodConstaint
To know the target area of applying annotation we can see api documentation of that
annotations and all the servlet annotations are class level annotation.
Application -19 of page 142.
-
8/17/2019 Natraj Jsp
79/87
Note: - While working with annotation if you specify value without parameter name
then that will go to parameter whose name is value.
23-Aug-15
JSTL =>
Jstl is providing 5 jsp tag libraries having set of tags in each tag libraries with tld files .
They are _
Core:- For Basic operations like variables decl, conditions,……
SQL ;- For DB interactions
XML :- for xml processing
Formatting : to Enable I18n (data formatting, number formatting )
Functions: TO manipulate Strings.
Every jstl tag library is identified with its fixed Uri which can be collected
from list
Corec.tldhttp://java.sun.com/jsp/jstl/core
SQLsql.tld /sql
Xmlx.tld /xml
Formattingfmt.tld /fmt
Functionsfn.tld /fn
All these tag liberties related tag handler classes, tld file and etc.
Are available in every server in the form of jar file…
They jstl.jar, standard.jar (Get form Tomcat installation).
For information about various jstl tag libraries and its tag, attribute refer page no -311
to 314.
JSTL core Tag Library:-
-
8/17/2019 Natraj Jsp
80/87
Given for basic operation to be done using tags like variable Declaration, conditions,
iterations and etc……
----……> like expression tag ( to display data).
----……> to declare variable with value in a scope.
----.> to remove variable from a scope…
JSTLAPP-1
|---->webcontent
|---->Test.jsp
Jars: jstl.jar, standard.jar….(deployment and assembly)
//”msg” is variable name “hello” is
value and “session” is scope “el” representing variable name
Message:
Message:
For more example on jstle Core tag library refer – 344 and 345.
C:if--->for if condition
C:forEach---> to iteration
C:forTokens>--->for String tokenization
, ---> for switch case.
--->for exception handling.
// here raised exception is stored in “e”
int a=Integer.parseInt("10");
-
8/17/2019 Natraj Jsp
81/87
-----> to import the content of destination resource to the source. (it is like
-----> to define url to use in url tag
From Main page:-
-
8/17/2019 Natraj Jsp
82/87
Jstl sql tag library is not really popular in real time because in real time jsp will be used
in the view layer(a/c to mvc2 architecture) and persistence logic is not required in the
view layer.
Formatting tag library:-
This tags are given to format data, number, label, according to local supporting according to
internalization (i18n).
Local means language +country.
o Eg:- en-us
o Fr-FR
o De-DE
o
Hi-IN ( hindhin as it specaks in india)
Making our application working for diff locals is called endabling I18n. Due to this our app
works for different customers of diff lcaes.
The formatting tags library tags are:
o poings to one local
o points to properties file (bundle file)
o TO display message according to label
o To format number
o
-> to format datao End etc…..
jstlApp2
|----->java resources
|----->src
|----->myfile.properites(base file)
|----->myfile_de_DE.properties(for Germany)
|----->myfile_fr_FR.Properties (for French)
|----->web content|----->Test
Note: - The base file name in all properties file must be same .
The keys in all properties file are must match and u can gather values by using
google translator.
-
8/17/2019 Natraj Jsp
83/87
Example:-
MyFile.properties:-
wismessage =”Good morning”.
Myfile_fr_Fr.proerties:-
Wishmessage=”some this called “
TestFormate.jsp
Uri= ………………………./core
-----------------------/fmt
30-Aug-15
Security in web application:-
It is middleware service/secondary service that protection to our application. Security deals
with.
a) Authentication:-
Check the identity of the user through username, password thumb impressions,
iris and etc….
b) Authorization:-
Checks the access permission of a user to access certain resources of the project.
Do not assign access permission directly to user names. Always assign access
permissions to user roles. Roles are like designation.
c) Data Integrity: -
Not allowing data being tampered while sending the data over the network is
called integrity. Rs 1000 should not become Rs 10000 while sending over the
network.
d)
Data Secrecy: -
Data must be accessed by the user for which it is intended to use i.e one usershould not use other users data. More ever data should send over the network
in an encrypted form.
Rajaoriginal data
Asbbckdb after encryption
-
8/17/2019 Natraj Jsp
84/87
raja after decription.
Only sender and receiver know inscription algorithm any one cannot misuse our data.
Servlet specification supports 4 modes of authentication:-
BASIC
DIGEST
FORM
CLIENT-CERT
We can enable the above authentication modes of security either in declarative mode or
programative mode.
In programmmitive mode we mainly write java in servlet and jsp program for authentication or
authorization.
In declarative approached everything will placed through xml file.
LDAP is providing password incription mechanism.(Light weight directly
access protocol.)
Security Realm is a context that maintains username, passwords which should be validated
while performing authentication.
We can configure security Realm.
a) Directly in the server.
b) As a flat file linked with the server.
c)
As database software linked with server.
d) As LDAP server linked with server.
LDAP Lightweight directory access protocol.
In LDAP the passwords will be stored as encrypted, so we cannot see the
password and modify the passwords, but we can reset the passwords.
If no name is given to realm the default name : myrealm.
Check:
Creating security realm in tomcat server directly(option-1)
In tomcat_home/conf/tomcat-users.xml
-
8/17/2019 Natraj Jsp
85/87
Basic mode of authentication:-
Uses Base64 encoding algorithm. Makes browser to give a standard dialog box asking
username, password. It works with all browser software
1 browser gives request to servlet.
2Container takes the request and notices that server is security enabled so request will not go
to servlet and container generates 401 status code based error response to browser.
3 upon receiving 401 status code response browser displays dialog box.
4 Dialog box submit the request having user name and password.
5 Container takes the request and validates user name, password against security realm if
found valid request goes to servlet.
6& 7 servlet process the request and sends response to browser.
For example basic/digest model refer:- page no:- 168, 169 application:- 30
DIGEST:-
Uses MD5 (Message digest) algorithm for encoding. Same as BASIC but browser gives a
different dialog box. Only few browsers and servers support this.
-
8/17/2019 Natraj Jsp
86/87
On form model:-
It is same as basic model but allows the user to form page asking user for username and
password instead of regular dialog box. Similarly allows to configure error page that should
displayed when authentication fail. All these configuration should be done in web.xml file’
By designing above from page the username text box should be j_username and password text
box should have name j_password and the action url must be j_security_check because the
servlet container receive the form data for authentication.
For example application on form page authentication page no:- 169, 169 application:- 301
Allows to configure digital certificate that are generated using some algorithm like RSA, varisign
and etc…
We configure this digital certificate with server by specifying https protocol to be used.
We cannot use this technique for authorization and authentication only for encryption by
sending data over the network so this technique can be combined with other technique.
https mean http over SSL. (Useful to establish secured connection between browser and server.
Procedure to work
1. Create digital certificate by using RSA.(Rivest, Sameer, Adalmen)
2. Ssl contains information about info about site and location and
etc………
How it works
o Browser gives request to server to an web resource program using https protocol server
sends digital certificate to browser browser recive install and digital and now
onwards the data send onward data send by client will be encrypted based on digital
certificate algorithm.
example:-
step-1) create digiatal certificate using RSA
c:\users\NIT> keytool – genkey – alias NIT – keyalg RSA
Note :- the above tool generate .keystore file as digital certificate in c:/users/nit folder. (nit is windows
user name)
o Configure the above digital certificate to tomcat server. By enabling https protocol.
o In \conf\server.xml
-
8/17/2019 Natraj Jsp
87/87
//protocol="Http/1.1"
Protocol=”org.apache.coyote.http11.Http11NioProtocol”
port = "8443" maxTHreads="200"
scheme="https" secure="true" SSLEnabled="true" clentAuth="false"
keystoreFile="c:/users/nit/.keystore" keystorePass="rajaraja"sslProtocol="TLS"/>
Step-3) starts the server:
Steep-4) Requests any web application of web server using http as shown below receive
install digital certificate.
/docs/ssl-howto.html#Indtrduction_to_SSL .
Step-5) https://localhost:8443/voterApp/input.html