簡體   English   中英

我可以在Spring MVC的Interceptor中使用RedirectAttributes或FlashMap

[英]Can I use RedirectAttributes or FlashMap in Interceptor of Spring MVC

我有一個攔截器來處理用戶會話。 如果user屬性不存在,則攔截器將重定向到登錄頁面。 我想用重定向網址發送session timeout消息,但我不想在網址中顯示該消息。 我為RedirectAttributesFlashMap搜索了很多FlashMap ,但我找不到任何好的解決方案。

public class UserSessionInterceptor extends HandlerInterceptorAdapter {
        protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User)request.getSession().getAttribute(CommonConstants.USER_SESSION_KEY);
        if (user == null) {
            String msg = String.format("session timeout");
            logger.error(msg);

    //      response.sendRedirect("/signin?errorMessage=" + msg); //I don't want to do this..

            return false;
        }

        return true;
    }    
}

signinController片段:

@Controller
@SessionAttributes(CommonConstants.KAPTCHA_SESSION_KEY)
public class SigninController extends BaseController {

    @RequestMapping(value = "/signin", method = RequestMethod.GET)
    public String signinPage() {
        return "forward:/index.jsp";
    }

    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public String signin(UserForm userForm, @ModelAttribute(CommonConstants.KAPTCHA_SESSION_KEY) String captchaExpected, RedirectAttributes redirectAttributes, HttpServletRequest request) {
    userForm.setCaptchaExpected(captchaExpected);
    try {
        loginValidator.validate(userForm);
    } catch (ValidateFailedException e) {
        logger.error(e.getMessage(), e);
        redirectAttributes.addFlashAttribute(ERROR_MESSAGE_KEY, e.getMessage());
        return "redirect:/signin";
    }

    User user = userService.getByUsername(userForm.getUsername());
    if (user == null || !user.getPassword().equals(DigestUtils.md5Hex(userForm.getPassword()))) {
        redirectAttributes.addFlashAttribute(ERROR_MESSAGE_KEY, "username or password is invalid");
        return "redirect:/signin";
    }
    request.getSession().setAttribute(CommonConstants.USER_SESSION_KEY, user);
    return "redirect:/dashboard";
}
}

index.jsp片段:

<%@page contentType="text/html; charset=utf-8"%>
<%@ include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>welcome</title>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="keywords" content="" />
<meta http-equiv="description" content="" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="${ctx}/css/bootstrap.min.css">
<link rel="stylesheet" href="${ctx}/css/main.css">
<script src="${ctx}/js/jquery-1.11.1.min.js"></script>
<script src="${ctx}/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-box text-center" >
    <div class="login-single-panel-header">
        <h5 style="color:red">${errorMessage}</h5>
    </div>
</div>
</div>
</body>
</html>

非常感謝你!

我剛遇到同樣的問題。 我對spring源代碼進行了調試,尋找spring mvc與flashmap屬性的相同之處,並在會話中提出了相同的flashmap屬性。

這是我最后的解決方案:

// create a flashmap
FlashMap flashMap = new FlashMap();

// store the message
flashMap.put("ERROR_MESSAGE", "this is the message");

// create a flashmapMapManger with `request`
FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);

// save the flash map data in session with falshMapManager
flashMapManager.saveOutputFlashMap(flashMap, request, response);
  • 上面的代碼引用了方法org.springframework.web.servlet.view.RedirectView#renderMergedOutputModel ,你可以自己檢查一下

希望這會對你有所幫助!

這是在Spring 5.0中執行此操作的另一種方法

public class LoginInterceptor extends HandlerInterceptorAdapter{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginUrl = request.getContextPath() + "/login";
        if(request.getSession().getAttribute("loggedInUser") == null) {
            FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
            outputFlashMap.put("loginError", "Please login to continue");
            //New utility added in Spring 5
            RequestContextUtils.saveOutputFlashMap(loginUrl, request, response);
            response.sendRedirect(loginUrl);
            return false;
        }
        return true;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM