【问题标题】:How to stop logic in another method in java如何在java中的另一种方法中停止逻辑
【发布时间】:2015-11-13 11:48:28
【问题描述】:

我的逻辑基本是这样的;

public static void main(String[] args) {

    check("This is string");

    System.out.println("logic continue");

}


private static void check(String text) {

    if (text.equals("This is string")) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}

我想检查另一个方法中的逻辑,如果语句为“假”我不想返回调用方法。

例如;

在“检查”方法中,如果字符串不相等,程序/线程或其他东西必须完成,不能写“逻辑继续”。

我想在 Web 服务中使用此逻辑来检查标头。在 doGet 和 doPost 超级方法中。如果标头不正确,则给出自定义异常并且程序不会按子类继续。

Thread.currentThread().stop();

上述代码 (Therad.currentThread().stop()) 在 sevlet 中不起作用。

任何人都可以安全地了解这种方法吗?

编辑:

有些人理解错了,所以我想编辑我的问题。下面是我想做的。我在动态 Web 应用程序中有 servlet。所有这些 servlet 都扩展了 myBaseServlet。

BaseServlet.java

public class BaseServlet extends HttpServlet{

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse resp) throws ServletException, IOException {

    if(HeadersCheckHelpers.checkHeaders(httpServletRequest){

        //if this part is working, everthing fine, application does what it wants

    }else{
        // if this else block works, thread should be stopped and non-return the subclasses
    }
}

}

示例子 servlet 类

public class ContextServlet  extends BaseServlet{

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    super.doGet(httpServletRequest, httpServletResponse);

    //if headers are not correct, i want this part not working. super class should handle this.
}

}

同样,如果逻辑是真或假,我想停止进程(我不想返回子类方法)。

【问题讨论】:

  • 从该方法返回一个布尔值,仅在该布尔值为真时打印。您也可以在 else 块中关闭应用程序 (System.exit(0);)
  • 返回布尔值不是逻辑方式,所有子类都必须以这种方式有if-else块。并且在 wer 服务中没有 system.exit(0) 机会
  • 由于您希望根据该方法中检查的条件执行下一行,因此返回布尔值是合乎逻辑的方式。毕竟,这就是布尔值的用途。
  • 也就是说,如果你有 100 个类扩展同一个类,你必须写 100 个 if-else 案例
  • 他们继承并重用该方法。那为什么呢?

标签: java


【解决方案1】:

声明方法返回 boolean 并在调用时检查它:

public static void main(String[] args) {
    if (check("This is string"))
        System.out.println("logic continue");
}


private boolean void check(String text) {

    if (text.equals("This is string")) {
        System.out.println("true");
        return true;
    } else {
        System.out.println("false");
        return false;
    }
}

澄清:我不知道你对java有多新,所以这一行

if (check("This is string"))

等同于:

boolean result = check("This is string");
if (result == true)

【讨论】:

  • 我不想返回值。只需停止该方法中的逻辑即可。
  • 该方法应该是静态的,不过:)
【解决方案2】:

在 Servlet 请求中,您必须始终返回响应。在这种情况下,您应该返回一个4xx Http 状态:

if (!check("This is string")) {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
} else {
    System.out.println("logic continue");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多