You are on page 1of 25

Limitations with servlets

Strong java knowledge is required to work with servlets.


Not suitable for non java programmers.
It does not give implicit objects.
Allow us to handle the exception.
If any modification is done in source code of servlet program will reflect when we recompiled
the servlet program or reloading the web application.
Configuration of servlet program in web.xml file is mandatory.

Advantages of jsp
It gives tag based programming.Suitable for both java and non java programmers.
It gives 9 implicit objects(built-in object).An object which is used directly without configuration
explicitly.
Request and response is not a implicit objects.
super and this is a implicit objects/ref variable of java app.
It allows us to develop custom tags and to work with third party supplied tags.
Handling an exception is always optional.
Configuration of web.xml is optional.

It is easy to learn and easy to use.

Gives all the features of servlets.

Note:
All Industries uses jsp and servlets to develop web applications. Procedure to develop and
deployed JSP program based web application

Create deployment directory structure.

1
Diagram:

ABC.jsp
<br><i>Date and Time </i></br>
<% java.util.Date d=new java.util.Date();
out.println(d.toString()); %>
<br><br>
End of jsp program.....

web.xml
<web-app/>

Note:
We don't need to compile jsp program so we don't need to add any jar file in "CLASSPATH"
environmental variables.

request url
http://localhost:2525/JspApp/ABC.jsp

Configuration of web.xml file


<web-app>
<servlet>
<servlet-name>abc</servlet-name>

2
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
</web-app>

How can we hide jsp programe getting accessible through file name(it means how can we access
jsp program by using url pattern)

we should place ABC.jsp file inside WEB-INF folder.

Diagram:

In web.xml
We need to configure
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<jsp-file>/WEB-INF/index.jsp</jsp-file>

3
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
</web-app>

Life cycle of servlet program


 init(ServeltConfig sc) is used to for instantiation event.
 service(HttpServletRequest req,HttpServletResponse res)is used for request arrival event.
 destroy() is used for destruction event.

Life cycle of jsp program


_jspinit() is used to perform instantiation event(just before creating JES class object).
_jspService() is used to perform request arrival event(before request comes to jsp program).
_jspDestroy() is used to perform destruction event(just fore destroy the JES class object).

Note:
All life cycle methods of jsp program will executed through life cycle methods of Servlet
program.

4
Life cycle of jsp diagram
Diagram:1

_jspinit() is used to perform initialization like opening jdbc objects(Connection,Statement ,ResultSet and
etc).

_jspService() is used to create webpages.

_jspDestroy() is used to perforn unintialization of jdbc objects(closing all jdbc objects).

In tomcat server JES class object will be created(ABC.jsp.class and ABC.jsp.java) in work folder
dynamically.

ex:

D:\Tomcat 6.0\work\Catalina\localhost\JspApp\org\apache\jsp.

By default JES class will give only one life cycle method that is _jspService(),but we can see _jspInit() and
_jspDestroy() in JEs class but these methods are helper methods.

5
Phases of Jsp program
Every jsp program having two phases

1)Translation phase

Our jsp program converts to equivalent Servlet program(JES class).

(ABC.jsp.class and ABC.jsp.java)

2)Request arrival phase

Our JES class executed and output is sends to browser window.

Diagram:2

Q) How to enable load on startup, What happen when we do load on startup?

Ans:

<web-app>

6
<servlet>

<servlet-name>abc</servlet-name>

<jsp-file>/ABC.jsp</jsp-file>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>abc</servlet-name>

<url-pattern>/test1</url-pattern>

</servlet-mapping>

</web-app>

Our Jsp program container will complete Translation phase during server startup or during deployment
of web application.

jsp container performs initialization and instantiation of JES class object during server startup or during
deployment of web application.

Jsp tags/elements

Scripting tags
It is used to place java code

1)scriptlet tag

ex:
---
<% %>

2)Declaration tag

ex:

---

<%! %>

3)Expression tag

ex:

7
--

<%= %>

jsp comments

<%-- %>

Directive tags

1)Page directive
ex:
<@page attribute>
2)Include directive
ex:
<@include attribute>
standard tags

<jsp:include>

<jsp:forward>

<jsp:getProperty>

<jsp:setProperty>

<jsp:param>

