I have the following block of code that works just fine:
<%@page import="java.util.*" %>
<%@page import="java.security.*" %>
<%
String str = "A string to hash.";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update( str.getBytes() );
byte[] digest = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0, j = digest.length; i < j; i++) {
String tmp = Integer.toHexString(0xFF & digest[i]);
if (tmp.length() < 2) {
tmp = "0" + tmp;
}
hexString.append(tmp);
}
out.println(hexString.toString());
%>
When I tried to break the hashing code out into a method I got a “NoSuchAlgorithmException” error when defining the MessageDigest object:
<%@page import="java.util.*" %>
<%@page import="java.security.*" %>
<%
String str = "A string to hash";
String md5string = md5hash(str);
out.println(md5string);
%>
<%!
public String md5hash(String str) {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update( str.getBytes() );
byte[] digest = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0, j = digest.length; i < j; i++) {
String tmp = Integer.toHexString(0xFF & digest[i]);
if (tmp.length() < 2) {
tmp = "0" + tmp;
}
hexString.append(tmp);
}
return hexString.toString();
}
%>
To get the JSP to compile, I had to modify it like so:
<%@page import="java.util.*" %>
<%@page import="java.security.*" %>
<%
String str = "A string to hash";
String md5string = md5hash(str);
out.println(md5string);
%>
<%!
public String md5hash(String str) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {}
md.update( str.getBytes() );
byte[] digest = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0, j = digest.length; i < j; i++) {
String tmp = Integer.toHexString(0xFF & digest[i]);
if (tmp.length() < 2) {
tmp = "0" + tmp;
}
hexString.append(tmp);
}
return hexString.toString();
}
%>
Why did I have to add a useless try/catch to make this code work?
The normal JSP source code is by itself already placed in one huge try-catch block. Every normal scriptlet
<% %>will become part of it, so you don’t need to explicitly catch the exceptions. However, a method definition<%! %>will be placed outside the standard try-catch, so you have to handle the exceptions yourself.Needless to say that this is not the best practice. Rather put the Java code in a real Java class. For this particular purpose, I think an EL function is very useful. See also How to avoid Java code in JSP files?