0% found this document useful (0 votes)
64 views96 pages

JSP

JSP allows embedding dynamic elements in HTML pages to improve performance compared to CGI and is compiled before processing each request unlike CGI scripts. JSP pages benefit from Java servlets and Java EE APIs and can be used with servlets for business logic while separating design from development. JSP provides features like expression language, custom tags, and implicit objects that make developing dynamic web applications easier compared to plain servlets.

Uploaded by

A SAI KIRAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views96 pages

JSP

JSP allows embedding dynamic elements in HTML pages to improve performance compared to CGI and is compiled before processing each request unlike CGI scripts. JSP pages benefit from Java servlets and Java EE APIs and can be used with servlets for business logic while separating design from development. JSP provides features like expression language, custom tags, and implicit objects that make developing dynamic web applications easier compared to plain servlets.

Uploaded by

A SAI KIRAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 96

JSP

JSP
• JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to servlet because it provides more functionality than
servlet such as expression language, jstl etc.
• A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain
than servlet because we can separate designing and development.
• It provides some additional features such as Expression Language, Custom Tag etc.
Why Use JSP?

Java Server Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offer several advantages in comparison with
the CGI.
•Performance is significantly better because JSP allows embedding Dynamic Elements
in HTML Pages itself instead of having a separate CGI files.
•JSP are always compiled before it's processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.

• Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP
etc.
• JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines.
• Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding
Advantages of JSP
• vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is
written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web
servers.
• vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have
plenty of println statements that generate the HTML.
• vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real"
programs that use form data, make database connections, and the like.
• vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.
• vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
Advantage of JSP over Servlet

1) Extension to Servlet
•JSP technology is the extension to servlet technology.
• We can use all the features of servlet in JSP.
•In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
•JSP can be easily managed because we can easily separate our business
logic with presentation logic.
•In servlet technology, we mix our business logic with the presentation
logic.
Advantages
3) Fast Development: No need to recompile and redeploy
•If JSP page is modified, we don't need to recompile and redeploy the project. The
servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
4) Less code than Servlet
•In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces
the code. Moreover, we can use EL, implicit objects etc.
JSP - Architecture
Life cycle of a JSP Page
JSP Interface
JSP Processing:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine.
• This is done by using the URL or JSP page which ends with .jsp instead of .html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content.
• This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code that implements the
corresponding dynamic behavior of the page.

• The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format, which
the servlet engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML
content.
• Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
EG
Methods of Jsp Page interface

public void jspInit(): 


•It is invoked only once during the life cycle of the JSP when JSP page is requested
firstly. It is used to perform initialization. It is same as the init() method of Servlet
interface.
public void jspDestroy(): 
•It is invoked only once during the life cycle of the JSP before the JSP page is destroyed.
It can be used to perform some clean up operation.
JSP Scriptlet tag (Scripting elements)
JSP Scriptlet tag

• A scriptlet tag is used to execute java source code in JSP. Syntax is as


follows:
<%  java source code %> 

EG:
<html>  
<body>  
<% out.print("welcome to jsp"); %>  
</body>  
</html>  
 