<jsp:params>

<jsp:body>

<jsp:text> and etc.

SP scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
Syntax is as follows:
<% java source code %>

8
Example of JSP scriptlet tag that prints the user name
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. Enter username:<input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression tag

<%= statement %>


Note: In expression tag no statement should end with semicolun(;).
Example of JSP expression tag that prints current time

9
index.jsp

1. <html>

2. <body>

3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>

4. </body>

5. </html>

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods

Example of JSP declaration tag that declares field

index.jsp

1. <html>

2. <body>

3. <%! int data=50; %>

4. <%= "Value of the variable is:"+data %>

5. </body>

6. </html>

Example of JSP declaration tag that declares method

index.jsp

1. <html>

2. <body>

3. <%!

4. int cube(int n){

5. return n*n*n;

10
6. }

7. %>

8. <%= "Cube of 3 is:"+cube(3) %>

9. </body>

10. </html>

Exception Handling in JSP


The exception is normally an object that is thrown at runtime. Exception Handling is the
process to handle the runtime errors. There may occur exception any time in your web application. So
handling exceptions is a safer side for the web developer.

In JSP, there are two ways to perform exception handling:

1. By errorPage and isErrorPage attributes of page directive

2. By <error-page> element in web.xml file

Example of exception handling in jsp by the elements of page directive

There are 3 files:

• index.jsp for input values

• process.jsp for dividing the two numbers and displaying the result
• error.jsp for handling the exception

index.jsp

1. <form action="process.jsp">

2. No1:<input type="text" name="n1" /><br/><br/>

3. No1:<input type="text" name="n2" /><br/><br/>

4. <input type="submit" value="divide"/>

5. </form>
process.jsp

1. <%@ page errorPage="error.jsp" %>

11
2. <%

3.

4. String num1=request.getParameter("n1");

5. String num2=request.getParameter("n2");

6.

7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);

9. int c=a/b;

10. out.print("division of numbers is: "+c);

11. %>

error.jsp
1. <%@ page isErrorPage="true" %>

2.

3. <h3>Sorry an exception occured!</h3>

4.

5. Exception is: <%= exception %>

Example of exception handling in jsp by

Specifying the <error-page> element in web.xml file.This approach is better because you don't
need to specify the errorPage attribute in each jsp page. Specifying the single entry in the
web.xml file will handle the exception
There are 4 files:

• web.xml file for specifying the error-page element

• index.jsp for input values


• process.jsp for dividing the two numbers and displaying the result
• error.jsp for displaying the exception

12
1) web.xml file if you want to handle any exception

1. <web-app>
2.
3. <error-page>
4. <exception-type>java.lang.Exception</exception-type>
5. <location>/error.jsp</location>
6. </error-page>
7.

8. </web-app>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

1.<%@ page attribute="value" %>

Attributes of JSP page directive

• import

• contentType

• extends

• info

• buffer

• language

• isELIgnored

• isThreadSafe

• autoFlush

• session

13
• pageEncoding

• errorPage

• isErrorPage

1)import
The import attribute is used to import class, interface or all the members of a package.It is
similar to import keyword in java.

Example of import attribute


1. <html>
2. <body>
3.
4. <%@ page import="java.util.Date" %>
5. Today is: <%= new Date() %>
6.
7. </body>
8. </html>

2)contentType
The contentType attribute defines the MIME
(Multipurpose Internet Mail Extension) type of the HTTP response.
The default value is "text/html".
Example of contentType attribute
1. <html>
2. <body>
3.
4. <%@ page contentType=application/msword %>
5. Today is: <%= new java.util.Date() %>

14
6.
7. </body>
8. </html>

3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.

4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
Example of info attribute
1. <html>

2. <body>

3.

4. <%@ page info="composed by Sonoo Jaiswal" %>

5. Today is: <%= new java.util.Date() %>

6.

7. </body>

8. </html>

5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.

The default size of the buffer is 8Kb.

Example of buffer attribute

1. <html>

2. <body>

3.

4. <%@ page buffer="16kb" %>

5. Today is: <%= new java.util.Date() %>

6.

15
7. </body>

8. </html>

6)language
The language attribute specifies the scripting language used in the JSP page. The default value is "java".

