Unit – 5
Servlets
Q1) Define servlet?
A1) Servlet
A web application is built using Servlet technology (resides at the server side and generates a dynamic web page).
The Servlet API contains several interfaces and classes, such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, and so on.
Java Servlets are programs that run on a Web or Application server and function as a middle layer between requests from a Web browser or other HTTP client and the HTTP server's databases or applications.
You can use Servlets to collect user feedback through web page forms, present records from a database or another source, and dynamically construct web pages.
Depending on the background, a servlet can be represented in a variety of ways.
● A web application is created using the Servlet technology.
● Servlet is an API that includes documentation as well as a variety of interfaces and classes.
● Any Servlet must have a Servlet interface that must be implemented.
● Servlet is a class that enhances the server's capabilities and responds to incoming requests. It is capable of responding to any message.
● A servlet is a server-side web component that allows you to build a dynamic web page.
Q2) Explain servlet architecture?
A2) Servlet Architecture
The servlet high-level architecture diagram is shown below. Let's take a look at how each component contributes to the operation of a servlet in more detail.
Fig 1: servlet architecture
Client
The client in the architecture above serves primarily as a medium, sending HTTP requests to the web server and then processing the response it receives. The web browser, as seen in the diagram, is our client.
Web server
A web server's main task is to process the requests and replies that a user sends over time and to keep track of how a web user can access the files that are hosted on the server. The server in question is a piece of software that controls access to a network's centralized resource or service. Web Servers are divided into two categories:
Web Container
Another common component of servlet architecture is the web container, which is responsible for interacting with the servlets. A web container has two primary functions:
● Managing the servlet lifecycle
● URL mapping
Web container is a server-side application that manages and handles all requests that come in via servlets, JSP pages, or potentially any other file system.
Q3) What do you mean by servlet interface?
A3) Servlet Interface
The Servlet interface unifies the actions of all servlets.
The Servlet interface specifies the methods that must be implemented by all servlets.
For any servlet to be created, the Servlet interface must be implemented (either directly or indirectly). It has three life cycle methods for initializing the servlet, servicing demands, and destroying the servlet, as well as two non-life cycle methods.
Servlet Interface Methods
The methods available in the Servlet interface are listed below.
2. void init(ServletConfig config) - When the Servlet container starts up (which occurs when the web server starts up), it loads and instantiates all of the servlets. This method initializes the servlet after the init() method is called for each instantiated servlet.
3. void service(ServletRequest req, ServletResponse res) - During the servlet life cycle, this is the only process that is called several times. Any time the server receives a request, this method is named to support the client.
4. ServletConfig getServletConfig() - This method returns a ServletConfig object containing the servlet's initialization and startup parameters.
5. java.lang.String getServletInfo() - The author, edition, and copyright of the servlet are all returned.
Q4) Describe servlet life cycle?
A4) Servlet Life Cycle
There are five stages in the life cycle of a servlet:
1) Loading of Servlet
2) Creating instance of Servlet
3) Invoke init() once
4) Invoke service() repeatedly for each client request
5) Invoke destroy()
Fig 2: servlet life cycle
Step 1: Loading of Servlet
The servlet container deploys and loads all the servlets when the web server (for example, Apache Tomcat) starts up.
Step 2: Creating instance of Servlet
The servlet container produces instances of each servlet class until all of the servlet classes have been loaded. The servlet container only generates one instance of each servlet class, and all servlet requests are handled by the same servlet instance.
Step 3: Invoke init() method
The init() method is called for each instantiated servlet until all of the servlet classes have been instantiated. The servlet is initialized with this form. In the deployment descriptor (web.xml) file, you can define those init parameters.
Syntax of init method
public void init(ServletConfig config) throws ServletException
Step 4: Invoke service() method
When a servlet request is received, the web server creates a new thread that calls the service() function. If the servlet is GenericServlet, the request is handled directly by the service() process; if the servlet is HttpServlet, the request is received and dispatched to the appropriate handler method based on the request form.
Syntax
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
Step 5: Invoke destroy() method
When the servlet container shuts down (which normally occurs when the web server is stopped), it unloads all of the servlets and calls the destroy() method on each one that has been initialized.
Syntax
public void destroy()
Q5) What is Handling HTTP get Requests?
A5) Handling HTTP get Requests
Extend the HttpServlet class and override the servlet methods that handle the HTTP requests that your servlet supports to handle HTTP requests in a servlet. DoGet are the methods that manage these requests.
To handle an HTTP GET request, the server calls the doGet () method via the service () method. This approach often handles HTTP HEAD requests automatically, as a HEAD request is simply a GET request with no body in the code and only request header fields. Let's look at a sample program that defines a servlet for handling HTTP GET requests to see how the doGet () method works.
Program
import <a href="https://ecomputernotes.com/java/what-is-java/what-is-java-explain-basic-features-of-java-language" data-internallinksmanager029f6b8e52c="16">java</a>.io.*;
import <a href="https://ecomputernotes.com/java/what-is-java/what-is-java-explain-basic-features-of-java-language" data-internallinksmanager029f6b8e52c="16">java</a>.util.*;
import javax.servlet.*;
public class ServletGetExample extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
String login= req.getParameter("loginid");
String password= req.getParameter("password");
out.println("Your login ID is: ");
out.println(login);
out.println("Your password is: ");
out.println(password);
out.close();
}
}
The doGet method is overridden by the servlet, which extends the HttpServlet class.
The getParameter method in the doGet method retrieves the servlet's intended statement.
Q6) What do you understand by Handling HTTP post Requests?
A6) Handling HTTP post Requests
To manage HTTP POST requests, the server invokes the do Post () method via the service () method, much like the doGet () method. The doPost () method is used when a huge volume of data has to be sent to the server and the doGet () method cannot handle it.
Parameters are appended to the URL in the doGet () process, while parameters are sent in a separate line in the HTTP request body in the do Post () method. The doGet ( ) method is typically used when data needs to be retrieved from the server, while the doPost ( ) method is typically used when data needs to be modified or sent to the server.
Overriding the doPost method is needed to handle POST requests.
Program
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class ServletPostExample extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
PrintWriter out = res.getWriter();
String login= req.getParameter(“loginid”);
String password= req.getParameter(“password”);
out.println(“Your login ID is: “);
out.println(login);
out.println(“Your password is: “);
out.println(password);
out.close();
}
}
The doPost method is overridden by the servlet, which extends the HttpServlet class.
The getParameter method in the doPost method retrieves the servlet's intended statement.
Q7) Write about Redirecting Requests to Other Resources?
A7) Redirecting Requests to Other Resources
Redirecting a request to a different resource is often useful. A servlet, for example, might detect the client browser's form and guide the request to a Web page tailored to that browser. When handling a request fails, this method is often used to guide users to an error page. In Example, the RedirectServlet receives a page parameter as part of a get request and uses it to redirect the request to another resource.
Program
// Redirecting a user to a different Web page.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class RedirectServlet extends HttpServlet
{
// process "get" request from client
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String location = request.getParameter( "page" );
if (location! = null)
{
if (location.equals( "deitel" ) )
response.sendRedirect( "http://www.deitel.com" );
else if ( location.equals( "welcome1" ) )
response.sendRedirect( "welcome1" );
} // end if
// code that executes only if this servlet
// does not redirect the user to another page
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
out.printf( "%s%s%s" , "<!DOCTYPE html PUBLIC" ,
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
// head section of document
out.println( "<head>" );
out.println( "<title>Invalid page</title>" );
out.println( "</head>" );
// body section of document
out.println( "<body>" );
out.println( "<h1>Invalid page requested</h1>" );
out.println( "<p><a href = " +
"\"servlets/RedirectServlet.html\">" );
out.println( "Click here to choose again</a></p>" );
out.println( "</body>" );
// end XHTML document
out.println( "</html>" );
out.close(); // close stream to complete the page
} // end method doGet
} // end class RedirectServlet
The page parameter is obtained from the request on line 17. The nested if... checks if the value returned isn't null. At line 2124, the else if argument specifies if the meaning is "deitel" or "welcome1." The answer object's sendRedirect method (line 22) redirects the request to www.deitel.com if the value is "deitel." Line 24 redirects the request to the servlet of Example 26.7 if the value is "welcome1." The jhtp6 background root for our Web application is not specifically defined on line 24.
Example: document to demonstrate redirecting requests to other resources.
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Example: RedirectServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Redirecting a Request to Another Site</title>
</head>
<body>
<p>Click a link to be redirected to the appropriate page</p>
<p>
<a href = "/jhtp6/redirect?page=deitel">
www.deitel.com</a><br />
<a href = "/jhtp6/redirect?page=welcome1">
Welcome servlet</a>
</p>
</body>
</html>
Q8) Describe Session Tracking, Cookies, Session Tracking with Http Session?
A8) Session Tracking, Cookies, Session Tracking with Http Session
HTTP is a "stateless" protocol, which means that any time a client requests a Web page, the client establishes a new connection with the Web server, and the server does not keep track of previous requests.
There are three ways to keep a session between a web client and a web server alive.
Cookies
A webserver can allocate a unique session ID to each web client as a cookie, and the received cookie can be used to identify subsequent requests from the client.
Since many browsers do not accept cookies, this method might not be reliable, so I would not suggest using it to manage sessions.
Session Tracking with Http Session
Aside from the three methods described above, servlets include the HttpSession Interface, which allows a user to be identified over multiple page requests or visits to a Web site, as well as store information about that user.
This interface is used by the servlet container to establish a connection between an HTTP client and an HTTP server. The session lasts for a set amount of time and spans several connections or page requests from the user.
The HttpSession object can be obtained by calling the public method getSession() of HttpServletRequest, as shown below.
HttpSession session = request.getSession();
Before sending any document content to the client, you must first call request.getSession(). The following is a list of the most important methods available via the HttpSession object.
No. | Method & Description |
1 | public Object getAttribute(String name) This method returns the object in this session bound with the specified name, or null if no object is bound with the name. |
2 | public Enumeration getAttributeNames() This method returns an Enumeration of String objects with the names of all the objects associated with this session. |
3 | public long getCreationTime() This method returns the milliseconds since midnight January 1, 1970 GMT, when this session was established. |
4 | public String getId() This method returns a string that contains the session's unique identifier. |
5 | public long getLastAccessedTime() This method returns the session's most recent accessed time in milliseconds since midnight on January 1, 1970 GMT. |
6 | public int getMaxInactiveInterval() The maximum time interval (seconds) that the servlet container can hold the session open between client accesses is returned by this process. |
7 | public void invalidate() This method unbinds all objects bound to this session and invalidates it. |
8 | public boolean isNew( If the client is unaware of the session or decides not to enter it, this approach returns true. |
9 | public void removeAttribute(String name) The object bound with the defined name is removed from this session using this form. |
10 | public void setAttribute(String name, Object value) This method uses the name defined to attach an object to this session. |
11 | public void setMaxInactiveInterval(int interval) This method defines the time between client requests before the servlet container invalidates this session in seconds. |
Q9) What is JSP?
A9) JSP
A Java Server Pages component is a type of Java servlet that serves as the user interface for a Java web application. JSPs are text files that contain HTML or XHTML code, XML components, and embedded JSP actions and commands, and are written by web developers.
You can use JSP to collect user feedback via Web Page forms, present records from a database or another source, and dynamically construct Web Pages.
JSP tags can be used for a number of things, including retrieving data from a database or registering user preferences, interacting with JavaBeans components, transferring control between pages, and exchanging data between requests, pages, and so on.
JSP technology, like Servlet technology, is used to create web applications. It can be thought of as a Servlet extension because it has more features than Servlet, such as expression language, JSTL, and so on.
HTML tags and JSP tags make up a JSP page. Since we can distinguish design and production, JSP pages are easier to manage than Servlets. It has some extra functionality, such as Expression Language and Custom Tags.
JSP stands for Java Server Pages, and it's a technology for creating interactive Web pages. This allows developers to embed java code in HTML pages by using special JSP tags, the majority of which begin with % and end with % >.
Q10) Why use JSP, also write advantages of JSP?
A10) Use of JSP
Java Server Pages are often used in the same way that programs written with the Popular Gateway Interface are (CGI). However, as compared to CGI, JSP has some advantages.
● Since JSP allows Dynamic Elements to be embedded in HTML Pages rather than requiring separate CGI files, performance is greatly improved.
● Unlike CGI/Perl, which allows the server to load an interpreter and the target script each time the page is requested, JSPs are always compiled until they are processed by the server.
● JSPs, including Servlets, are designed on top of the Java Servlets API, so they have access to all of the powerful Enterprise Java APIs, such as JDBC, JNDI, EJB, JAXP, and so on.
● The model supported by Java servlet template engines allows JSP pages to be used in conjunction with servlets that manage business logic.
Finally, JSP is an essential component of Java Enterprise Edition (Java EE), a comprehensive framework for enterprise-class applications. As a result, JSP can be used in a wide range of applications, from the easiest to the most complex and challenging.
Advantages of JSP
● It's easy to code and maintain.
● Scalability and high performance.
● Since JSP is based on Java technology, it is platform independent.
Q11) Write the first Java Server Page Example?
A11) A first Java Server Page Example
Write some HTML code as shown below and save it with the.jsp extension to build the first JSP page. This file has been called index.jsp. To run the JSP website, put it in a folder and paste it in the web-apps directory of Apache Tomcat.
index.jsp
Let's look at a simple JSP example in which we use the scriptlet tag to embed Java code in the JSP tab. The scriptlet tag will be covered later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
On the browser, it will print 10.
Example
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
How to run a simple JSP page
To run this JSP page, go through the steps below:
● Begin the server.
● Place the JSP file in a folder and publish it to the server.
● Use the URL to open the window.
Q12) Describe an implicit object?
A12) Implicit Object
These Objects are Java objects that the JSP Container makes accessible to developers in each page, and the developer can call them without having to declare them explicitly. Pre-defined variables are another name for JSP Implicit Objects.
The nine Implicit Objects that JSP supports are mentioned in the table below.
No. | Object | Description |
1 | request | This is the HttpServletRequest object that the request is associated with. |
2 | response | This is the HttpServletResponse object that corresponds to the client's response. |
3 | out | This is the PrintWriter object, which is responsible for sending output to the client. |
4 | session | This is the HttpSession object that the request is connected with. |
5 | application | The application context is associated with this ServletContext object. |
6 | config | This is the page's associated ServletConfig item. |
7 | pageContext | This includes the use of server-specific features such as faster JspWriters. |
8 | page | This is just another name for this, and it's used to call the methods specified by the translated servlet class. |
9 | Exception | The Exception object allows designated JSPs to access exception data. |
The request Object
The request object is a javax.servlet instance. http.HttpServletRequest is an entity that represents a http.HttpServletRequest request. When a client requests a page, the JSP engine generates a new object to represent it.
The request object contains methods for retrieving HTTP header information such as form data, cookies, and HTTP methods, among other things.
The response Object
The answer object is a javax.servlet.http.HttpServletResponse object, which is an instance of javax.servlet.http.HttpServletResponse. The server creates an object to represent the answer to the client in the same way that it creates the request object.
The interfaces for creating new HTTP headers are also defined by the response object. The JSP programmer will use this object to add new cookies, date stamps, HTTP status codes, and so on.
The out Object
The out implicit object is a javax.servlet.jsp.JspWriter object that is used to submit content as part of a response.
Depending on whether the page is buffered or not, the initial JspWriter object is generated in a different way. The buffered = 'false' attribute of the page directive can be used to switch off buffering.
Many of the methods in the JspWriter object are the same as those in the java.io.PrintWriter class. JspWriter, on the other hand, has several additional buffering methods. JspWriter, unlike the PrintWriter object, throws IOExceptions.
The session Object
The session object is a javax.servlet.http.HttpSession instance that behaves in the same way that session objects in Java Servlets do. The session object is used to keep track of a client's session from one request to the next.
The application Object
The application object is a wrapper around the ServletContext object for the created Servlet, and is actually a javax.servlet. ServletContext kind.
This object represents a JSP page during its entire life cycle. This object is generated when the JSP page is first loaded and is removed when the jspDestroy() method is used to delete the JSP page.
You will ensure that all JSP files that make up your web application have access to it by adding an attribute to application.
The config Object
The config object is an instantiation of javax.servlet.ServletConfig and For the created servlet, is a direct wrapper around the ServletConfig item.
This object gives the JSP programmer access to Servlet or JSP engine initialization parameters including paths and file positions, among other things.
The page Context Object
A javax.servlet.jsp.PageContext object is an instance of the pageContext object. The entire JSP page is represented by the pageContext object.
This object is designed to provide access to page information while removing most of the implementation specifics.
The page Object
This object is a real-time reference to the page's case. It's similar to an object that represents the entire JSP page.
The page object is essentially the same as this object.
The Exception Object
The exception object is a wrapper that contains the previous page's exception. It's usually used to come up with a suitable answer to an error state.
Q13) What is Scripting?
A13) Scripting
<% % > tags are used to write JSP scripting elements. The JSP engine processes the code within percent > tags when the JSP page is translated. The rest of the text on the JSP page is HTML code or plain text.
Different types of scripting elements
Scripting elements | Example |
Comment | <%-- comment --%> |
Directive | <%@ directive %> |
Declaration | <%! declarations %> |
Scriptlets | <% scriptlets %> |
Expression | <%= expression %> |
Comment
When you're making a JSP page and want to add feedback on what you're doing, you'll use JSP Comment. Only the JSP page displays JSP comments. During the translation process, these comments are not included in the servlet source code, nor do they appear in the HTTP response.
The JSP statement syntax is as follows:
<%-- JSP comment --%>
Directives
When a page is translated, the Directive Tag gives special instructions to the Web Container. There are three types of directive tags: page, include, and taglib.
The Page directive specifies a set of page-specific properties that interact with the Web Container during translation. The page directive's basic syntax is <% @ page attribute="value" % >, where attributes can be any of the following:
● import attribute
● language attribute
● extends attribute
● session attribute
● isThreadSafe attribute
● isErrorPage attribute
● errorPage attribute
● contentType attribute
● autoFlush attribute
● buffer attribute
Declaration
We know that a JSP page is eventually converted into a Servlet class. When we declare a variable or method in JSP using the Declaration Tag, it means that the declaration is made within the Servlet class but outside of the service(or any other) method. Within the Declaration Tag, you can declare static members, instance variables, and methods.
Declaration Tag Syntax:
<%! declarations %>
Scriptlets
You may use the Scriptlet Tag to write Java code inside a JSP page. The Scriptlet tag uses script/java code to enforce the _jspService method features.
The Scriptlet Tag has the following syntax:
<% JAVA CODE %>
Expression
The Expression Tag is used to print java language expressions that are placed within tags. Any java language expression that can be used as an argument to the out.print() method can be stored in an expression tag.
Expression Tag Syntax
<%= expression %>
Q14) Define standard actions?
A14) Standard Actions
Standard(Action) tags are provided by the JSP specification for use in JSP pages. Since scriptlet code is technically not recommended nowadays, these tags are used to delete or exclude scriptlet code from your JSP page. Putting java code directly within your JSP page is considered poor practice.
The jsp: prefix is used to start standard tags. There are a number of JSP Standard Action tags that are used to carry out particular tasks.
The following are some examples of JSP Standard Action Tags:
Action Tag | Description |
jsp : forward | The request will be forwarded to a new tab. Usage : <jsp:forward page="Relative URL" /> |
jsp : useBean | This method locates or creates a JavaBean. Usage : <jsp:useBean id="beanId" /> |
jsp : getProperty | a property from a JavaBean instance is retrieved. Usage : <jsp:useBean id="beanId" ... /> ... <jsp:getProperty name="beanId" property="someProperty …../> The name of the pre-defined bean whose property we want to access is beanName. |
jsp : setProperty | Data can be stored in any JavaBeans instance's property. Usage : <jsp:useBean id="beanId" ... /> ... <jsp:setProperty name="beanId" property="someProperty" value="some value"/> The name of the pre-defined bean whose property we want to access is beanName. |
jsp: include | Includes a JSP page's runtime answer in the current page
|
jsp: plugin | Creates an OBJECT or EMBED tag for Java Applets using a client browser-specific build.
|
jsp: fallback | If the java plugin isn't accessible on the client, it provides an alternative text. If the included jsp plugin is not loaded, you can use this to print a message. |
jsp: element | Dynamically defines XML components. |
jsp: attribute | The attribute of a dynamically defined XML entity is defined. |
jsp: body | Used to include the tag body in regular or custom tags. |
jsp: param | Parameters are added to the request object. |
jsp: text | In JSP pages and papers, it's used to write template text. Usage: <jsp:text>Template data</jsp:text> |
Q15) What do you mean by directives?
A15) Directives
These guidelines give the container guidance and instructions on how to manage certain aspects of the JSP processing.
The overall structure of the servlet class is affected by a JSP directive. It normally takes the form of the following.
<%@ directive attribute = "value" %>
A directive may have a number of attributes, which you can mention as key-value pairs separated by commas in a table.
The space between the @ symbol and the directive name, as well as the space between the last attribute and the closing percent >, is optional.
A directive tag may be one of three styles.
No. | Directives | Description |
1 | <%@ page ... %> | Scripting language, error page, and buffering specifications are all page-dependent attributes. |
2 | <%@ include ... %> | During the translation process, a file is included. |
3 | <%@ taglib ... %> | Declares a tag library of custom behavior that can be included throughout the page. |
Page Directives
The page directive is used to give the container instructions. These guidelines apply to the current JSP page. Page instructions can be coded anywhere in your JSP page. Page instructions are coded at the top of the JSP page by convention.
The page directive's basic syntax is as follows:
<%@ page attribute = "value" %>
Include Directives
During the translation process, the include directive is used to include a file. During the conversion process, this directive instructs the container to merge the content of other external files with the current JSP. Include directives can be placed anywhere in your JSP page.
This directive's general use form is as follows:
<%@ include file = "relative url" >
Taglib Directives
Custom JSP tags that look like HTML or XML tags can be specified using the JavaServer Pages API, and a tag library is a collection of user-defined tags that enforce custom actions.
The taglib directive declares that your JSP page uses a collection of custom tags, specifies the library's location, and specifies how to locate the custom tags in your JSP page.
The taglib directive has the following syntax.
<%@ taglib uri="uri" prefix = "prefixOfTag" >
Q16) Explain Custom Tag Libraries?
A16) Custom Tag Libraries
Custom Tags can be used when EL and Standard Action elements aren't enough to delete scriptlet code from your JSP Page. User-defined tags are what custom tags are.
Custom tags are a great way to separate the complexities of business logic from the presentation of Web pages in a way that is simple to use and manage for the Web author. It also allows for reusability since custom tags can be reused.
A custom tag's format can be either void (called an Empty tag) or contain a body (called a Body tag). The number of attributes that a tag will accept is determined by the Tag Handler class's implementation.
An Empty Tag has the following syntax:
<tagLibraryPrefix:customTagName attribute1="attributeName"
attribute2="attributeName" ... />
The following is the syntax for a custom body tag:
<tagLibraryPrefix:customTagName attribute1="attributeName"
attribute2="attributeName" ... />
< --Body of custom tag-- >
</tagLibraryPrefix:customTagName>
In the world of JSP, creating custom tags is considered a very good practice. Often try to build and use your own custom tags in your JSP application from commonly used operations. Let's move on to the next lesson, where we'll learn how to make a Custom tag.
Creating a custom tag in Jsp
The following components are needed to build a Custom Tag:
Tag Handler Class
There are two ways to build a Tag Handler class:
● By using one of three interfaces: SimpleTag, Tag, or BodyTag, which describe methods that are called during the tag's life cycle.
● Extending a base class that implements the SimpleTag, Tag, or BodyTag interfaces. The SimpleTag, Tag, and BodyTag interfaces are implemented by the SimpleTagSupport, TagSupport, and BodyTagSupport groups, respectively. Extending these classes frees up the tag handler class from having to follow any of the interfaces' methods, as well as providing other useful features.
Tag Library Descriptor
A Tag Library Descriptor is an XML document that contains information about both the library as a whole and each tag inside it. TLDs are used by both the site container and the JSP page creation tools to verify tags.
The tag library descriptor file must be in the /WEB-INF/ directory or subdirectory of a WAR file, or in the /META-INF/ directory or subdirectory of a tag library packed in a Container.