Example of JSP Scriptlet tag that prints the user
name
Welcome.jsp
Index.html <html>  
<html>   <body>  
<body>   <%  
<form action="welcome.jsp">   String name=request.getParameter("
<input type="text" name="uname uname");  
">   out.print("welcome "+name);  
<input type="submit" value="go" %>  
><br/>   </form>  
</form>   </body>  
</body>   </html>  
</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 %>  
Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.
<html>  
<body>  
<%= "welcome to jsp" %>  
</body>  
</html>  
Example of JSP expression tag that prints current
• To display the current time, we havetime
used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after
getting the instance of Calendar class by the getInstance() method.
index.jsp
<html>  
<body>  
Current Time: <%= java.util.Calendar.getInstance().getTime() %>  
</body>  
</html>  
Example of JSP expression tag that prints the user
Index.jsp
nameWelcome.jsp
<html>  
<body>   <html>  
<form action="welcome.jsp">   <body>  
<input type="text" name="uname"><br/ <
>  <input type="submit" value="go">   %= "Welcome "+request.getParameter("un
ame") %>  </body>  
</form>  
</html>  
</body>  
</html>  
JSP Declaration Tag

• The JSP declaration tag is used to declare fields and methods.


• The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.
• So it doesn't get memory at each request.

Syntax of JSP declaration tag


• The syntax of the declaration tag is as follows:
• <%!  field or method declaration %>  
Difference between JSP Scriptlet tag and Declaration
Jsp Scriptlet Tag
tag
Jsp Declaration Tag
• The jsp scriptlet tag can only declare • The jsp declaration tag can declare
variables not methods. variables as well as methods.
• The declaration of scriptlet tag is • The declaration of jsp declaration tag is
placed inside the _jspService() placed outside the _jspService()
method. method.
Example of JSP declaration tag that declares field
<html>  
<body>  
<%! int data=50; %>  
<%= "Value of the variable is:"+data %>  
</body>  
</html>  
Example of JSP declaration tag that declares method
<html>  
<body>  
<%!   
int cube(int n){  
return n*n*n*;  
}  %>  
<%= "Cube of 3 is:"+cube(3) %>  
</body>  
</html>  
JSP Implicit Objects
• There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
• The available implicit objects are out, request, config, session, application etc.A list
of the 9 implicit objects is given below:
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
JSP out implicit object
For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();  
Example of out implicit object
In this example we are simply displaying date and time.
index.jsp
<html>  
<body>  
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>  
</body>  
</html>  
JSP request implicit object

• The JSP request is an implicit object of type HttpServletRequest i.e. created for each
jsp request by the web container.
• It can be used to get request information such as parameter, header information,
remote address, server name, server port, content type, character encoding etc.
• It can also be used to set, get and remove attributes from the jsp request scope.
EG
index.html
welcome.jsp

<%   
<form action="welcome.jsp">  
String name=request.getParameter("uname"
<input type="text" name="uname">  
);  out.print("welcome "+name);  
<input type="submit" value="go"><br/
%>  
>  </form>  
JSP response implicit object
• In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.
• It can be used to add or manipulate response such as redirect response to another
resource, send error etc.
EG
index.html welcome.jsp
<form action="welcome.jsp">   <%   
<input type="text" name="uname">   response.sendRedirect("http://
<input type="submit" value="go"><br/>   www.google.com");  
</form>   %>  
The out Object:
• The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is
used to send content in a response.
• The initial JspWriter object is instantiated differently depending on whether the
page is buffered or not. Buffering can be easily turned off by using the
buffered='false' attribute of the page directive.
• The JspWriter object contains most of the same methods as the java.io.PrintWriter
class. However, JspWriter has some additional methods designed to deal with
buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
• Following are the important methods which we would use to write boolean char,
int, double, object, String etc.
….
Method Description

out.print(dataType dt) Print a data type value

out.println(dataType dt) Print a data type value then terminate the line with new line
character.

out.flush() Flush the stream.


The session Object:
• The session object is an instance of javax.servlet.http.HttpSession and behaves
exactly the same way that session objects behave under Java Servlets.
• The session object is used to track client session between client requests.
The application Object:

• The application object is direct wrapper around the ServletContext object for the
generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
• This object is a representation of the JSP page through its entire lifecycle. This object
is created when the JSP page is initialized and will be removed when the JSP page is
removed by the jspDestroy() method.
• By adding an attribute to application, you can ensure that all JSP files that make up
your web application have access to it.
The config Object:

• The config object is an instantiation of javax.servlet.ServletConfig and is a direct


wrapper around the ServletConfig object for the generated servlet.
• This object allows the JSP programmer access to the Servlet or JSP engine
initialization parameters such as the paths or file locations etc.
• The following config method is the only one you might ever use, and its usage is
trivial:
config.getServletName();
• This returns the servlet name, which is the string contained in the <servlet-name>
element defined in the WEB-INF\web.xml file
The pageContext Object:

• The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The


pageContext object is used to represent the entire JSP page.
• This object is intended as a means to access information about the page while
avoiding most of the implementation details.
• This object stores references to the request and response objects for each request.
The application, config, session, and out objects are derived by accessing attributes
of this object.
• The pageContext object also contains information about the directives issued to the
JSP page, including the buffering information, the errorPageURL, and page scope.

• The PageContext class defines several fields, including PAGE_SCOPE,


REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the
four scopes. It also supports more than 40 methods, about half of which are
inherited from the javax.servlet.jsp. JspContext class.
• One of the important methods is removeAttribute, which accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the
attribute from all scopes, while the following code only removes it from the page
scope:
pageContext.removeAttribute("attrName", PAGE_SCOPE)

The page Object

• This object is an actual reference to the instance of the page. It


can be thought of as an object that represents the entire JSP
page.
• The page object is really a direct synonym for the this object.
The exception Object
• The exception object is a wrapper containing the exception
thrown from the previous page. It is typically used to generate
an appropriate response to the error condition.
JSP directives

• The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
• There are three types of directives:
page directive
include directive
taglib directive
Syntax of JSP Directive
• <%@ directive attribute="value" %>
JSP page directive

• The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
1. import
2. contentType
3. extends
4. info
5. buffer
6. language
7. isELIgnored
8. isThreadSafe
9. autoFlush
10. session
11. pageEncoding
12. errorPage
13. isErrorPage
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 class or interface.
• EG:
<html>  
<body>  
  <%@ page import="java.util.Date" %>  
Today is: <%= new Date() %>  
  </body>  
</html>  
contentType

• The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)


type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
<html>  
<body>    
<%@ page contentType=application/msword %>  
Today is: <%= new java.util.Date() %>  
  </body>  
</html>  
Extends

• The extends attribute defines the parent class that will be inherited by the
generated servlet.
• It is rarely used.
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:
• By errorPage and isErrorPage attributes of page directive
• By <error-page> element in web.xml file
Example of exception handling in jsp by the
• elements
In this case, you of page
must define directive
and create a page to handle the
exceptions, as in the error.jsp page. The pages where may occur
exception, define the errorPage attribute of page directive, as in
the process.jsp page.
• 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
EG index.jsp

<form action="process.jsp">  
No1:<input type="text" name="n1" /><br/><br/>  
No1:<input type="text" name="n2" /><br/><br/>  
<input type="submit" value="divide"/>  
</form>  
process.jsp

<%@ page errorPage="error.jsp" %>  
<%    
String num1=request.getParameter("n1");  
String num2=request.getParameter("n2");  
 int a=Integer.parseInt(num1);  
int b=Integer.parseInt(num2);  
int c=a/b;  
out.print("division of numbers is: "+c);  
  %>  
error.jsp

<%@ page isErrorPage="true" %>  
  <h3>Sorry an exception occured!</h3>  
  Exception is: <%= exception %>  
Jsp Include Directive
• The include directive is used to include the contents of any resource it may be jsp
file, html file or text file. The include directive includes the original content of the
included resource at page translation time (the jsp page is translated only once so it
will be better to include static resource).
• Advantage of Include directive
Code Reusability
• Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive

• In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.
<html>  
<body>    
<%@ include file="header.html" %>  
  Today is: <%= java.util.Calendar.getInstance().getTime() %>  
  </body>  
</html>  
JSP Taglib directive

• The JSP taglib directive is used to define a tag library that defines many tags. We use
the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we
will use this tag so it will be better to learn it in custom tag.
• Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>  
Example of JSP Taglib directive

• In this example, we are using our tag named currentDate. To use this tag we must
specify the taglib directive so the container may get information about the tag.
<html>  
<body>    
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>  
  <mytag:currentDate/>  
  </body>  
</html>  
JSP Action Tags

• There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.
• The action tags are used to control the flow between pages and to use Java Bean. 
The Jsp action tags

JSP Action Tags Description


jsp:forward forwards the request and response to another
resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and


include mostly.

jsp:fallback can be used to print the message if plugin is working.


It is used in jsp:plugin.
jsp:forward action tag

• The jsp:forward action tag is used to forward the request to another resource it may
be jsp, html or another resource.
• Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />  
• Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">  
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />  </
jsp:forward>  
Example of jsp:forward action tag without
parameter
Index.jsp Printdate.jsp
<html>   <html>  
<body>   <body>  
<h2>this is index page</h2>   <
 <jsp:forward page="printdate.jsp" />   % out.print("Today is:"+java.util.Calendar.
</body>   getInstance().getTime()); %>  
</html>   </body>  
</html>  
Example of jsp:forward action tag with parameter
Index.jsp Printdate.jsp
<html>  
<html>  
<body>  
<body>  
<h2>this is index page</h2>     <
  <jsp:forward page="printdate.jsp" >  
% out.print("Today is:"+java.util.Calendar.
<jsp:param name="name" value="java
getInstance().getTime()); %>  
tpoint.com" />   <%= request.getParameter("name") %>  
</jsp:forward>     </body>  
  </body>   </html>  
</html>  

In this example, we are forwarding the


request to the printdate.jsp file with
parameter and printdate.jsp file prints the
parameter value with date and time.
jsp:include action tag

• The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet.
• The jsp include action tag includes the resource at request time so it isbetter for
dynamic pages because there might be changes in future.
• The jsp:include tag can be used to include static as well as dynamic pages.
Advantage of jsp:include action tag

• Code reusability : We can use a page many times such as


including header and footer pages in all pages. So it saves a lot
of time.
Difference between jsp include
JSP include directive directive
JSP include action and include action

includes resource at translation time. includes resource at request time.

better for static pages. better for dynamic pages.

includes the original content in the calls the include method.


generated servlet.
Syntax of jsp:include action tag without parameter

• <jsp:include page="relativeURL | <%= expression %>" />  
Syntax of jsp:include action tag with parameter
• <jsp:include page="relativeURL | <%= expression %>">  
• <jsp:param name="parametername" value="parametervalue | 
<%=expression%>" />  
• </jsp:include>  
Example ofindex.jsp
In this example, jsp:include
file includesaction tag
the content without
of the parameter
printdate.jsp file.
index.jsp
<h2>this is index page</h2>  
<jsp:include page="printdate.jsp" />  
 <h2>end section of index page</h2>  
printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> 
eg
Java Bean

• A Java Bean is a java class that should follow following conventions:


• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as
getter and setter methods.
Why use Java Bean?

• According to Java white paper, it is a reusable software


component. A bean encapsulates many objects into one
object, so we can access this object from multiple places.
Moreover, it provides the easy maintenance.
Simple example of java bean class

//employee.java
package mypack;  
public class Employee implements java.io.Serializable{  
private int id;  
private String name;  
public Employee(){}  
 public void setId(int id){this.id=id;}  
public int getId(){return id;}  
 public void setName(String name){this.name=name;}  
  public String getName(){return name;}  
  }  
How to access the java bean class?

• To access the java bean class, we should use getter and setter method.
package mypack;  
public class Test{  
public static void main(String args[]){  
 Employee e=new Employee();//object is created  
 e.setName("Arjun");//setting value to the object  
  System.out.println(e.getName());  
}}  
jsp:useBean action tag

• The jsp:useBean action tag is used to locate or instantiate a


bean class. If bean object of the Bean class is already created, it
doesn't create the bean depending on the scope. But if object
of bean is not created, it instantiates the bean.
Syntax of jsp:useBean action tag

<jsp:useBean id= "instanceName" scope= "page | request | session |
 application"  class= "packageName.className" type= "packageNam
e.className"  
beanName="packageName.className | <%= expression >" >  
</jsp:useBean>  
Attributes and Usage of jsp:useBean action tag
id: is used to identify the bean in the specified scope.
scope: represents the scope of the bean. It may be page, request, session or application. The
default scope is page.
page: specifies that you can use this bean within the JSP page. The default scope is page.
request: specifies that you can use this bean from any JSP page that processes the same request. It
has wider scope than page.
session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not. It has wider scope than request.
application: specifies that you can use this bean from any JSP page in the same application. It has
wider scope than session.
class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must
have no-arg or no constructor and must not be abstract.
type: provides the bean a data type if the bean already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without class or beanName, no bean is instantiated.
beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
Simple example of jsp:useBean action tag
• Calculator.java (a simple Bean class)
package com.javatpoint;  
public class Calculator{  
 public int cube(int n){return n*n*n;}  
  
}  
Index.jsp
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>  
 <%  
int m=obj.cube(5);  
out.print("cube of 5 is "+m);  
%>  
Jsp:setProperty and jsp:getProperty action tags
• The setProperty and getProperty action tags are used for developing web
application with Java Bean. In web devlopment, bean class is mostly used because it
is a reusable software component that represents data.
• The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.
MVC in JSP
• MVC stands for Model View and Controller. It is a design
pattern that separates the business logic, presentation logic
and data.
• Controller acts as an interface between View and Model.
Controller intercepts all the incoming requests.
• Model represents the state of the application i.e. data. It can
also have business logic.
• View represents the presentaion i.e. UI(User Interface).
Architecture
Implementation

• We are going to create a Student object acting as a model.StudentView will be a


view class which can print student details on console and StudentController is the
controller class responsible to store data in Student object and update
viewStudentView accordingly.
• MVCPatternDemo, our demo class, will use StudentController to demonstrate use of
MVC pattern.
eg
Create Model Student.java
public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
Create View StudentView.java
public class StudentView {
public void printStudentDetails(String studentName, String studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
Create Controller StudentController.java

public class StudentController {


private Student model;
private StudentView view;
public StudentController(Student model, StudentView view){
this.model = model;
this.view = view;
} public void setStudentName(String name){
model.setName(name);
} public String getStudentName(){
return model.getName();
} public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
} public String getStudentRollNo(){
return model.getRollNo();
}
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}
Use the StudentController methods to demonstrate MVC design
pattern usage.MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the database
Student model = retriveStudentFromDatabase();
//Create a view : to write student details on console
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
//update model data
controller.setStudentName("John");
controller.updateView();
} private static Student retriveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}}
Verify the output.

Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
Advantage of MVC (Model 2) Architecture

