Sei sulla pagina 1di 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)

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

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

Feature of jsp: Allows tags based programming.

Strong java knower is not required, so it is suitable for both java and

non-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

Strong java knowledge is not required so

for java programmers.

suitable for both java and non-java

programmers.
Does not supports tag based programming.

Supports tag based programming.

Modification will reflect only after

Will reflect without recompilation and

recompletion and reloading.

reloading.

Does not give implicit objects.

Gives implicit objects.(9)

Exception handling is mandatory.

Exception handling is optional.

Makes programmer to mix-up java business

Allows to separate the logic.

logic java code and presentation logic(html


code)
Configuration of prog in web.xml is mandatory. It is optional.
Note: - in the initial days programmers have used jsp as complete alternate to
servlet. But according to MVC architecture it is recommended to use both
servlets and jsp together in application development.
Jsp page compiler internally uses servlet API, jsp API while generating jsp class.
Jsp API is the extension of servlet API.
Servlet API will be used in the development of servlet container.
Jsp container internally uses ServletContainer so we can say jsp container is

developed based on both jsp API and servlet API.


Servlet api:- javax.servlet, javax.servlet.http, javax.servlet.annotation,
javax.servlet.descriptor.
Jsp api: - javax.servlet.jsp, javax.servlet.jsp.el, javax.servlet.jsp.tagext

In Tomcat sever: Servlet container name: catalinajar file : catalina.jar


Jsp container name: jaspser jar file: jasper.jar
Servlet api jar file: servlet-api.jar
Jsp api jar file :jsp-api.jar

Note: All these entire jar files are available in <tomcat_home>\lib folder.

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.

Place jspApp folder in <Tomcat_home>\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: <% java.util.Date d=new java.util.Date(); %>
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. config
7. session
8. page
9. pageContext
What is the difference between html and jsp?

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 so
the 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 -

o ABC_jsp.java , ABC_jsp.class and the location is

<Tomcat_Home>\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.

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.

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 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.

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

<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.

JSP COMMENTS (<%-- .. --%>)

3. DIRECTIVE TAGS/ELEMENTS
a. page directive (<%@ page attributes %>)
b. include directive (<%@ include attributes %>)
c. taglib directive (<%@taglib attributes %> )

4. STANDARD ACTION TAGS.


<jsp:include>
<jsp:forward>

<jsp:useBean>
<jsp:setProperty>
<jsp:params>
<jsp:param>
<jsp:plugin>
<jsp:fallback>
<jsp:text>
<jsp:attributes>

1. Scripting Tags:1. (a) Scriptlet:Standard syntax:<%....................(java code)


%>

Xml syntax:
<jsp:scriptlet>
...................

...................(java code)
</jsp:scriptlet>

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

<% int a=20; %>

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
<%
int a=20;
int b=30;
int c=a+b;

In JES class

public class ABC_jsp extends .


{

public void _jspService(-,-)


{

int a=20;

out.println(sum=+c);
%>

int b=30;

int c=a+b;

out.println(sum=+c);
}}

Using xml syntax:<b><i> Welcome to jsp </i></>


</br> </br>
<jsp:scriptlet>
Out.println(system date + new java.util.Date());
</jsp:scriptlet>

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

as xml sub tag.

out.println(a + is greater than+ b);

else

out.println(b + is greater than+ a);

]]>

</jsp:scriptlet>
SOLUTION-1:

Use standard syntax:


<%
..//same as above code
%>

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).

out.println(a + is less than+ b);

else

out.println(b + is less than+ a);

</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");

%>// 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

In JES class

<%

public void _jspService(-,-) throws

public int sum(int x,int y)

Se,IOE

return x+y;

public int sum(int x,int y)

return x+y;

%>// it will gives error because it will become


nested method in _jspService(-,-) method.

}
}

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 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,

class/interface definition (nested), jspInit(), jspDestroy() method


definitions and etc
Standard syntax:<%!
.
.
%>

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;

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.

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.
%>

We can place user defined method in declaration tag.


JSP program
<%! public int findBig(int x,int y)
{
if (x<y)
return y;
else
return x;
}
%>
<% out.println(Big value +
findBig(10,20));
%>

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.

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.
<web-app>

<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>

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 in
declaration 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

<%!class Test
}

%>

