如何停止servlet?

Dav*_*uth 4 java jsp servlets java-ee

我有一个看起来像这样的servlet:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我的想法是,我想传递param1param2运行validateInput()以验证输入是否有效.如果输入无效,请写回消息然后结束该过程.我的问题是如何结束这个过程?我所知道的,调用return;doPost()将结束的过程,但我想,以避免返回任何值validateInput(),以doPost()刚刚结束的过程的缘故.我个人觉得它更具可读性这种方式,而不是返回truefalsedoPost()并调用return;那里.有办法吗?或者这根本不可能?

Nis*_*ant 9

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

}
Run Code Online (Sandbox Code Playgroud)


Kri*_*ris 5

除非您抛出异常(未经检查的异常或在本例中),否则控制权将始终返回到运行doPost后。validateInputIOException

因此,如果您没有从validateInputto返回任何值doPost,即使您提交了响应,doPost仍然会继续执行它应该执行的操作。(当然,如果响应被提交,浏览器将完全不知道服务器端的任何进一步活动)。

您将需要返回一个值、抛出异常(可能doPost会捕获)设置一个用于检查的全局值doPost(这只是混乱)。

  • 是的,这就是我所说的。返回真/假值的验证方法并没有什么“不干净”的地方。这就是它的函数的输出。 (2认同)