JSP - issue with custom Taglib - java

I just tried to add a custom taglib to my project, such that the testtaglib.tld file contains:
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>name</shortname>
<tag>
<name>test</name>
<tagclass>taglib.TestTaglib</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>testCode</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
</tag>
<taglib>
And then I added taglib class TestTaglib.java
public class TestTaglib extends TagSupport {
private String testCode;
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
//doing some conversion with testCode
out.print(testCode);
return EVAL_PAGE;
} catch(IOException ioe) {
throw new JspException("Error: " + ioe.getMessage());
}
}
}
And then in .jsp file
<name:test testCode="${testCode}"/>
Okay the issue is:TestTaglib.java is recognizing values of testCode as ${testCode} and not the original value. Any suggestion?

Hi all inbuilt tag already handles the expression language. Just change your code as mentioned below and it will work fine.
public class TestTaglib extends TagSupport {
private String testCode;
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
//doing some conversion with testCode
String value = (String) ExpressionUtil.evalNotNull("test", "testCode", testCode, String.class, this, pageContext);
out.print(value);
return EVAL_PAGE;
} catch(IOException ioe) {
throw new JspException("Error: " + ioe.getMessage());
}
}
}
ExpressionUtil is class provided under org.apache.taglibs.standard.tag.el.core package.
Here is short desc of evalNotNull method args
1) tagName : your tag name is test
2) tagAttribute: to eval in your case it is testCode
3) expression : which is el expression ${testCode}
4) Value: Class of expression value whether it is Boolean,String or any Object
5) tagClass: Reference of tag handler class so you can pass this
6) pageContext: which is coming from TagSupport

Related

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

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);
}
}
}

Custom Tag implementation issue

I have customs tags as follows. repeat and heading tag have doAfterBody method implemented.Both of them extends BodyTagSupport class
<csajsp:repeat reps="5">
<LI>
<csajsp:heading bgColor="BLACK">
White on Black Heading
</csajsp:heading>
</LI>
</csajsp:repeat>
Repeat tag Class
public void setReps(String repeats) {
System.out.println("TESTING"+repeats);
//sets the reps variable.
}
public int doAfterBody() {
System.out.println("Inside repeate tag"+reps);
if (reps-- >= 1) {
BodyContent body = getBodyContent();
try {
JspWriter out = body.getEnclosingWriter();
System.out.println("BODY"+body.getString());
out.println(body.getString());
body.clearBody(); // Clear for next evaluation
} catch(IOException ioe) {
System.out.println("Error in RepeatTag: " + ioe);
}
return(EVAL_BODY_TAG);
} else {
return(SKIP_BODY);
}
}
Class of Heading tag
public int doAfterBody()
{
System.out.println("inside heading tag");
BodyContent body = getBodyContent();
System.out.println(body.getString());
try {
JspWriter out = body.getEnclosingWriter();
out.print("NEW TEXT");
} catch(IOException ioe) {
System.out.println("Error in FilterTag: " + ioe);
}
// SKIP_BODY means I'm done. If I wanted to evaluate
// and handle the body again, I'd return EVAL_BODY_TAG.
return(SKIP_BODY);
}
public int doEndTag() {
try {
JspWriter out = pageContext.getOut();
out.print("NEW TEXT 2");
} catch(IOException ioe) {
System.out.println("Error in HeadingTag: " + ioe);
}
return(EVAL_PAGE); // Continue with rest of JSP page
}
Custom tag tld file is
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>csajsp</shortname>
<uri></uri>
<tag>
<name>heading</name>
<tagclass>com.test.tags.HeadingTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>bgColor</name>
<required>true</required> <!-- bgColor is required -->
</attribute>
</tag>
<tag>
<name>repeat</name>
<tagclass>com.test.tags.RepeatTag</tagclass>
<info>Repeats body the specified number of times.</info>
<bodycontent>JSP</bodycontent>
<attribute>
<name>reps</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
The order in which SOP are printed is
Setter method of csajsp:repeat is called.
White on Black Heading is printed. ie doAfterBody of csajsp:heading tag is called.
I don't know why it is not calling doAfterBody of csajsp:repeat tag.
Please help me to understand this.
What class do your tags extend?
The default behaviour of TagSupport is to return SKIP_BODY, which would skip processing of the tag body.
The default behaviour of BodyTagSupport is to return EVAL_BODY_BUFFERED, which would process the tag body.
If you are implementing BodyTag yourself, then you need to make sure you override doStartTag correctly to indicate that the JSP body should be evaluated.

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.

Property Editor not registered with the PropertyEditorManager error on Custom Validation Tag (java)

