4

STS からは正常に動作する Spring Boot Web アプリがありますが、WAR ファイルから Tomcat で実行すると異なる動作を示します。

私は Thymeleaf を使用してすべての Web ページを処理していますが、jQuery を使用して非同期呼び出しを送信し、ユーザー エクスペリエンスをより動的にするページがいくつかあります。

とにかく、私はこの方法で処理するをスローする可能性のあるサービスメソッドを呼び出すコントローラーメソッドを持っていますRuntimeException:

@ExceptionHandler(MyRuntimeException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody String handleMyRuntimeException(MyRuntimeException exception) {
    return "Oops an error happened : " + exception.getMessage();
}

JS では、上記の応答本文を使用して画面にメッセージを表示します。

STS でアプリを実行している場合は問題なく動作しますErrorPageFilterが、Tomcat で展開するように切り替えると、呼び出されdoFilter()て実行されます。

if (status >= 400) {
    handleErrorStatus(request, response, status, wrapped.getMessage());
    response.flushBuffer();
}

handleErrorStatus()ステータスと関連メッセージでエラーが発生しますが、応答は返されません。

これを解決する方法がわかりませんでした。誰かが助けてくれれば本当に感謝しています。

ありがとう!

4

1 に答える 1

2

次のようにして、この問題を回避しました(Spring Bootの問題だと思います)。

  1. Rest コントローラーと Mvc コントローラーを分離する ここで私の質問を参照してください: Spring MVC: Get i18n message for reason in @RequestStatus on a @ExceptionHandler

  2. Jackson コンバーターを挿入し、自分で応答を書き込みます。

    @ControllerAdvice(annotations = RestController.class)
    @Priority(1)
    @ResponseBody
    public class RestControllerAdvice {
        @Autowired
        private MappingJackson2HttpMessageConverter jacksonMessageConverter;
    
        @ExceptionHandler(RuntimeException.class)
        @ResponseStatus(value = HttpStatus.BAD_REQUEST)
        public void handleRuntimeException(HttpServletRequest request, HttpServletResponse response, RuntimeException exception) {
            try {
                jacksonMessageConverter.write(new MyRestResult(translateMessage(exception)), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
                response.flushBuffer(); // Flush to commit the response
                } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
于 2015-03-27T08:33:16.290 に答える