Luke has inherited a Java Struts-based application. Struts is one of the many Java web frameworks, designed around having HTTP requests trigger actions- that is routing HTTP requests to a specific function call.
Now, on one screen, the user filled in a form, and then the corresponding action on the server side needed to read the form data for an eventId
and act upon it. In Struts, this can be very simple:
int event_id = Integer.parseInt(request.getParameter("event_id"));
That's the assumed way of doing that. But if you don't learn how to use the framework properly, you might end up writing something else:
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
int event_id = 0;
try {
InputStream is = request.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String eventStr = "";
StringBuffer buff = new StringBuffer();
String line;
do {
line = br.readLine();
buff.append(line);
} while (br.readLine() != null);
eventStr = buff.toString();
StringTokenizer parseEventId = new StringTokenizer(eventStr, ",");
while (parseEventId.hasMoreTokens()) {
String eventString = parseEventId.nextToken();
if (eventString.startsWith("event_id")) {
event_id = Integer.parseInt(eventString.substring(eventString.indexOf("=") + 1));
}
}
} catch (Exception e) {
e.printStackTrace();
}
...
}
This pile of code opts to read in the entire body of the input stream as a string, and then parse that string using a tokenizer, searching for substring which starts with event_id
, at which point they can split on the =
and get the integer value.
All of this is too complicated and reinventing a wheel badly, but the specific token we split on hints at deeper problems: ", "
, as well as the fact that our read do/while
loop only reads every other line.
An HTML form POST
request encodes the data either as application/x-www-form-urlencoded
or multipart/form-data
. Neither of those formats sends up commas to separate key/value pairs. Either the client side is applying its own custom formatting, which we need to parse, or this code is just plain wrong.
But also, Struts does have a whole model/form binding feature set, so the "official" way to do this would be to just map to a Java Bean object.
Everything about this is wrong and overengineered, and smells like it was written by someone who was "smarter" than everyone else, and thus couldn't be bothered with using standard approaches to anything.