Java tutorial
/* * Copyright 2005-2013 shopxx.net. All rights reserved. * Support: http://www.shopxx.net * License: http://www.shopxx.net/license */ package net.shopxx.interceptor; import java.net.URLEncoder; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.shopxx.Principal; import net.shopxx.entity.Merchant; import net.shopxx.service.MerchantService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /** * Interceptor - ?? * * @author SHOP++ Team * @version 3.0 */ public class MerchantInterceptor extends HandlerInterceptorAdapter { /** ????? */ private static final String REDIRECT_VIEW_NAME_PREFIX = "redirect:"; /** "??URL"??? */ private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl"; /** ""?? */ private static final String MERCHANT_ATTRIBUTE_NAME = "merchant"; /** URL */ private static final String DEFAULT_LOGIN_URL = "/login.jhtml"; /** URL */ private String loginUrl = DEFAULT_LOGIN_URL; @Value("${url_escaping_charset}") private String urlEscapingCharset; @Resource(name = "merchantServiceImpl") private MerchantService merchantService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); Principal principal = (Principal) session.getAttribute(Merchant.PRINCIPAL_ATTRIBUTE_NAME); if (principal != null) { return true; } else { String requestType = request.getHeader("X-Requested-With"); if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) { response.addHeader("loginStatus", "accessDenied"); response.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } else { if (request.getMethod().equalsIgnoreCase("GET")) { String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI(); response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset)); } else { response.sendRedirect(request.getContextPath() + loginUrl); } return false; } } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (modelAndView != null) { String viewName = modelAndView.getViewName(); if (!StringUtils.startsWith(viewName, REDIRECT_VIEW_NAME_PREFIX)) { modelAndView.addObject(MERCHANT_ATTRIBUTE_NAME, merchantService.getCurrent()); } } } /** * ?URL * * @return URL */ public String getLoginUrl() { return loginUrl; } /** * URL * * @param loginUrl * URL */ public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } }