Mental Jetsam

By Peter Finch

Archive for the ‘Programming’ Category

Programming Language topics

Custom taglib in Tomcat 7

Posted by pcfinch on April 12, 2012

The following is a simple example for creating a custom tag library (taglib) for the Apache Tomcat JSP server and could be used as a simple template engine.

  1. Create a taglib definition file in “WEB-INF/jsp/mytaglib.tld”.

    <taglib>  
        <tlib-version>1.0</tlib-version>  
        <jsp-version>1.2</jsp-version>  
        <short-name>example tags</short-name>  
        <uri>http://www.peterfinch.me/mytag</uri>  
        <tag>  
            <name>menu</name>  
            <tag-class>me.peterfinch.MenuTag</tag-class>  
        </tag>  
        <tag>  
            <name>master</name>  
            <tag-class>me.peterfinch.MasterTag</tag-class>  
        </tag>  
    </taglib>
    
  2. Add taglib section to web.xml

    <web-app>
    ...
    <jsp-config>
      <taglib>
        <taglib-uri>http://www.peterfinch.me/mytag</taglib-uri>
        <taglib-location>/WEB-INF/jsp/mytaglib.tld</taglib-location>
      </taglib>
    </jsp-config>
    </web-app>
    
  3. Create MasterTag Java class to handle the tag events. This class wraps the encoded HTML (generated by the JSP) and could be used as a simple page template.

    package me.peterfinch;
    import java.io.IOException;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.JspWriter;
    import javax.servlet.jsp.tagext.BodyContent;
    import javax.servlet.jsp.tagext.BodyTagSupport;
    
    public class MasterTag extends BodyTagSupport {
    	
    	@Override
    	public int doAfterBody() throws JspException {
    		try {
    			BodyContent bodycontent = getBodyContent();
    			String body = bodycontent.getString();
    			JspWriter out = bodyContent.getEnclosingWriter();
    			out.print("<div class='master' style='border:1px solid black'>") ;
    			out.print(body) ;
    			out.print("</div>") ;
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return SKIP_BODY;
    	}
    }
    
  4. Add MenuTag Java class handler. This just replaces the tag, and it’s contents with some predefined HTML and could be used as a Menu (or anything else you desire)

    package me.peterfinch;
    import java.io.IOException;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.JspWriter;
    import javax.servlet.jsp.tagext.BodyTagSupport;
    
    public class MenuTag extends BodyTagSupport {
    	
    	@Override
    	public int doAfterBody() throws JspException {
    		try {
    			String i = this.pageContext.getRequest().getParameter("i") ;
    			JspWriter out = bodyContent.getEnclosingWriter();
    			out.print("<a href='index.jsp'>Home</a> " + i) ;
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return SKIP_BODY;
    	}
    }
    
  5. Add taglib definition to JSP page

    <%@ taglib uri="http://www.peterfinch.me/mytag" prefix="my" %>
    
  6. Add the custom tags to to your page

    <my:master>
    <my:menu></my:menu>
    <h1>Hello from index.jsp</h1>
    </my:master>
    
  7. Advertisements

Posted in JSP | Leave a Comment »

Google Developer Day 2011 HTML 5 Challenge

Posted by pcfinch on August 22, 2011

I entered the Google Developer Day 2011 HTML5 challenge, to create a “Google doogle” of the Developer Day Logo entirely in HTML, and I actually made the cut… top 3 in Australia, I’m very happy 🙂

https://sites.google.com/site/opencallforgdd/the-challenge-1

http://www.peterfinch.me/gdd2011/

Posted in HTML, javascript, Personal | Leave a Comment »

Accessing DataSource values from within a DataList ItemTemplate

Posted by pcfinch on June 29, 2011

The following C# (ASP.NET) code example shows a couple of ways to access the values returned by a asp:SqlDataSource from within a asp:DataList asp:ItemTemplate. The difficult part was accessing the data sources values and passing them to nested ASP controls like asp:Buttons and asp:ImageButtons.

<asp:SqlDataSource ID="ds" runat="server"
  ConnectionString="<%$ ConnectionStrings:portal %>"
  SelectCommand="select did, title, did from documents">
</asp:SqlDataSource>
<asp:DataList ID="dl" runat="server" DataSourceID="ds">
  <ItemTemplate>
    <div class="result">
      <a href='details.aspx?id=<%#Eval("did")%>>
      <div class="title"><%#Eval("title")%></div>
      <asp:ImageButton ID="butDelete" runat="server"
        ToolTip="Delete"
        ImageUrl="images/delete.png"
        OnClick="butDelete_Click"
        OnClientClick="javascript:confirm('Block comment thread?')"
        CommandName="delete"
        CommandArgument='<%# DataBinder.Eval(Container, "DataItem.did") %>' />
    </div>
  </ItemTemplate>
</asp:DataList>

In order to response to a click on one of the dynamically generated delete buttons use the following code.

protected void butDelete_Click (object sender, ImageClickEventArgs e)
{
  String command = ((ImageButton)sender).CommandName;
  if ("delete" == command) {
    int dId = Int16.Parse(((ImageButton)sender).CommandArgument);
    using(portalConnection portal = new PortalConnection())
    {
      portal.Delete(dId);
    }
    dl.DataBind();
  }
}

Posted in C#.NET | Leave a Comment »

ASP.NET catch “A potentially dangerous Request”

Posted by pcfinch on April 7, 2011

ASP.NET has a handy little feature enabled that filters requests that may be dangerous from the application. One of these is a check for HTML code that may be in a response field in order to avoid the possibility of injecting malicious code onto websites. It’s a nice security feature, and easy to disable by just adding “ValidateRequest=’false'” to the Page directive.


<%@ Page Language="C#" MasterPageFile="~/site.master" AutoEventWireup="true" CodeFile="myWebPage.aspx.cs" Inherits="details" Title="Test" ValidateRequest="false"%>

However, if you want to leave it turn on but avoid the nasty C# exception, that gets thrown when it happens, you can either override the default error page in ASP.NET or the following code can catch (trap) the HttpRequestValidationException exception and render a custom message, or redirect to your own error page.

public partial class myWebPage: System.Web.UI.Page {
 virtual public void ProcessRequest(HttpContext context) {
   try {
     Page.ProcessRequest(context);
   } catch (HttpRequestValidationException) {
     context.Response.Write("Danger");
   }
 }
}

I’m not sure if this is the official way to do it, but it works.

 

Posted in C#.NET | Leave a Comment »