java 如何停止servlet?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5244416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:11:27  来源:igfitidea点击:

how to stop servlet?

javajspservletsjakarta-ee

提问by Davuth

I have a servlet that looks like this:

我有一个如下所示的 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
    }
}

The idea is that I want to pass param1and param2to 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 trueor falseto doPost()and call return;there. Is there a way to do it? Or is it simply impossible?

这个想法是我想通过param1param2发挥作用validateInput()来验证输入是否有效。如果输入无效,则回写一条消息,然后结束该过程。我的问题是如何结束这个过程?我知道调用return;indoPost()将结束该过程,但我试图避免仅为了结束该过程而从validateInput()to返回任何值doPost()。我个人觉得它更具可读性这种方式,而不是返回truefalsedoPost()和呼叫return;那里。有没有办法做到这一点?还是根本不可能?

回答by Nishant

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

}

回答by Kris

Control will always return to doPostafter validateInputruns unless you throw an exception (either an unchecked exception or IOExceptionin this case).

除非您抛出异常(未经检查的异常或在这种情况下),否则控制将始终返回到运行doPost后。validateInputIOException

So if you do not return ANY value from validateInputto doPost, even if you commit the response, doPostwill 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).

所以如果你没有从validateInputto返回任何值doPost,即使你提交了响应,doPost仍然会继续做它应该做的事情。(当然,如果响应被提交,浏览器将完全不知道服务器端的任何进一步活动)。

You will need to return a value, throw an exception (which doPostmay catch) orset a global value that doPostchecks (which is just messy).

您将需要返回一个值、抛出一个异常(doPost可能会捕获)设置一个全局值来doPost检查(这很麻烦)。

回答by Jigar Joshi

More sophisticated way would be .

更复杂的方法是 .

  • validate and setAttributes to request if error found and forwardrequest to jsp
  • on jsp check for the error attribute if any present display them
  • 如果发现错误,则验证和设置属性以请求并将请求转发到 jsp
  • 在jsp上检查错误属性是否存在显示它们


See Also

也可以看看

回答by duffymo

What are you calling "the process"? That single request? If yes, then sending a message back DOES end the servlet's responsibility. HTTP is a request/response protocol.

你说的“过程”是什么?那个单一的要求?如果是,则发回消息确实结束了 servlet 的责任。HTTP 是一种请求/响应协议。

If you mean stopping the servlet, that's not right. The servlet runs in the container, which is still going. It waits for the next request.

如果您的意思是停止 servlet,那是不对的。servlet 在容器中运行,容器仍在运行。它等待下一个请求。

I don't see anything that merits stopping. Validation and routing back with errors is common.

我看不出有什么值得停下来的。有错误的验证和路由很常见。

回答by Dave Lugg

Try this:

试试这个:

I changed your validate to return a boolean, so you can run an if statement on it in the doPost method. I also made it return a success instead of failure, just so the check makes more sense once you've returned.

我将您的验证更改为返回一个布尔值,因此您可以在 doPost 方法中对其运行 if 语句。我还让它返回成功而不是失败,所以一旦你返回,检查就更有意义。

response.sendError will allow you to do a generic error page (See this: http://blogs.atlassian.com/2007/07/responsesenderror_vs_responses/) instead of your output. If you want that you'll want setStatus (again, see the link).

response.sendError 将允许你做一个通用的错误页面(见这个:http: //blogs.atlassian.com/2007/07/responsesenderror_vs_responses/)而不是你的输出。如果你想要,你会想要 setStatus(同样,请参阅链接)。

The return should terminate execution and prevent the rest from happening, but it won't shut down the servlet like a system.exit(0) would.

返回应终止执行并防止其余部分发生,但它不会像 system.exit(0) 那样关闭 servlet。

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
    String param1 = request.getParameter("param1");
    String param2 = request.getParameter("param2");

    if (! validateInput(param1, param2, request, response)){
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        //Or you can use this instead... 
        //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        //PrintWriter out = response.getWriter();
        //out.write("invalid input");
        return;
    }
    //if nothing's wrong with the input, do this and that
}




private boolean validateInput(String param1, String param2, HttpServletRequest request, HttpServletResponse response) throws IOException{
    boolean success = false;

    //validate input blah blah blah

    return success;
}

回答by Koekiebox

It sounds like you want to get a reference to the OutputStreamto write HTML back to the client?

听起来您想获得OutputStream对将 HTML 写回客户端的引用?

You can make use of response.getOutputStream()that would return a ServletOutputStream.

您可以利用response.getOutputStream()它返回一个ServletOutputStream.

Once you have written to this stream, you need to finish. You will have to close()and flush()once you are done.

写入此流后,您需要完成。你必须close()flush()一旦你完成。

Whatever you write to this stream will be sent to the browser. Also remember to call the response.setContentType("text/html");so the browser knows its dealing with HTML.

无论您写入此流的任何内容都将发送到浏览器。还记得调用 response.setContentType("text/html");以便浏览器知道它处理 HTML。

回答by Deepak

have you tried with either one of the following

您是否尝试过以下任一方法

response.sendRedirect("some view.jsp");

response.sendRedirect("some view.jsp");

(or)

(或者)

System.exit(0); // which exits from the program

System.exit(0); // which exits from the program