Class 2 | Intermediate Java 30-IT-397 |
replace.java
package edit;
// import the necessary libraries.
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/**
* Simple custom JSP tag that prints a copyright where inserted.
*
* 12/18/2001 jonesbr@email.uc.edu
**/
public class Replace extends BodyTagSupport {
String remove = new String();
String add = new String();
/**
* method doAfterBody
*
* Gets the body between the tags, replaces
the remove text with the add text.
*
* @author jonesbr@email.uc.edu
* date December 30, 2001
*/
public int doAfterBody() {
try {
// Get the BodyContent object to manipulate the body.
BodyContent body = getBodyContent();
// Call the change method to swap these values.
String newBody = change(body.getString(), remove, add);
// Get the output stream so that we can write the new body out.
JspWriter out = body.getEnclosingWriter();
out.print(newBody);
} catch (IOException
e) {
System.out.println("IOException in Replace: " + e);
} catch (Exception e)
{
System.out.println("Exception in Replace " + e);
}
// Let them know I'm
finished.
return(SKIP_BODY);
}
private String change(String body, String remove,
String add) {
StringBuffer returnString
= new StringBuffer();
int fromIndex = 0;
int location = body.indexOf(remove,
fromIndex);
while(location != -1)
{
returnString.append(body.substring(fromIndex, location));
returnString.append(add);
fromIndex = location + remove.length();
location = body.indexOf(remove, fromIndex);
}
// Add the last chunk,
or the whole thing if remove was never present.
returnString.append(body.substring(fromIndex,
body.length()));
return returnString.toString();
}
// setter method for the remove attribute.
public void setRemove(String remove) {
this.remove = remove;
}
// setter method for the add attribute.
public void setAdd(String add) {
this.add = add;
}
// End the class.
}
Created by: Brandan Jones December 17, 2001