JSP/Java/HTML | JSP out.println(); prints to console when in method - java

I'm working a dynamic website with jsp.
Now my problem: when I use <%, to write my java, everything works perfectly fine.
<%
out.println("<p>test</p>");
%>
But when i use the <%! like this:
<%!
private void test() {
out.println("<p>test</p>");
}
%>
My output will get displayed in my code editors console and not on my website as expected.
As import I used <%# page import="static java.lang.System.out" %>. Is this the correct import or is the problem somewhere else?
If more information is needed please comment! :)

As you probably know, JSPs are turned into servlets on-the-fly by the Java EE container. In a <% ... %> block, out is a local variable in the generated _jspService (or similar) method in the generated servlet. It's a JspWriter for writing to the output for the page.
In a <%! ... %> block, you're outside that generated _jspService (or similar) method, and so your static import means your out reference is to System.out, which isn't where the page output should be sent.
If you want to define methods in your JSP in <%! ... %> blocks, you'll have to pass out into them:
<%!
private void test(JspWriter out) throws IOException {
out.println("<p>test</p>");
}
%>
About that JSP -> servlet thing, say we have this JSP:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<%
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
%>
<%!
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
%>
</body>
</html>
Note that it has a <%...%> block and a <%! ... %> block.
The Java EE container turns that into something somewhat like the following. Note where our test method ended up, and where the code in our <%...%> block ended up (along with our raw JSP text/markup):
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
/* ...lots of setup stuff omitted... */
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!doctype html>\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta charset=\"utf-8\">\n");
out.write("<title>Example</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

Related

Java: JNDI Lookup fails when ran inside a Thread

I'm facing a rather strange behaviour regarding JNDI lookup using Wildfly 18. I have one simple EJB:
package com.getronics.ejb;
import javax.ejb.Remote;
import javax.ejb.Local;
import javax.ejb.Stateless;
#Stateless
#Local(ICalculadoraLocal.class)
public class CalculadoraBean implements ICalculadoraLocal {
public int suma(int a, int b){
return a+b;
}
}
With a simple interface:
package com.getronics.ejb;
public interface ICalculadoraLocal{
int suma(int a, int b);
}
And a simple JSP page to check it out:
<html>
<body>
<%# page import="java.util.Hashtable,javax.naming.*,com.getronics.ejb.*" %>
request: <%= request.getRequestURI()%><br>
<%
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
ICalculadoraLocal calculadora = (ICalculadoraLocal)context.lookup("java:app/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal");
int suma = calculadora.suma(2,2);
%>
context: <%= context%></br>
2+2= <%=suma%>
</body>
</html>
This works fine:
request: /ejb/index.jsp
context: javax.naming.InitialContext#3e532295
2+2= 4
However, when I try to use a Thread, like this:
<html>
<body>
<%# page import="java.util.Hashtable,javax.naming.*,com.getronics.ejb.*" %>
request: <%= request.getRequestURI()%><br>
<%
new Thread() {
public void run() {
try {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
ICalculadoraLocal calculadora = (ICalculadoraLocal)context.lookup("java:app/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal");
int suma = calculadora.suma(2,2);
System.out.println("suma: " + suma);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
%>
</body>
</html>
It throws a NameNotFoundException:
javax.naming.NameNotFoundException: java:app/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal
Any ideas on why can this happen?
It seems that using "global" instead of "app" makes it work:
ICalculadoraLocal calculadora = (ICalculadoraLocal)context.lookup("java:global/ear-0.0.0.0.0.1/ejb-0.0.0.0.0.1/CalculadoraBean!com.getronics.ejb.ICalculadoraLocal");
The reason seems to be that JNDI lookup of "app", "module" and "comp" won't work in those threads as for specification.
You can check these links for more info:
jndi lookup fails in user-thread
[jboss-as7-dev] Issue with access to java:comp/UserTransaction from non EE threads

Display dynamically generated image to the browser using jsp

I am doing a small project with images using jsp/servlets.In that I generate some image dynamically(actually I'll decrypt two image shares as one).That decrypted image must be displayed directly to browser without saving it as file in filesystem.
Crypting c=new Crypting();
BufferedImage imgKey;
BufferedImage imgEnc;
imgKey = ImageIO.read(new File("E:/Netbeans Projects/banking/web/Key.png"));
imgEnc=ImageIO.read(new File("E:/Netbeans Projects/banking/build/web/upload/E.png"));
BufferedImage imgDec=Crypting.decryptImage(imgKey,imgEnc);
When I store it in filesystem and display it using <img> it does not show the image.When reloaded it shows the image.So it is problem with the backend work of IDE.
Any help pls...
Make a servlet to generate images.
Use html img tag with attribute src, as a path to your genarated resource.
Example in spring boot (QR Codes).
Servlet
public class QRCodeServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = req.getParameter("url");
String format = req.getParameter("format");
QRCodeFormat formatParam = StringUtils.isNotEmpty(format) && format.equalsIgnoreCase("PDF") ?
QRCodeFormat.PDF : QRCodeFormat.JPG;
if(formatParam.equals(QRCodeFormat.PDF))
resp.setContentType("application/pdf");
else
resp.setContentType("image/jpeg");
if(StringUtils.isNotBlank(url)) {
ByteArrayOutputStream stream = QRCodeService.getQRCodeFromUrl(url, formatParam);
stream.writeTo(resp.getOutputStream());
}
}
}
Configuration:
#Configuration
public class WebMvcConfig {
#Bean
public ServletRegistrationBean qrCodeServletRegistrationBean(){
ServletRegistrationBean qrCodeBean =
new ServletRegistrationBean(new QRCodeServlet(), "/qrcode");
qrCodeBean.setLoadOnStartup(1);
return qrCodeBean;
}
}
Conroller:
String qrcodeServletPrefix = "http://localhost:8082/qrcode?url="
String encodedUrl = URLEncoder.encode("http://exmaple.com?param1=value1&param2=value2", "UTF-8");
modelAndView.addObject("qrcodepage", qrcodeServletPrefix + encodedUrl);
modelAndView.setViewName("view");
view.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<img src="<c:url value='${qrcodepage}'/>" />

get image url of rss with rome library

I having a rss file in following :
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title> سایپا نیوز </title>
<link>http://www.saipanews.com/</link>
<description></description>
<language>fa</language>
<item>
<author></author>
<pretitle></pretitle>
<title>پیام تبریک دکتر جمالی به مناسبت فرارسیدن سالروز ولادت حضرت علی(ع) و روز پدر</title>
<link>http://www.saipanews.com/view-6751.html</link>
<pubdate>2016-04-20 10:58:00</pubdate>
<description>سایپا نیوز: مدیرعامل گروه خودروسازی سایپا همزمان با فرارسیدن سالروز میلاد باسعادت حضرت علی(ع) و روز پدر، طی پیامی به تمامی پدران متعهد و پرتلاش ایران زمین تبریک گفت.</description>
<secid>0</secid>
<typid>8</typid>
<image>http://www.saipanews.com/media/image/jamali/jmali.JPG</image>
</item>
<item>
<author></author>
<pretitle></pretitle>
<title>فرهنگ رانندگی بین خطوط در معابر شهری در حال گسترش است </title>
<link>http://www.saipanews.com/view-6748.html</link>
<pubdate>2016-04-19 11:27:00</pubdate>
<description>سایپا نیوز: به گزارش سایپا نیوز و به نقل از فرارو، از آنجایی که فرهنگ رانندگی مجموعه ای از رفتارهای درست رانندگی و آداب زندگی اجتماعی بهنگام تردد در شهرها و جاده ها است، رانندگی در بین خطوط معابر شهری یکی از نمادهای فرهنگ رانندگی در کشورهای درحال توسعه و توسعه یافته می باشد.</description>
<secid>0</secid>
<typid>8</typid>
<image>http://www.saipanews.com/media/image/farhang%20ranandegi/252887_331.jpg</image>
</item>
</channel>
</rss>
I want to get image's urls.
I use Rome library but not found any solution.
how to get image's url in item with Rome library ?
I for that get image tag , build new rss parser on the following:
public class NewRssParser extends RSS094Parser implements WireFeedParser {
public NewRssParser() {
this("rss_2.0");
}
protected NewRssParser(String type) {
super(type);
}
protected String getRSSVersion() {
return "2.0";
}
protected boolean isHourFormat24(Element rssRoot) {
return false;
}
protected Description parseItemDescription(Element rssRoot, Element eDesc) {
Description desc = super.parseItemDescription(rssRoot, eDesc);
desc.setType("text/html"); // change as per
// https://rome.dev.java.net/issues/show_bug.cgi?id=26
return desc;
}
public boolean isMyType(Document document) {
boolean ok;
Element rssRoot = document.getRootElement();
ok = rssRoot.getName().equals("rss");
if (ok) {
ok = false;
Attribute version = rssRoot.getAttribute("version");
if (version != null) {
// At this point, as far ROME is concerned RSS 2.0, 2.00 and
// 2.0.X are all the same, so let's use startsWith for leniency.
ok = version.getValue().startsWith(getRSSVersion());
}
}
return ok;
}
#Override
public Item parseItem(Element arg0, Element arg1) {
Item item = super.parseItem(arg0, arg1);
Element imageElement = arg1.getChild("image", getRSSNamespace());
if (imageElement != null) {
String imageUrl = imageElement.getText();
Element urlElement = imageElement.getChild("url");
imageUrl = urlElement != null ? urlElement.getText() : imageUrl;
Enclosure enc = new Enclosure();
enc.setType("image");
enc.setUrl(imageUrl);
item.getEnclosures().add(enc);
}
return item;
}
}
in the class override parseItem method and add code for get image element and add image's url to Enclosures.
then add following line to rome.properties file :
WireFeedParser.classes=[packge name].NewRssParser
Example :
WireFeedParser.classes=ir.armansoft.newscommunity.newsgathering.parser.impl.NewRssParser
Rome wont provide the <image> tag because it does not belong to the namespace it is in. So the feed isn't valid:
line 18, column 3: Undefined item element: image (29 occurrences) [help]
<image>http://www.saipanews.com/media/image/%D8%AA%D9%88%D9%84%D9%8A%D8%A ...
If the image tag would be in a different namespace, like this:
<image:image>http://www.saipanews.com/media/image/%D8%AA%D9%88%D9%84%D9%8A%D8%AF/2.jpg</image:image>
You could get foreing markup in this way:
for(SyndEntry entry : feed.getEntries()) {
for (Element element : entry.getForeignMarkup()) {
System.out.println("element: " + element.toString());
}
}
And the result would be
element: [Element: <image:image [Namespace: http://purl.org/rss/1.0/modules/image/]/>]
Unless the feed is fixed, It seems that there isn't a way to get the image url with Rome library at the moment.
The Answer is so simple.
First get the syndContent using the Roam API.
Find the code for the reading images and all content from RSS
<%# page import="com.rometools.rome.feed.synd.SyndFeed"%>
<%# page import="com.rometools.rome.feed.synd.SyndEntry"%>
<%# page import="com.rometools.rome.feed.synd.SyndContent"%>
<%# page import="com.rometools.modules.mediarss.MediaEntryModule"%>
<%# page import="com.rometools.rome.feed.module.Module"%>
<%# page import="com.rometools.modules.mediarss.types.Thumbnail"%>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.List"%>
<html>
<head>
<title>website</title>
<link href="/css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Home</h1>
<%
HttpSession session1=request.getSession(false);
SyndFeed syndFeed11= (SyndFeed) session1.getAttribute("syndFeed");
%>
<h2><%=syndFeed11.getTitle()%></h2>
<ul>
<%
Iterator it = syndFeed11.getEntries().iterator();
while (it.hasNext())
{
SyndEntry entry = (SyndEntry) it.next();
%>
<li><%=entry.getTitle()%> <%
List<SyndContent> syndContents=entry.getContents();
System.out.println(syndContents.size());
for(SyndContent syndContent:syndContents)
{
System.out.println(syndContent.getMode());
System.out.println("This is content"+syndContent.getValue());
%>
//This is The STRING WHICH CONTAINS the link to the image apply regex expression to get SAMPLE_LINK out of "<img src"LINK">"
<%=syndContent.getValue() %>>
<%
}
//SyndContent syndContent=syndContents.get(0);
for (Module module : entry.getModules()) {
if (module instanceof MediaEntryModule) {
MediaEntryModule media = (MediaEntryModule)module;
for (Thumbnail thumb : media.getMetadata().getThumbnail()) {
%><img src="<%=thumb.getUrl() %>" />
<%
}
}
}
%></li>
<% } %>
</ul>
</body>
</html>
Bellow is the Servlet Class:-
package website.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
public class HomeServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private Logger logger = Logger.getLogger(this.getClass());
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String rssUrl=(String)req.getAttribute("rss");
logger.debug("Retrieving yahoo news feed");
URL url = new URL("https://www.reddit.com/.rss");
SyndFeedInput syndFeedInput = new SyndFeedInput();
HttpSession session=req.getSession();
SyndFeed syndFeed = null;
XmlReader xmlReader = new XmlReader(url);
try {
syndFeed = syndFeedInput.build(xmlReader);
System.out.println("Donr");
} catch (IllegalArgumentException e) {
logger.error("", e);
} catch (FeedException e) {
logger.error("", e);
}
logger.debug("Forwarding to home.jsp");
req.setAttribute("syndFeed11", syndFeed);
PrintWriter out = resp.getWriter();
out.println("<h1>");
out.println();
session.setAttribute("syndFeed", syndFeed);
out.println("</h1>");
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/WEB-INF/jsp/home.jsp");
dispatcher.forward(req,resp);
}
}
I solved this problem by parsing the feed with Rome and then parsing it again to get the raw jdom Document. Then I can get the item elements from the feed and look for images. Bit hacky but it easier than extending the RSS parsers and so on.
byte[] data = ... bytes for the feed ...
SyndFeedInput input = new SyndFeedInput()
input.allowDoctypes = true
SyndFeed sf = input.build(new XmlReader(new ByteArrayInputStream(data)))
Document doc = new MyWireFeedInput().getDocument(new XmlReader(new ByteArrayInputStream(data)))
Element channel = doc.rootElement.getChild("channel")
List<Element> items = channel ? channel.getChildren("item") : null
List<SyndEntry> entries = sf.entries
for (int i = 0; i < entries.size(); i++) {
SyndEntry entry = entries[i]
Element item = items ? items[i] : null
if (item) {
Element image = item.getChild("image")
... add it to enclosures or whatever ...
}
}
Here is the class that gets the jdom Document:
/**
* This is a hack to get at the protected {#link WireFeedInput#createSAXBuilder()} method so we can get the
* raw jdom document for the feed to extract elements (e.g. 'image') not parsed by the built in feed parsers.
*/
public class MyWireFeedInput extends WireFeedInput {
Document getDocument(Reader reader) {
final SAXBuilder saxBuilder = createSAXBuilder();
try {
if (xmlHealerOn) reader = new XmlFixerReader(reader)
return saxBuilder.build(reader);
} catch (final JDOMParseException ex) {
throw new ParsingFeedException("Invalid XML: " + ex.getMessage(), ex);
} catch (final IllegalArgumentException ex) {
throw ex;
} catch (final Exception ex) {
throw new ParsingFeedException("Invalid XML", ex);
}
}
}

JQuery/AJAX code error - text not displayed on typing in textbox

I have this jsp document (below). Basically, when user types in the textbox, I want to show an error if the username exists in the database/ length<5, etc.
I want these errors to be simultaneously displayed without any refresh through jQuery/AJAX. I did this but it doesn't seem to be working. Here, CheckAvailability and Success are servlets and CheckAVailability checks the existence in database.
the JSP file:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.11.3.js"></script>
<script>
$(document).ready(function() {
$('#username').keyup(function() {
var name = $('#username').val();
$.get('CheckAvailability?username='+name,function(responseText){
$('#status').text(responseText);});}); 
</script>
</head>
<body>
<form id="login_form" ><input type="text" placeholder="username" name="username" class="style-4" required="required" action="Success"/>
<div id="status"> </div>
CheckAvailability Servlet
public class CheckAvailability extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn=null;
Statement s=null;
ResultSet rs=null;
PreparedStatement ps;
try {
//make connection
String userid = request.getParameter("username");
String arr;
Class.forName("oracle.jdbc.OracleDriver");
if (userid.equals("")) {
arr = "Error: User name cannot be empty";
} else if(userid.length()<5){
arr="Error: Username cannot be less than 5 characters.";
}
else
{
String table="user1.app_users";
String p = "alpha";//database password
String query = "select userid from " + table + " where userid='" + userid + "'";
String url = "jdbc:oracle:thin:system/" + p + "#localhost:1521:XE";
conn = DriverManager.getConnection(url);
s = conn.createStatement();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
if (!rs.next()) {
arr="UserID <b>" + userid + "</b> is available.";
} else {
arr= "Error: UserID <b>" + userid + "</b> is already in use.";
}
}
response.setContentType("text/plain");
response.getWriter().write(arr);
}catch (SQLException se) {
out.println("Error ->" + se.getMessage());
} catch(ClassNotFoundException ce)
{
out.println("Error ->" + ce.getMessage());
}finally {
out.close();
}
}
}
But this isn't displaying anything as I type in the text box. The servlet did fire on hitting on submit. What didn't happen was that the text didn't display alongside. The code executes, no error in my IDE on that. I can't exclusively run the servlet, it gives the error: 'HTTP method GET is not supported by this URL', i.e. when I run it with parameters. I took the input inside as in, String username="user12", and that didn't run either. Can anybody point out my mistake? I'm new to jQuery/AJAX.
This worked for me:
$(document).ready(function() {
$('#userid').keyup(function(event) {
var user=$('#userid').val();
$.get('CheckValidity',{username:user},function(responseText) {
$('#status').text(responseText);
});
});
});
Had to use a different JQuery.
Overrride doGet, because javax.servlet.http.HttpServlet doesn't have any processRequest method.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("hi " + req.getParameter("username"));
}
Read this
Anyway.. how are you declaring your servlet? Through annotations? In web.xml? And what's the URL pattern?
if using web.xml:
<servlet>
<servlet-name>CheckAvailability Servlet</servlet-name>
<servlet-class>your.package.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability Servlet</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
if using annotations:
#WebServlet("/CheckAvailability")
public class Serv extends HttpServlet {
// ...
}

JSP Custom Taglib: Nested Evaluation

Say I have my custom taglib:
<%# taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
Inside the taglib class I need to process a template and tell the JSP to re-evaluate its output, so for example if I have this:
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
The output I have is:
<c:out value="My enclosed tag"/>
Test
When I actually need to output this:
My enclosed tag
Test
Is this feasible? How?
Thanks.
Tiago, I do not know how to solve your exact problem but you can interpret the JSP code from a file. Just create a RequestDispatcher and include the JSP:
public int doStartTag() throws JspException {
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
RequestDispatcher disp = request.getRequestDispatcher("/test.jsp");
try {
disp.include(request, response);
} catch (ServletException e) {
throw new JspException(e);
} catch (IOException e) {
throw new JspException(e);
}
return super.doStartTag();
}
I tested this code in a Liferay portlet, but I believe it should work in other contexts anyway. If it don't, I would like to know :)
HTH
what you really need to have is this:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
and change your doTag to something like this
#Override public void doTag() throws JspException, IOException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
// do something to the body here.
JspWriter out = bc.getEnclosingWriter();
if(body != null) {
out.print(buff.toString());
}
} catch(IOException ioe) {
throw new JspException("Error: "+ioe.getMessage());
}
}
make sure the jsp body content is set to jsp in the tld:
<bodycontent>JSP</bodycontent>
Why do you write a JSTL tag inside your doTag method?
The println is directly going into the compiled JSP (read: servlet) When this gets rendered in the browser it will be printed as it is since teh browser doesn't understand JSTL tags.
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
You can optionally add HTML tags to the string.

Categories