Friday, September 23, 2011

how to highlight multiple word in html page


I have created one server side logic to high light the multiple word

val - is my message in which i want to high light the word
matchWord - is array list of word to be high lighted
highlightWord() - is a function in which i replace word with span and return
string

now pass this string to jsp page and put it in to the div.


package com.idbi.intech.aml.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
* Servlet implementation class HighlightWord_servlet
*/
public class HighlightWord_servlet extends AMLProtectedServlet {
private static final long serialVersionUID = 1L;

@Override
public void performTask(HttpServletRequest request,
HttpServletResponse response, HttpSession session)
throws ServletException, IOException {

String val = "{1:F01EQBLKENAXXX0000000003}{2:O1030658090128CITIGB2LXXX20941550021103181130N}{4:"
+ ":20:3121835002"
+ ":32A:110607EUR500,"
+ ":50K:/FR7619106006520062842101348"
+ "MONSIEUR SLOVENIA GALIFI CHRISTIAN"
+ "74 AVENUE ALFRED BORRIGLIONE"
+ "06100 NICE"
+ ":59:/183104000075518"
+ "PAULINE MUMBI KAMAU"
+ "."
+ "."
+ ":70:VIREMENT FAMILIAL"
+ ":72:/IBK/KIMATHI STREET BRANCH"
+ ":71A:SHA" + "-}";

ArrayList matchWord = new ArrayList();

matchWord.add("GALIFI");
matchWord.add("PAULINE");
matchWord.add("BRANCH");
matchWord.add("VIREMENT");
matchWord.add("FR");

val = highlightWord(val, matchWord);

RequestDispatcher rd = request.getRequestDispatcher("./WEB-INF/JSPs/HighlightWord_jsp.jsp");
request.setAttribute("val", val);
rd.forward(request, response);
}

public String highlightWord(String str, ArrayList matchWord){

StringBuffer temp = new StringBuffer(str);

for (String string : matchWord) {

String patternStr = string;
String replacementStr = "" + string + "";

// Compile regular expression
Pattern pattern = Pattern.compile(patternStr);

// Replace all occurrences of pattern in input
Matcher matcher = pattern.matcher(temp);
temp = new StringBuffer(matcher.replaceAll(replacementStr));

}


return temp.toString();
}

}

No comments:

Post a Comment