Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Thursday, September 04, 2008

How to Split a String Based on a Delimeter using Java


<form action="testdissect.jsp" method="POST">
<textarea name="stuff"></textarea>
<input type="submit" value="split"/>
</form>
output:<br/>
<%
if(request.getParameter("stuff")!=null) {
String stuff = (java.lang.String) request.getParameter("stuff");
stuff = stuff.replaceAll("\\n|\\r",""); // (optional) remove line breaks
String[] chunks = stuff.split(";");
for(int i=0; i < chunks.length; i++)
out.println("["+i+"] "+chunks[i]);
}

%>

Sunday, December 11, 2005

Passing Values Out from a JSP 2.0 .tag file

This is really poorly documented on the web, so here goes:

There seem to be two ways to get data OUT of a tag.

Method #1:

Use the request scope. Inside the .tag file, try this:


<%

String led = "zeppelin";

request.setAttribute("led", led);

%>


If you need to vary the name of the request Attribute, pass it in to the .tag file in an attribute then use jspContext.getAttribute(nameOfYourTagAttributeHere) to grab it into a String.

Anyhow, now you can access it in the calling JSP using EL.


<c:out value="${led}"/>


Method #2:

I've only read about this one, haven't tried it, but here goes:

A tag receives input through its attributes. In addition to the output text produced by the tag file, a tag can also "output" data by creating EL variables. A tag file might return a value to the page that called it as follows:

<%@ variable name-given="filesincluded" scope="AT_END" %>

The "name-given" provides the name of the variable to set in the page after the tag has completed. "AT_END" specifies that the variable is set when the tag file completes.

How to Pass a HashMap or Other Type into a JSP 2.0 tag file

First, lets assume your HashMap has the name "myHashMap"

Your call to the tag file could look like this:


<mytaglibrary:mytag map="${myHashMap}">


For me, the EL kept trying to change the hashmap to a string inside the .tag file. So I had to do the following at the top of the .tag file:

<%@ tag import="java.util.HashMap"%>
<%@ attribute name="map" required="true" type="java.util.HashMap"%>

Then I could use the map as usual:

The value of map.keyName is ${map.keyName}

Labels

Blog Archive

Contributors