3

あるコントローラーから別のコントローラーにデータを渡す作業を行っています。アプリケーションのすべての例外を処理するために使用される @ControllerAdvice で注釈が付けられたクラスが 1 つあります。

私は例外を処理し、それらをカスタム クラスに追加しています。次に、ModelAndView でそれを追加し、リダイレクトを使用して別のコントローラーに渡しています。そして、そのコントローラーで追加されたオブジェクトが必要ですが、そのオブジェクトを取得する方法についてはあまりわかりません。いくつかのトリックを試しましたが、成功しませんでした。

コード:

ExceptionHandler クラス:

@ControllerAdvice
public class DefaultExceptionHandler {

    @Autowired
    private CPro cPro;

    private static final Logger LOG = LoggerFactory.getLogger(DefaultExceptionHandler.class);

    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ModelAndView handleException(Exception ex) {

        ModelAndView modelAndView = new ModelAndView("redirect:/");
        String exceptionType = ex.getClass().getSimpleName();
        DefaultExceptionHandler.LOG.error("Internal Server Exception", ex);
        ErrorResponse response = new ErrorResponse();
        if (ex.getCause() != null) {
            response.addSimpleError(exceptionType, ex.getCause().getMessage(), cPro.getProName());
        } else {
            response.addSimpleError(exceptionType, ex.getMessage(), cPro.getProName());
        }
        modelAndView.addObject("processingException", response);

        return modelAndView;
    }
}

私のホームコントローラー:

@RequestMapping(value = "/", method = RequestMethod.GET)
    public String getHomePage(@ModelAttribute("processingException") ErrorResponse errorResponse, Model model) {                

        // I want to get object data of processingException added in exception handler using ModelAndView
        model.addAttribute("processingException", errorResponse.getError() == null ? null : errorResponse);
        return "upscale"; //here upscale.html redirection       
    }

コントローラーでそのオブジェクトデータを取得する方法を知っている人はいますか?

ありがとう。

4

2 に答える 2

0

次のような回避策を作成できます。

public ModelAndView handleException(Exception ex, HttpServletRequest req) {
//...
ModelAndView modelAndView = new ModelAndView("forward:/");
//...
req.setAttribute("processingException", response);

次に、コントローラー メソッドで HttpServletRequest にアクセスし、属性 (オブジェクト) を取得します。

public String getHomePage(@ModelAttribute("processingException", HttpServletRequest req)
{
//....
req.getAttribute("processingException");
于 2015-07-30T08:32:35.247 に答える