Today we are going to write a JSP web application program to find the entered string is Palindrome or not.
This program is a pure JSP web application, it is not a JSP – Servlet web application. Basically the JSP code is embedded with the HTML.
Logic to find the palindrome is very simple, reverse the entered string and compare the reversed string with the original string, if both are same then it is a Palindrome.
But, only reversing the string won’t help in some cases, some time people may enter a Palindrome sentences to check, and the sentence may contain dots, commas, spaces etc., In this case there are chances to fail comparing the strings. To avoid that, we need to remove spaces, special characters and also has to change the string to lower case.
Here is the complete JSP program to find a string is Palindrome or not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Check if a String is Palindrome or not in JSP - Tutorialsmade.com</title> </head> <body> <h2>Check if a String is Palindrome or not in JSP - Tutorialsmade.com!</h2> <form action="" method="post"> <label>Enter a Sentence or Word: </label><input type="text" name="string" /> </form> </body> </html> <% //check if post request if("POST".equalsIgnoreCase(request.getMethod())) { //define variables String mystring, revstring; Boolean Palindrome; //get the value from text box and convert into float mystring = request.getParameter("string"); //remove the spaces from string mystring = mystring.replace(" ", ""); //remove special characters from string mystring = mystring.replaceAll("[^A-Za-z0-9\\-]",""); //change all characteres to lowercase mystring = mystring.toLowerCase(); //reverse the string revstring = new StringBuilder(mystring).reverse().toString(); //check if both the entered string and the reverse string are same Palindrome = new String(mystring).equals(revstring); //if yes then palindrom, if no then it is not if(Palindrome){ out.println("<p>Hoorah! It is Palindrome</p>"); }else{ out.println("<p>Hmm! It is not a Palindrome</p>"); } } %> |
Read the comments in the program to understand it step by step.
What all you can learn from this above JSP script?
1. How to submit a Web form and get POST value in JSP? -> Ans: getParemeter().
2. How to remove spaces from string in JSP? -> Ans: replace()
3. How to use Regex to remove special characters in JSP? -> Ans: replaceAll()
4. How to Lowercase string / text in JSP? -> Ans: toLowerCase()
5. How to reverse a String in JSP? -> Ans: new StringBuilder(mystring).reverse().toString()
6. Finally, how to compare the strings in JSP? -> new String(mystring).equals(revstring)
Here are few Palindrome words / sentences to test the JSP script:
1. madam
2. mum
3. civic
4. Madam, I’m Adam
5. No lemon, no melon.