Action tags
Action tags provides functionality with the support of servlet api features.

It contains only xml syntax.

It does not contain any standard syntax.

Action tags will execute dynamically at runtime(translation phase,request processing phase).

There are two types of action tags

1)Standard Action tags


It is built-in tags

ex:

<jsp:include> ,<jsp:forward> and etc.

2)Custom Action tags


Tags which is created by a programmer.

Action include

Syntax:- <jsp:include page="destination program"/>


It is used to include destination output to out of source jsp program dynamically at runtime.This tag
does not include code ,it will include the output.It tag internally used servlet functionality rd.include(-,-)
to include the output

Note:Here two JES class will be create one is for A.jsp and another for B.jsp

16
Diagram:3

Diagram:4

17
web.xml
<web-app/>

A.jsp
<b>Beginning of A.jsp program</b>

<br>

<jsp:include page="B.jsp"/>

<br>

<b>End of A.jsp program...</b>

B.jsp

<b>Beginning of B.jsp program</b>

<br>

<%= java.util.Date() %>

<br>

<b>End of B.jsp program...</b>

request url

http://localhost:2525/IncludeApp/A.jsp

Action forward

syntax:- <jsp:forward page="Destination progam"/>


It is used to forward the request to destination jsp program from source jsp program.This
internally uses servlet functinality rd.forward(-,-) to forward the reques to destination jsp
program.
html output of source jsp program will be discarded and html output of destination jsp program
will goes to browser window as response.Since html output of source jsp program is discarded,
so it recommended to place

18
<jsp:forward> in source jsp program as conditional statement.Here seperate JES classes will be
created one is for A.jsp and another for B.jsp

Diagram:5

Diagram:6

19
web.xml
<web-app/>

A.jsp
<b>Beginning of A.jsp program</b>

<br>

<jsp:include page="B.jsp"/>

<br>

<b>End of A.jsp program...</b>

B.jsp
<b>Beginning of B.jsp program</b>

<br>

<%= java.util.Date() %>

<br>

<b>End of B.jsp program...</b>

request url
http://localhost:2525/IncludeApp/A.jsp

For servlet to javaBean communication

we need to place java code in servlet class to create java bean object and to call setters and
getters method for Jsp to javaBean communication

We should used following tags.

1)<jsp:useBean>tag

20
2)<jsp:setProperty>tag

3)<jsp:getProperty>tag

<jsp:useBean>tag
It is used to create and locate java bean class object.

<jsp:setProperty>tag

it is used to call setXxx() method and to set the data to bean property.

<jsp:getProperty>tag

It is used to call getXxx() method and to read the data from bean property.

Note: All 3 tags are independent tags.

Example application on use Bean action tag

Diagram:7

21
Calculator.java
package com.vn;
class Calculator
{
public int cube(int n)
{
return n*n*n;
}
}

index.jsp
<jsp:useBean id="obj" class="com.vn.Calculator"/>

<% int m=obj.cube(5);

out.print("Cube of 5 is "+m);%>

web.xml

<web-app/>

Request url

http://localhost:2525/UseBeanApp1/index.jsp

Example of bean development in JSP


In this example there are 3 pages:

index.html
For input of values.

22
process.jsp
File that sets the incoming values to the bean object and prints the one value.

User.java
Bean class that have setter and getter methods.

Index.html
<form action="process.jsp" method="post">

Name:<input type="text" name="name"><br>

Password:<input type="password" name="password"><br>

Email:<input type="text" name="email"><br>

<input type="submit" value="register">

</form>

process.jsp

<jsp:useBean id="u" class="com.vn.User"></jsp:useBean>

<jsp:setProperty property="*" name="u"/>

Record:<br>

<jsp:getProperty property="name" name="u"/><br>

<jsp:getProperty property="password" name="u"/><br>

<jsp:getProperty property="email" name="u" /><br>

User.java

class User

private String name;

private String password;

23
private String email;

public void setName(String name)

this.name=name;

public String getName()

return name;

public void setPassword(String password)

this.password=password;

public String getPassword()

return password;

public void setEmail(String email)

this.email=email;

public String getEmail()

return email;

Request url

http://localhost:2525/UseBeanApp2/index.html

24
25

You might also like