I am using TomCat 5.5 with MyFaces 1.1 and am trying to implement a custom regex validation tag.
My RegExValidator class looks like this:
public class RegExValidator implements Validator, StateHolder {
private String regex;
private boolean transientValue = false;
public RegExValidator() {
super();
}
public RegExValidator(String regex) {
this();
this.regex = regex;
}
public void validate(FacesContext context, UIComponent component, Object toValidate) throws ValidatorException {
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
if (!(component instanceof UIInput)) {
return;
}
if (null == regex || null == toValidate) {
return;
}
String val = (String) toValidate;
if (!val.matches(regex)) {
FacesMessage errMsg = MessageFactory.createFacesMessage(context, Constants.FORMAT_INVALID_MESSAGE_ID, FacesMessage.SEVERITY_ERROR, (new Object[]{regex}));
throw new ValidatorException(errMsg);
}
}
public Object saveState(FacesContext context) {
Object[] values = new Object[1];
values[0] = regex;
return (values);
}
public void restoreState(FacesContext context, Object state) {
Object[] values = (Object[]) state;
regex = (String) values[0];
}
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
this.regex = regex;
}
public boolean isTransient() {
return transientValue;
}
public void setTransient(boolean transientValue) {
this.transientValue = transientValue;
}
}
My RegExValidatorTag class looks like this:
#SuppressWarnings("serial")
public class RegExValidatorTag extends ValidatorELTag {
private static String validatorID = null;
protected ValueExpression regex = null;
public RegExValidatorTag() {
super();
if (validatorID == null) {
validatorID = "RegExValidator";
}
}
public Validator createValidator() throws JspException {
FacesContext facesContext = FacesContext.getCurrentInstance();
RegExValidator result = null;
if (validatorID != null) {
result = (RegExValidator) facesContext.getApplication().createValidator(validatorID);
}
String patterns = null;
if (regex != null) {
if (!regex.isLiteralText()) {
patterns = (String) regex.getValue(facesContext.getELContext());
} else {
patterns = regex.getExpressionString();
}
}
result.setRegex(patterns);
return result;
}
public void setValidatorID(String validatorID) {
RegExValidatorTag.validatorID = validatorID;
}
/**
* #param regex
* the regex to set
*/
public void setRegex(ValueExpression regex) {
this.regex = regex;
}
}
My Taglibrary Descriptor looks like this:
<tag>
<name>regexValidator</name>
<tag-class>com.company.components.taglib.RegExValidatorTag</tag-class>
<attribute>
<name>regex</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
My face-common-config.xml has a Validator tag like this:
<validator>
<description>
Validate an input string value against a regular
expression specified by the "regex" attribute.
</description>
<validator-id>RegExValidator</validator-id>
<validator-class>com.company.components.validators.RegExValidator</validator-class>
<attribute>
<description>
The regular expression to test the value against
</description>
<attribute-name>regex</attribute-name>
<attribute-class>java.lang.String</attribute-class>
</attribute>
</validator>
And later on it is supposed to be used in a jsp file like this:
<tc:in value="${dataBean.currentBean.field}">
<a:regexValidator regex="${dataBean.currentBean.validationRegEx}" />
</tc:in>
When calling the page, the following error comes up:
javax.servlet.ServletException: javax.servlet.jsp.JspException: org.apache.jasper.JasperException: Unable to convert string "[\d{4}]" to class "javax.el.ValueExpression" for attribute "regex": Property Editor not registered with the PropertyEditorManager
Caused by:
org.apache.jasper.JasperException - Unable to convert string "[\d{4}]" to class "javax.el.ValueExpression" for attribute "regex": Property Editor not registered with the PropertyEditorManager
I hope I provided enough details for someone to help me out on this...
I seem to have a similar problem like yours, I'm trying to find the solution but seems that the problem is when using Tomcat or the application server(WebSphere Application Server 7.0) JSF libraries, my problem is that the new application server has new JSF libraries (1.2) instead of the 1.1 libraries that my old application server had. (Version 6.1)
To be more specific. my problem is described here. http://www-01.ibm.com/support/docview.wss?uid=swg21318801

cannot use values from beans in facelets custom component

i cannot use any bean value in my custom control.:
for instance:
this is my foo.taglib.xml file.
<facelet-taglib>
<namespace>http://www.penguenyuvasi.org/tags</namespace>
<tag>
<tag-name>test</tag-name>
<component>
<component-type>test.Data</component-type>
</component>
</tag>
</facelet-taglib>
faces-config.xml
<component>
<component-type>test.Data</component-type>
<component-class>test.Data</component-class>
</component>
test.Data class
package test;
import java.io.IOException;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
public class Data extends UIComponentBase {
private Object msg;
#Override
public String getFamily() {
return "test.Data";
}
#Override
public void encodeBegin(FacesContext context) throws IOException {
super.encodeBegin(context);
context.getResponseWriter().write(msg.toString());
}
public void setMsg(Object msg) {
this.msg = msg;
}
}
Bean.java:
package test;
public class Bean {
private String temp = "vada";
public String getTemp() {
return temp;
}
}
test.xhtml (doesn't work)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://www.penguenyuvasi.org/tags">
<py:test msg="#{bean.temp}" />
</html>
test.xhtml (works)
<py:test msg="#{bean.temp}" />
In your test.Data class, I suggest that you implement the getter for msg like that:
public String getMsg() {
if (msg != null) {
return msg;
}
ValueBinding vb = getValueBinding("msg");
if (vb != null) {
return (String) vb.getValue(getFacesContext());
}
return null;
}
And then, in your encodeBegin method:
...
context.getResponseWriter().write(getMsg());
...
This getter method is needed in order to evaluate the expression you may give to the msg attribute in your JSF page.
Edit, to use ValueExpression instead of the deprecated ValueBinding:
ValueExpression ve = getValueExpression("msg");
if (ve != null) {
return (String) ve.getValue(getFacesContext().getELContext());
}

Categories