<%! interface xyz{


}%>

public class ABC_jsp extends HttpJspBase


class Test{}

interface xyz{}

<%! int counter=0;%>


<% counter++;

out.println(No of request:+counter); %>

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:-

<%= <Expression> %>

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(-,-)

the variable a value.

</b><% result :%> <%=a*a%>

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;
}
%>

<% int x=10,y=20;%>


Sum of: <%=x%> <%=y%>is <%=sum(x, y)%>
<% string s=hello how are you;%>

</br>

Length of <%=s> is <%=s.length()%>

Date and Time: <%=new java.util.Date()%>

Date and Time <jsp:expression>new java.util.Date()<jsp:expression>

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?

Step-1) configure tomcat 8 with eclipse ide.


Step-2) windowserverrun time environmentaddapache tomcat
8nextlocation of tomcat serverfinishok.
Step-3) create dynamic web project.
filenew dynamic web project
step-4) add first jsp to web content folder of the project.
<%! public String generateWishMessage(String uname)
{

//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 message

if(h<=12)

return Good morning+uname;


else if(h<=16)

return good after noon: +uname;

else if( h<=20)


return Good evening+uname;

else

return Good night: uname;


}

%>//end of declaration tag


<h1> Welcome to Jsp </h1><br>

Date and time is : <%=new java.util.Date()%>


//end of expression tag
<br>

<% String name=request.getParameter(uame);reads the request parameter value


%>
Wish messge:<%=generateWishMessage(name)%>
Request Url- http://localhost:3030/jspApp2/
Step-4) run the application.

27-Jul-15 (thr to fri)


Detailed Life cycle of jsp

Comment in jsp:-

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.


<%-- <%=a %> -- %>

Html comments are useful to comment html code/ tags of jsp prog.

These tags will be recognized by html interpreter.


<!-- <b>hello</b> -->

java comments are useful to comment java code of jsp program.


Theses comment is recognized by java compiler (javac).
<% int a=110;
//a=a*a;
%>
Comment
Visibility
.jsp
In JES
In JES
source
compiled

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

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.

<%!public void jspInit()


{

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()%>

JspWriter object of class name<%=out.getClass()%>


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, this
class is actually extends from JspWriter.

JspWriter out=new JspWriterImpl();

<Reference type>

<object type>

Html to jsp to DB s/w communication

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 ........................%>)

It provides Global info to jsp page.

b. Include directive (<%@include ..........%>)

It is use to include the content of destination file

c. Taglib Directive (<%@taglib...............%)

It is used to work with custom jsp tag.

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 %>

Attributes of page directive contentType=text/plain


Default value is text/html.
info=this is home page
No any default value

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)

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: <%@page contentType=text/plain%>
<%@page contentType=text/html,text/plain%>
<jsp:directive.page language=java contentType=text/html%>

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.

In JES class getServletInfo() method will be overridden having this short


description.

ABC.jsp

IN JES class

Emp Report %>

<%@page info=jsp page that gives


.

public String getServetInfo()


return jep page that gives emp Report;
}

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

<%@page extends=Test %>

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:

<%@page import=java.util.*,java.sql.* %>

<%@page import=jaav.sql.* import=java.util.*%>

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.

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:-

<%@page isThreadSafe=false %>//jsp is thread safe.

<%@page isThreadSafe=true %> //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.

<%@page buffer=10Kb %> //enable buffer.

<%@page buffer=none %> //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

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:-

<%@page buffer=5KB autoFlush=true %>

<%@page buffer=none autoFlush=false %>

<%@page buffer=none autoFlush=true %>

Gives exception indicating bad combo.


Does not gives exception, but not a good practice.

<%@page buffer=1kb autoFlush=false%>


<%for(int i=1;i<=1000000;++i)
out.println(hello);%>

Raise exception indicating Buffer over flow.

Any exception related to buffer is IOException


Note: we can also the buffer explicitly even though auto flush
is disable.

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

class object. This object is useful to

about current jsp page like request, response,

differentiate page directive tag variable from

session mode, error page, buffer size, autoFlush

scriptlet tag variable when both have got

mode and etc. we can use this object to create

same name.

page, request, session, application scope

In JES it looks like

In JES

Final java.lang.Object page=this;

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 %
<%..

//code that may raise exception


