I'm trying to use a PhaseListener for the APPLY_REQUEST_VALUES phase for having one central place where I can filter all input fields and sanitize them without adding code to them individually.
In my first step, I've tried just to set one value to a field I left empty in the browser when submitting the form, but I got an Exception telling me that I can't set request parameters.
Below is my experimental PhaseListener. This version tests if I can change any input field content at all by setting one known field to a value.
Once I get that working, the final code shall iterate over all fields, get their content, sanitize it, and write it back to the request.
public class SanitizeRequestValuesPhaseListener implements PhaseListener {
private static final long serialVersionUID = 1L;
public static final String SEARCH_FORM_INPUT_PRICE_TO = "searchForm:inputPriceTo";
public PhaseId getPhaseId() {
return PhaseId.APPLY_REQUEST_VALUES;
}
public void afterPhase(final PhaseEvent event) {
}
public void beforePhase(final PhaseEvent event) {
final FacesContext facesContext = event.getFacesContext();
final ExternalContext externalContext = facesContext.getExternalContext();
System.out.println();
final Map<String, String> requestParameters = externalContext.getRequestParameterMap();
printMap(requestParameters, "Request Parameters");
if (requestParameters.containsKey(SEARCH_FORM_INPUT_PRICE_TO)) {
final String priceTo = requestParameters.get(SEARCH_FORM_INPUT_PRICE_TO);
if (priceTo != null) {
// just out of curiosity
System.out.println(priceTo.getClass().getName());
}
try {
requestParameters.put(SEARCH_FORM_INPUT_PRICE_TO, "120");
} catch (final Throwable ex) {
ex.printStackTrace();
}
}
}
private static void printMap(final Map<?, ?> reqAttrs, final String title) {
final StringBuilder sb;
sb = new StringBuilder();
for (final Object key : reqAttrs.keySet()) {
sb.append("* (");
sb.append(key);
sb.append("=");
sb.append(reqAttrs.get(key));
sb.append(")\n");
}
System.out.println(title);
System.out.println(sb);
}
}
Is there another way to change/override user input values?
Or shoud I use a completely different approach?
Remember: The important thing is to have once central place that handles all input fields across the whole web application.