• Navigation Control is centralized


• Easy to maintain the large application
Custom Tags in JSP

• Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag
and separates the business logic from the JSP page.
• The same business logic can be used many times by the use of custom tag.
Advantages of Custom Tags

• The key advantages of Custom tags are as follows:


• Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet
tag which is considered bad programming approach in JSP.
• Separation of business logic from JSP The custom tags separate the the business
logic from the JSP page so that it may be easy to maintain.
• Re-usability The custom tags makes the possibility to reuse the same business logic
again and again.
Syntax to use custom tag

• There are two ways to use the custom tag. They are given below:
<prefix:tagname attr1=value1....attrn=valuen />  
<prefix:tagname attr1=value1....attrn=valuen >  
body code  
</prefix:tagname>  
JSP Custom Tag API

• The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom
tag API. The JspTag is the root interface in the Custom Tag hierarchy.
JspTag interface

• The JspTag is the root interface for all the interfaces and classes
used in custom tag. It is a marker interface
Tag interface

• The Tag interface is the sub interface of JspTag interface. It provides methods to
perform action at the start and end of the tag.
Fields of Tag interface

Field Name Description

public static int it evaluates the body content.


EVAL_BODY_INCLUDE

public static int EVAL_PAGE it evaluates the JSP page content after
the custom tag.

public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the
custom tag.
Methods of Tag interface
Method Name Description
public void setPageContext(PageContext pc) it sets the given PageContext object.

public void setParent(Tag t) it sets the parent of the tag handler.

public Tag getParent() it returns the parent tag handler object.

public int doStartTag()throws JspException it is invoked by the JSP page implementation object. The JSP
programmer should override this method and define the business
logic to be performed at the start of the tag.

public int doEndTag()throws JspException it is invoked by the JSP page implementation object. The JSP
programmer should override this method and define the business
logic to be performed at the end of the tag.

public void release() it is invoked by the JSP page implementation object to release the
state.
Thank You

You might also like