%>

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();%>

Note:- This implicit object exception is visible only in error page.

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

browser 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 <%@page %> for this.

Global error configuration:

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%>

Resource url: http://localhost:3030/jspApp4/Main1.jsp

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

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.

Directive include:<%@include file=...... %>


Xml Syntax:

<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.

Note: this tag does not use rd.include() internally.


<b><i>From the beginning of A.jsp</i></b>
<br />
<%@include file="B.jsp"%>
<br />
<b>end of jsp </b>

<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:

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.

Eg. <jsp:forward> <jsp:include> 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:-

<jsp:include page= flush=/>


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.

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()%>

What is the difference between


Directive

Action

Perform code inclusion

Perform output inclusion.

Performs inclusion at translation phase so

Performs output binding/inclusion at run

it is called static binding or compiles time

time so it is called dynamic binding

Does not use rd.include() internally.

Uses rd.include() internally.

This tag contains both standard, xml

Only xml syntax.

Does not allow servlet program as the

Allows

binding.

syntax.

runtime binding.

destination program.
Does not allow specifying destination page

Allows to specifies <%String

<% String destPage=B.jsp;%>

<jsp:include page=<%=destPage%>/>

through expression.

<%@include file=<%=destPage%>%>
(error)

It does not generate separate JES class if

destPage=B.jsp;%>

Not a error
Generates Separates JES class.

destination program is jsp program.


Useful when destination program is static

Useful when dest prog is Dynamic web

Eg:- html page.

Eg: servlet prog, jsp prog

web resource program.

resource program.

<table width="100%" height="100%">


<tr height="30%" >

<td colspan="2"><jsp:include page="/header"/></td>

</tr>

<tr height="60%">

<td width="30%"><%@include file="leftcontent.html"%></td>


<td width="70%"><jsp:include page="home.jsp"/></td>

</tr>

<tr width="10%"><td><%@include file="footer.html"%></td>


</tr>

</table>

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
jsps in a communication is called jsp chaining request/
dispatching/communication.

For this we can use <jsp:include>/<jsp:forward> 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.
<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=/>

o Note: there is no directive forward tag.

A.jsp

<b> from the start of A.jsp </b>


<br>

<jsp:forward page=B.jsp/>
<br>

From end of A.jsp


B.jsp

<b> form B.jsp</b><br>

Date and time: <%=new java.util.Date()%>


In servlet programming the statement placed after rd.forward() in source servlet
program will be executed but there html output will be discarded.

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.

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;.
<jsp:param>
Can be used as the sub tag of <jsp:include> /<jsp:include>

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

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

<%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.

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 jsps 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
o

pageContext.setAttribute(attr1,val1);//here attr1 is attribure name and val1 is value.


creates attr1 as page scope attribute.
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() method


o

same setAttribute() method.

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 recommended


to 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

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 <jsp:param> 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 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

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.
<jsp:plugin> tag internally uses <embed> or <object> tag and <jsp:fallback> tag
internally uses <noembded> 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

<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

public class TestApp extends Applet


{

Pubic void paint(Graphics g)


{

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 serlet
and cll various setXXX(0,0) and getxxx(-,-) methods.
For jsp to jsvaBean communication we can use
o <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>, <jsp:setPropery> tags ..
Example java Bea
-----Public class StudentBean
{

Private int sno;


Private String name;

Private String address;


{

//getter and setter


}}

<jsp:useBean>
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 <jsp:useBean id=st class=com.nt.StudentBean scope=session/>

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:<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

Attributes:name= Bean id(id attribute values of <jsp:useBean> 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:- <jsp:setProperty name=st property=sno value=101
Assign value 101 to sno property by calling st.setSno(-) method.
Eg2: <jsp:setProperty name=st property=sname param=stname/>
Reads the stname req param value and assign that value to sname property by calling
st.setSname(-) method.

<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.

<jsp:getProperty name=st property=sno/>


Reads and displays sno property value.
If you want to use java class or java bean in a jsp that shuld be placed either parallel to jsp or in a
cackage of WEB-INF\classes folder, But we prefer placing in a pkg of WEB-INF/classes folder
because we can even use that in servlet prog
jspApp12(EDWP)
|---------->java resources
|---------src
|---------com.nt
|---------studentBean.java
|---------webcontent
|---------setValues.jsp
|---------getValues.jsp

|---------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()

{
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)

Checks format, pattern of from data(main logic that generate


result)

Form validation logic.

B.logic/service logic/request processing logic


The logic that gives user interterface.
Presentations logic

Logic that performs database operation example jdbc code.

Cookies, hidden form fields and etc)

Additional services like security, logging, pooling and etc..)

Session management logic


Middleware services.

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

separation 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

(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.

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 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.

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

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 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);
}

