- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I create custom tag in JSP which can accept attribute from parent jsp page?
You can use various attributes along with your custom tags. To accept an attribute value, a custom tag class needs to implement the setter methods, identical to the JavaBean setter methods as shown below −
package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { private String message; public void setMessage(String msg) { this.message = msg; } StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { if (message != null) { /* Use message from attribute */ JspWriter out = getJspContext().getOut(); out.println( message ); } else { /* use message from the body */ getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } }
The attribute's name is "message", so the setter method is setMessage(). Let us now add this attribute in the TLD file using the <attribute> element as follows −
<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> </attribute> </tag> </taglib>
Let us follow JSP with message attribute as follows −
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello message = "This is custom tag" /> </body> </html>
This will produce the following result −
This is custom tag
- Related Articles
- I want to create a custom tag in JSP. How to write a custom tag in JSP?
- How a JSP page works. Can somebody explains the JSP architecture in simpler terms
- What are the standard attributes that should be passed to a custom tag in a JSP page?
- What is an exception Object in JSP? What type of exceptions can occur in a JSP page?
- How to create a common error page using JSP?
- How to apply if tag in JSP?
- How to apply choose tag in JSP?
- How to apply forEach tag in JSP?
- How to apply forTokens tag in JSP?
- What are JSP declarations? In how many ways we can write JSP declarations?
- I want to use %> literal in JSP page. But it is throwing error. How to escape this syntax in JSP?
- How to avoid Java code in jsp page?
- What is JSP page redirection?
- What is autoFlush attribute in JSP?
- What is contentType attribute in JSP?

Advertisements