com.wx.spring.interceptor.OAuth2Interceptor.java Source code

Java tutorial

Introduction

Here is the source code for com.wx.spring.interceptor.OAuth2Interceptor.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wx.spring.interceptor;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class OAuth2Interceptor implements HandlerInterceptor {

    /** 
     * DispatcherServlet?? 
     * ,?afterCompletion() 
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) throws Exception {
        System.out.println("**?: 3?afterCompletion**");

    }

    /** 
     * ????,?? 
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2,
            ModelAndView modelAndView) throws Exception {
        System.out.println("**?: 2?postHandle**");

    }

    /** 
     * ??? false ?afterCompletion(),? 
     * true , ?Controller ?, 
     * ?postHandle() ???afterCompletion() 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("**?: 1?preHandle**");
        String url = request.getRequestURL().toString();

        HttpSession session = request.getSession();
        // ?  

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        OAuthRequired annotation = method.getAnnotation(OAuthRequired.class);
        if (annotation != null) {
            System.out.println("OAuthRequired????");
            Object objUid = session.getAttribute("UserId");
            if (objUid == null) {
                String resultUrl = request.getRequestURL().toString();
                String param = request.getQueryString();
                if (param != null) {
                    resultUrl += "?" + param;
                }
                System.out.println("resultUrl=" + resultUrl);
                try {
                    resultUrl = java.net.URLEncoder.encode(resultUrl, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //  
                String contextPath = request.getContextPath();
                response.sendRedirect(contextPath + "/oauth2.do?resultUrl=" + resultUrl);
                return false;
            }

        }
        return true;
    }

}