Natraj JSP
Natraj JSP
Natraj JSP
Client side web Technology: (useful to develop client side web resource program/components)
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 a
server 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
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.
17-jul-15
Strong java knower is not required, so it is suitable for both java and
non-java programmers.
Gives 9
implicit objects.
(java code).
The modification done in jsp will be reflected without any
tag.
Easy to learn and use.
Exception handling is optional.
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.
Servlet
Jsp
programmers.
Does not supports tag based programming.
reloading.
Note: All these entire jar files are available in <tomcat_home>\lib folder.
will be generated through template text and the dynamic values will be
generated through java code of scriptlet.
20-Jul-15
Q: - How many object can be there in jsp?
Html
Jsp
<Tomcat_Home>\localhost\jspApp\org\apaceh\jsp
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.
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.
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.
processing phase if the source code of jsp page/program is not modified when
compared 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.
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 not
participate 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.
ii.
configure in web.xml file and Access jsp prog either through servlet/servlet filter.
o Example
<web-app>
<servlet>
<servlet-name>A</servlet-name>
<jsp-file>/WEB-INF/pages/ABC.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>A</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
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.
3. DIRECTIVE TAGS/ELEMENTS
a. page directive (<%@ page attributes %>)
b. include directive (<%@ include attributes %>)
c. taglib directive (<%@taglib attributes %> )
<jsp:useBean>
<jsp:setProperty>
<jsp:params>
<jsp:param>
<jsp:plugin>
<jsp:fallback>
<jsp:text>
<jsp:attributes>
Xml syntax:
<jsp:scriptlet>
...................
...................(java code)
</jsp:scriptlet>
In jsp
in JES class
int a=20;}}
We can use scriptlet for placing request processing logic, because its code
In JES class
int a=20;
out.println(sum=+c);
%>
int b=30;
int c=a+b;
out.println(sum=+c);
}}
While working with less than symbol < in the xml syntax of scriptlet we need to be
very careful because if we place less than symbol < as the body of the tag, it will be
treated as xml meaning sub-tag, and it will not treated as java conditional operator.
<jsp:scriptlet>
<![CDATA[
int a=20;
int b=30;
if(a<b) // here < will not be treated as java conditional operator and will be treated
else
]]>
</jsp:scriptlet>
SOLUTION-1:
SOLUTION-2:
Use
<![CDATA[.]]> support
<jsp:scriptlet>
<![CDATA[ //it will suppress the xml meaning on the body of the tag and takes
the body as ordinary text (java code), so < will be treated as the conditional
operator.
.
.
]]>
</jsp:scriptlet>
But greater than symbol does not have such problem:
<jsp:scriptlet>
int a=20;
int b=30;
if(a>b).
else
</jsp:scriptlet>
NOTE: - less than symbol is not there with standard syntax and greater than symbol not
problem in any syntax.
goes this
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.
<%
out.println(request.getHeader("user-agent");
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
In JES class
<%
Se,IOE
return x+y;
return x+y;
}
}
Note: - we cannot place interface definition in a method definition that mean we cannot place
interface definition in scriptlet.
We can place interface definition inside the class and class definition
inside the interface.
1. (b) Declaration Tag: The code placed in Declaration tag goes outside to _jspService method of JES class.
So we can use this tag for global variables declaration, method definition,
Xml syntax:-
<jsp:declaration>
.
.
</jsp:declaration>
Variable declared in Declaration tag will come as global variable of JES class.
In JES
In JES class
%>
int a=10;
}
Q: - How can we differentiate declaration tag variable from scriptlet tag variable
being from scriptlet when both have got same name.
23-Jul-15
Ans:- Use either implicit object page or this as shown below:<% int a=30; %>
<%! int a=20;
out.println(<br> local a value +this.a);
ABC_jsp o1=(ABC_jsp)page;
//out.println(<br> Local a value +this.a);
out.println(<br> global a value +o1.a); // it is not recommended because it demands
typecasting
//with JES class that changes server to server.
%>
In JES class
publc class ABC_jsp
{
public void _jspService(-,-)
{ out.println(Big value + findBig(10,20));
}
public int findBig(int x,int y)
{
if (x<y)
return y;
else
return x;
}
}
While working with xml based declaration tag there is a possibility of getting problem with less
than< symbol use
<![CDATA[.]]>
<jsp:declaration >
<![CDATA[public int findBig(int x,int y)
{
if (x<y)
return y;
else
return x;
}]]>
</jsp:declaration>
<% out.println(Big value + findBig(10,20));%>
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.
<%! public void jspInit()
{
System.out.println("jspInit()");
}
<%! public void jspDestroy()
{
System.out.println("jspDestroy()")
}
%>
<% System.out.println("_jspDestroy(-,-)%>
jspInit() useful to place the initialization logic of program like crating jdbc
connection.
jspDestroy() useful to place the un-initialization logic of programmer like closing
jdbc connection.
_jspServce(-,-) useful to place request processing logic.
_jspInit() contains JES class related predefined initialization logic.
_jspDestroy() contains JES class related predefined un-initialization.
Q: - can we place servlet life cycle methods directly in jsp program using
declaration tags?
Ans) No, Not possible because all these methods are declared as final methods in the
super class of JES class that is HttpjspBase class in Tomcat server and final methods of
super class cannot be overridden in sub-class.
Q :- what is the advantage of enabling load-on-startup on jsp page?
Ans: - The container performs the following operations either during server startup or
during deployment of web application.
<servlet>
<servlet-name>a</servlet-name>
<jsp-file>/ABC.jsp</jsp-file>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
</web-app>
JES class
<%!class Test
}
%>
interface xyz{}
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:-
<jsp:expression>
</jsp:expression>
We can use expression tag to display variable values.
<% int a=20;
out.println(<b> value=+a+</b>);
%> Bad practice because we are mixing up html code and java code
<%int a=10; %>
<b> value =</b><%a=%>
Here <%a=%> will display variable a value.
Jsp program
<% int a=10;%>
<b>value : <%=a%><br>---display
JES class
public class ABC_jsp extends
{
public void _JspService(-,-)
int a=10;
out.print(<b> value:</b>);
out.print(a);
out.pritn(<br>);
out.println(<b>result</b>);
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
%>
In JEs class:
out.println(Browser);
Name:<%=request.getHeader("user-
out.println(request.getHeader(user-
agent");
agent));
We can use expression tag to call both pre-defined and user-defined methods but those
methods must return value.
<%! public int sum(int x,int y)
{
return x+y;
}
%>
</br>
Even <![CDATA[..]]> cannot solve the < symbol that raise with xml syntax of
expression tag.
Date and Time <jsp:expression><![CDATA[ 10<5]]> //here is < problem which can
not be solved by using CDATA
</jsp:expression>
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.
<%=a*a a*a*a%> //wrong
<%=a*a,a*a*a%> //wong
<%=a*a+ + a*a*a %>// 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?
int h=c1.get(java.util.Calendar.HOUR_OF_DAY);
//generate wish message
if(h<=12)
else
Comment in jsp:-
Html comments are useful to comment html code/ tags of jsp prog.
Code that
goes to
browser
No
Jsp comment
Yes
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.
Technically speaking in jsp implicit object are not there but implicit reference
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
ServletConfig cg=getServletConfig();
String s1=cg.getInitParameter(driver);
ServletContext sc=getServletContext();
String s2=sc.getInitParameter(user);
Sop(s1+ +s2);
}
%>
<web-app>
<context-param>
<param-name>user</param-name>
<param-value>scott</param-value>
</context-param>
<servlet>
<servlet-name>a</servlet-name>
<jsp-file>one.jsp</jsp-file>
<init-param>
<param-name>p1</param-name>
<param-value>val1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>A</servlet-name>
<url-pattern>/test1</url-pattern>
</web-app>
</servlet-mapping>
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 variables
pointing 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<%=respose.getClass()%>
Request object classname<%=request.getclass()%>
<Reference type>
<object type>
For html to jsp communication we need to use jsp file or url pattern as href value of
<a> tag or action attribute values of <form> 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.
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
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 (<%@page ........................%>)
Page Directive
To provide global info of jsp page like package imports, buffer size, content type and
etc
Standard syntax
<%@page attributes %>
Xml syntax
<jsp:directive.page attributes %>
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
<%@page language=java%> (valid)
<%@page language=c%> (invalid)
session : It specifies whether the implicit object session should be created or not.
<%@page session=true%>
Create implicit object session
<%@page session=false%>
Does not create implicit object session default values: true.
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.
ABC.jsp
IN JES class
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.
Jsp
In JES class
import:
Example:
isThreadSafe:
The jsp page that allows one request/thread at a time is called thread
safe jsp.
By default jsp page is not thread safe because the default value of
isThreadSafe attribute is true.
Example:-
PrintWriter
JspWriter
Supports buffering
Note: - When buffering is disable in jsp (buffer=none) the jsp writer internally uses
PrintWriter object to write the content.
autoflush
autoFlush=ture
autoFlush=false
disable autoFlushing.
Example:-
03-aug-15
With the utilization of buffer while transferring data from source file to destination
file. We can reduce no of write operation on source file and number of writer
operant on destination file.
What is the difference between implicit object page and pageContext?
Page
page hold this i.e. reference of current JES
pageContext
pageContext object holds multiple details
same name.
In JES
attributes.
pageContext=_jspxFactory.getPageContext(this.
request,response,err.jsp,false,8192,true);
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).
${<Expression>}
isELIgnored specified whether EL in jsp should be recognized or ignored.
<%@page isELIgnored=true %>
Sum is :${1+2} ouput is Sum is :$(1+2)
<%@page isELIgnored=false %>
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
<%@page isErrorPage=true %>
<%=exception.getMessage();%>
Exception handling in jsp Or error page configuration in jsp:Note: Even though JES takes care of exception handling it display technical, ugly message on
Common for all jsp program/pages of web application use <errorpage> tag of web.xml file.
Main.jsp
<%@page errorPage="err.jsp" %>
<% int a=Integer.parseInt("a10"); %>
Value :<%=a %>
err.jsp
<%@page isErrorPage="true" %>
<b> internal Problem . Try again !!!!</b>
Message : <%=exception.getMessage() %>
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 we
need 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 <error-page> tag web.xml file.
JspApp4
|----------------------->WEB-INF
|------->Main1.jsp |------->web.xml
|------->Main2.jsp
|------->error.jsp
<web-inf>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/err.jsp</location>
</error-page>//error page configuration for any exception
raised in jsp pages
</web-inf>
<%@page isErrorPage="true"%>
<br>
<font color='red'>Internal problem. Try again</font>
<br>
<br>
<%=exception.getMessage()%>
<b>from Main1.jsp</b>
<%int a=Integer.parseInt("a10")%>
Value=<%=a%>
<b>From Main2</b>
<%java.util.Date d=null;
int month=d.getMonth();%>
<br>
current month is: <%=month%>
Note: we can place multiple <error-page> 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
<jsp:directive.include file=../>
Includes the content/code of Destination file to the code of source jsp pages in JES class
at translation phase. Separate execution does not take place for Destination
page/file/program.
No JES class will be generated for B.jsp but B.jsp code will be included to the JES class of A.jsp.
<b>from b.jsp</b>
<%=new java.util.Date()%>
Note:- in the above example in the JES class of a.jsp contains the code of A.jsp and B.jsp.
Action tag:
Action include:Syntax:-
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.
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
<b>From the begnig A.jsp</b>
<br />
<jsp:include page="B.jsp" flush="true"/>
<br />
<b>End of</b>
<br />
<b>From B.jsp</b>
<%=new java.util.Date()%>
Action
Allows
binding.
syntax.
runtime binding.
destination program.
Does not allow specifying destination page
<jsp:include page=<%=destPage%>/>
through expression.
<%@include file=<%=destPage%>%>
(error)
destPage=B.jsp;%>
Not a error
Generates Separates JES class.
resource program.
</tr>
<tr height="60%">
</tr>
</table>
Taking request from client and processing that request by using multiple
jsps in a communication is called jsp chaining request/
dispatching/communication.
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.
<jsp:forward> ====> perform forwarding request operation
<jsp:include>==> perform including response operation .
<jsp:forward>
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 <jsp:forward> in source jsp page as a conditional
statement to execute.
Syntax:-
<jsp:forward page=/>
A.jsp
<jsp:forward page=B.jsp/>
<br>
In jsp programming statement placed after <jsp:forward> 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.
07-Aug-15
Some points are left :A.jsp
<jsp:forward page=b.jsp>
<jsp:param name=p1 value=val1/>//val1 is param
values <jsp:param name=p2 value=val2/>//val2 is
paramvalue
<jsp:forward page=b.jsp>
B.jsp
Additional req param values: <%=req.getPrameter(p1)%>
<%=req.getParameter(p2)%>
Bill.jsp uses <jsp:forward > tag to forward the control to discount.jsp and it also uses
jsp:param tag to pass bill amount to Discount.jsp
<%response.sendRedirect(http://www.google.co.in);%>
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.
Use jsp:forward, jsp:include tags when source jsp and destination jsp programs are local
to each other.
Use response.sendRedirect() method when destination page is unknown technology
based web resource program.
If we place multiple jsp include in one jsp then the output of multiple destination will
be included.
If you place multiple jsp:forwared in one jsp then first jsp:forward tag effect will
takes place.
If you place multiple response.sendRedirect method exception will be raised.
If we place jsp:forward before response.sendRedirect then the effect of jsp:forward tag
takes place. Otherwise exception will raised.
What is diffente bw jsp:fowared and response.sendRedirect?
Refer the difference rd.forward and response.sendRedirect
08-Aug-15
In servlet/jsp program attribute is a logical name that holds values. Attributes are useful
to pass data between web resource programs.
request attribute scope is request scope i.e they are specific to each request.
session attributes scope is session i.e they are specific to each browser.
application attribute scope is application scope i.e they are visible with in the
application.
String s2=(String)pageContext.getAttribute(attr2,pageContext.SESSION_SCOPE);
//get attr2 vales from session scope
pageContext.removeAttribute(attr2),pageContext.SESSION_SCOPE);
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.
If source jsp page and destination program reside in the same web application
If source jsp page and destination program reside in two different web
application
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 <jsp:fallback/> 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)
<jsp:plugin>
If applets are used to display/design animation/logos then <jsp:plugin> is useful. This
tag attributes are:
type->applet/bean
width->
<jsp:params>,<jsp:param> tag.
Pluging.jsp
<jsp:plugin type=applet code=TestApp.class
codebase-/jspApp11
width-300
height=400>
<jsp:params>
<jsp:param name=orgName value=Niit/>
</jsp:params>
</jsp:plugin>
TestApp.java
String name=getParameter(orgName);
//super class method can directly called in sub class directly getParameter() is paint class
method.
g.drawString(name,200,200);
}
}
<jsp:useBean>
Useful to create /locate bean class object.
o Attributes
scope page/request/session/application
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:<jsp:useBean id=st type=com.nt.Person class =com.nt.studentBean scope=page/>
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.
11-Aug-15
calls setxxx() of java bean class to set given values to bean properties.
o
<jsp:getProperty>
Reads and display bean property values by calling getxxx() method.
Attributes:
Name= bean id
Property = bean property name or xxx of getxxx() method.
|---------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.
{
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
Model-1
Here we use either only servlets or only jsp to
develop java application, i.e if servlets are used
in web application the jsp will not be used any
vice versa.
Model-1 architecture is mainly using jsp
Model-2
application.
Here every main web resource pro like
servlet/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 clean
MVC
MModel Layer represents B.logic +persistence logic. (Accountants
(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.
13-aug-15
MVC-2 rueles/principle
Every layer is designed to have specific logic so just place those logic and dont 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 etcoperations.
Can we change the roles of various technologies uses in MVC-2 architecture based
application?
Servlet as view:-
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.
Project: Add rotator. This application display advertisements in the web pages.
There are three type of adds :a) Sequential advertisements
b) Random advertisements
c) Direct advertisements
Eg: while searching for seven wonders it displays adds about tours
and travels)
jspApp13:
|------->java resources
|
|------->com.nt
|------->Rotator.java (bean class)
|------->webcontent
|------->Addrotator.jsp
|------->1.jpg, 2.jpg, 3.jpg
|------->WEB-INF
|------->web.xml
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 nonsynchronization 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 cant place each record of ResultSet to each
element of ArrayList
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<Student> al=new ArrayList<Student>();
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);
}
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.
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.
a) Response downloading:
b) Resource downloading:
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.
20-aug-15
Procedure to develop custom jsp tag library
Step-1) Design Jsp Tag library.
HCLTaglibrary
|-------><ABC>,<xyz>
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 </XYZ> 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)
ABC<-------->ABCTag.class
XYZ<-------->XYZTag.class
Step-4) configure jsp tagLibrary in web.xml file having taglib uri.
<web-app>
<jsp-config>
<taglib> (d)
Test.jsp
=========
<%@taglib uri="demo" prefix="st"%>
---c----------
(b)(prefix taken
<h:ABC/>
(a)
<h:XYZ/>
Note: - step-4 and step-5 talks about utilization of jsp tag library.
<%@taglib %> 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
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.
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, custom
tags and etc
Syntax:
${}
<%@page isELIgnore = true>
o Ignore EL
<%@page isELIgnore = false>
o Does not Ignore EL
EL operators:
Same as java
ELImplcit objects: Param
paramValues
header,
headerValues
cookie
initParam
requestScope
pageScope
SessionScope
appliationScope and etc.
Note:- These object can be used along with a implicit object of jsp.
<%@page isELIgnored="false"%>
Sum is : ${4+5}<br>
4>5? ${4>5} <br>
request param usname value: ${param.uname}<br>
Current browser name: ${header['user-agent']}<br>
<%
request.setAttribute("course","java");
%>
Request Attribute value:${requestScope.course}<br>
Cookie name ${cookie.JSESSIONID.name}<br>
Cookie value ${cookie.JSESSIONID.value}
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
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) Annotations:
Annotations are java statement that can be place in java source code
directly.
@<annotation>(param1=val1,param2=val2,.)
Servlet Annotations: Given from servlet api-3.0 (computable servers are : Tomcat 7,8)
Alternate to web.xml file based configuration like servlet configuration, filter
configuration.
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
@WebListener to configure servlet listener
@HandlerTypes
@ServletSecurity
@Multipartconfig
@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.
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 _
Every jstl tag library is identified with its fixed Uri which can be collected
from list
Corec.tld http://java.sun.com/jsp/jstl/core
SQL sql.tld
Xml x.tld
Formatting fmt.tld
Functions fn.tld
All these tag liberties related tag handler classes, tld file and etc.
/sql
/xml
/fmt
/fn
For information about various jstl tag libraries and its tag, attribute refer page no -311
to 314.
Given for basic operation to be done using tags like variable Declaration, conditions,
iterations and etc
JSTLAPP-1
|---->webcontent
|---->Test.jsp
Jars: jstl.jar, standard.jar.(deployment and assembly)
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
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
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
int a=Integer.parseInt("10");
</jsp:scriptlet>
</c:catch>
<c:out value="${e}"/>
<c:import> -----> to import the content of destination resource to the source. (it is like
<@include>
<c:url> -----> to define url to use in url tag
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
<c:redirect rul="https://www.google.com"/>
SQL:o Here the tags given for DB interaction , to interact with DB s/w and to amaniputlate
DB data.
o <sql:setDataSource> to establish the connection
o <sql:query> to execute the select query.
o <sql:update> to execute the non-select query.
o <sql:param> to set param (?) value to Query.
o <sql: transaction><sql:update> tag should be uased under this tag.
o <sql:dataParam>to date values to query params.
For Example application 345 and 346.
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).
Eg:- en-us
Fr-FR
De-DE
Making our application working for diff locals is called endabling I18n. Due to this our app
works for different customers of diff lcaes.
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.
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 user
should not use other users data. More ever data should send over the network
in an encrypted form.
Rajaoriginal data
Asbbckdb after encryption
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.
Security Realm is a context that maintains username, passwords which should be validated
while performing authentication.
<role rolename="manager"/>
Uses Base64 encoding algorithm. Makes browser to give a standard dialog box asking
username, password. It works with all browser software
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.
Uses MD5 (Message digest) algorithm for encoding. Same as BASIC but browser gives a
different dialog box. Only few browsers and servers support this.
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.
Configure the above digital certificate to tomcat server. By enabling https protocol.
In <Tomcat_home>\conf\server.xml
<connector>
//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"/>
</connector>
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" 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