【发布时间】: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