Where did we use javaBean in real project.

a) As DTO class to send from one layer to another layer


b) As VO class to represent multiple input values in an object.
c) As BO class while supplying input to persistence logic while gathering outputs
from persistence logic in the form of object.
d) As BO class or helper class while transferring ResultSet record to collection.
e) As model layer component in MVC-1, MVC-2 application.
f) As domain class in hibernate programming.
g) To maintain multiple value as single session attribute values in session tracking.
Where did you use collection in project?

We ArrayList to send ResultSet record over the network.


While gathering jdbc properties from outside file we use java.util.Properites.
We use java.util.Properties to maintain the mail properties.
We use HashTable to maintain JNDI properties.

We use HashMap or Hashtable as buffer or cache.


We use in collection in session tracing to maintain multiple values as single
session attribute values.

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

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.

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.

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)

<taglib-uri>demo</taglib-uri>//here demo is taglib uri


<taglib-location>/WEB-INF/hcl.tld</taglib-location>// /WEB-INF/hcl.tld is the name and
loaction of tld file (e)
</taglib>
</jsp-config>
</web-app>
Step-5) Use the tags of jspstaglibrary in jsp page/program.

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.

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 belonging
to 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, 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}

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.

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) Annotations:

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:--

@<annotation>(param1=val1,param2=val2,.)

In java we have two types of annotations:a) Annotations for Documentation

Useful for api documentation.


Eg:- @author, @return, @param, @see, @since, and etc.

b) Annotations for programming (from jdk 1.5)


@Override( it indicate method is overridden method), @suppresswarning(it is
used to suppress warnings from compiler ).

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

(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.

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.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.

Are available in every server in the form of jar file

They jstl.jar, standard.jar (Get form Tomcat installation).

/sql
/xml
/fmt
/fn

For information about various jstl tag libraries and its tag, attribute refer page no -311
to 314.

JSTL core Tag Library:-

Given for basic operation to be done using tags like variable Declaration, conditions,
iterations and etc

<c:out>----> like expression tag ( to display data).

<c:set> ----> to declare variable with value in a scope.

<c:remove>----.> to remove variable from a scope

JSTLAPP-1
|---->webcontent
|---->Test.jsp
Jars: jstl.jar, standard.jar.(deployment and assembly)
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>

<c:set var="msg" value="hello" scope="session"/>

//msg is variable name hello is

value and session is scope el representing variable name


Message: <c:out value="${msg}"/>

<c:remove var="msg" scope="session"/>


Message:<c:out value="${msg}"/>

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

<c:choose>, <c:when> ---> for switch case.


<c:catch> --->for exception handling.

<%@taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>

<c:catch var="e" >// here raised exception is stored in e


<jsp:scriptlet>

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"%>

From Main page:<c:import url="abc.html"/> <!-gets abc.html file's output ocntent->

<a href="<c:url value="http://localhost:3030/JSTLApp1/abc.html/>"> go</a>

<c:redirect> performs send redirection by using response.sendRedirect(-) method.


<%@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).

Local means language +country.


o

Eg:- en-us

Fr-FR

De-DE

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

<fmt:setLocal>poings to one local

<fmt:setBundle> points to properties file (bundle file)

<fmt:message> TO display message according to label

<fmt:formatNumber> To format number

<fmt:formatData> -> to format data

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.

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 user
should not use other users data. More ever data should send over the network
in an encrypted form.
Rajaoriginal data
Asbbckdb after encryption

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.
LDAPLightweight 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
<role rolename="clerk"/>

<role rolename="manager"/>

<user username="raja" password="tomcat" roles="clerk"/>

<user username="ravi" password="tomcat" roles="manager"/>

<user username="anil" password="tomcat" roles="clerk,manager"/>


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.

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.

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

Potrebbero piacerti anche