0

当访问路由 /user/ *时,我在登录页面上有自动重定向。重定向到登录页面时,我需要显示闪烁消息。

我读了一些关于事件监听器的东西,但需要一个真实的例子来实现它。

我在尝试:

services:
    listener.requestresponse:
        class: SciForum\Version2Bundle\EventListener\ExceptionListener
        tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

还有我的异常监听器

class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
    // You get the exception object from the received event
    $exception = $event->getException();
    $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
    );

    // Customize your response object to display the exception details
    $response = new Response();
    $response->setContent($message);

    // HttpExceptionInterface is a special type of exception that
    // holds status code and header details
    if ($exception instanceof HttpExceptionInterface) {
        $response->setStatusCode($exception->getStatusCode());
        $response->headers->replace($exception->getHeaders());
    } else {
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    // Send the modified response object to the event
    $event->setResponse($response);
}
}

但是当自动重定向存在时,例外是较新的抛出。

4

1 回答 1

0

EventListener 旨在侦听特定事件。您已经创建了一个 ExceptionListener,它将 GetResponseForExceptionEvent 作为参数。如果重定向成功,那么它永远不会抛出任何异常。

您需要创建一个通用的 EventListener,甚至是一个 InteractiveLoginEvent 监听器:

这是我制作的登录监听器:

    use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
    use Symfony\Component\Security\Core\SecurityContext;
    use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; 

class LoginListener
{

    private $securityContext;       

    private $em;        

    public function __construct(SecurityContext $securityContext, Doctrine $doctrine)
    {
        $this->securityContext = $securityContext;
        $this->em              = $doctrine->getManager();
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
             //do stuff
    }
}

但是,要直接解决您的问题,您能否不只是在控制器中获取重定向标头然后显示消息?

于 2014-06-17T15:18:11.040 回答