I have a servlet that looks like this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
validateInput(param1, param2, request, response);
//if nothing's wrong with the input, do this and that
}
private void validateInput(String param1, String param2, HttpServletRequest request, HttpServletResponse response) throws IOException{
boolean fail = false;
//validate input blah blah blah
if (fail){
PrintWriter out = response.getWriter();
out.write("invalid input");
//end process or servlet
}
}
The idea is that I want to pass param1
and param2
to function validateInput()
to validate whether or not the input is valid. If input is invalid, write a message back and then end the process. My question is how to end the process? I'm aware of that calling return;
in doPost()
will end the process but I'm trying to avoid returning any value from validateInput()
to doPost()
just for the sake of ending the process. I personally feel that it's more readable this way rather than returning true
or false
to doPost()
and call return;
there. Is there a way to do it? Or is it simply impossible?
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
if(!isValidInput(param1, param2)){
PrintWriter out = response.getWriter();
out.write("invalid input");
return;
}
//if nothing's wrong with the input, do this and that
}
private boolean isValidInput(String param1, String param2){
boolean fail = false;
//validate input and return true/false
}
Control will always return to doPost
after validateInput
runs unless you throw an exception (either an unchecked exception or IOException
in this case).
So if you do not return ANY value from validateInput
to doPost
, even if you commit the response, doPost
will still go on to do whatever it is supposed to do. (Of course, if the response is commited, the browser will be entirely unaware of any further activity on the server side).
You will need to return a value, throw an exception (which doPost
may catch) or set a global value that doPost
checks (which is just messy).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With