Skip to content

Instantly share code, notes, and snippets.

@p120ph37
Last active December 4, 2018 15:11
Show Gist options
  • Save p120ph37/132f8f6d0c70b5ac6be310831db2c841 to your computer and use it in GitHub Desktop.
Save p120ph37/132f8f6d0c70b5ac6be310831db2c841 to your computer and use it in GitHub Desktop.
Servlet Parameter Validator Utility Class
public class ExampleUsage extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final ParameterValidator validator = new ParameterValidator()
.regex("userName", "^[a-z0-9.]{1,20}$")
.regex("fullName", "^[A-Za-z0-9.]{1,40}$", false)
.regex("street", "^[A-Za-z0-9 ]{1,30}$")
.regex("city", "^[A-Za-z ]{1,30}$")
.regex("zip", "^[A-Za-z0-9 ]{1,20}$")
.regex("ccn", "^[0-9]{1,30}$");
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
// Validate input
if(!validator.isValid(request, response)) return;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.NoArgsConstructor;
import lombok.Value;
@NoArgsConstructor
public class ParameterValidator {
@Value(staticConstructor="of")
private static class RegexTest {
String param;
String regex;
boolean required;
public boolean isValid(String value) {
if (value == null) {
return this.required ? false : true;
} else {
return value.matches(regex);
}
}
}
private final Map<String, RegexTest> template = new LinkedHashMap<String, RegexTest>();
public ParameterValidator regex(String param, String regex) {
return this.regex(param, regex, true);
}
public ParameterValidator regex(String param, String regex, boolean required) {
template.put(param, RegexTest.of(param, regex, required));
return this;
}
public boolean isValid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
for(String key: template.keySet()) {
RegexTest test = template.get(key);
if(!test.isValid(request.getParameter(test.getParam()))) {
request.setAttribute("message", "Invalid value for '"+test.getParam()+"'");
request.getRequestDispatcher("ErrorHandler").forward(request, response);
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment