Login using annotations Spring MVC + interceptor

Foreword

In the project, log on to check whether there are several ways, today introduced the use of annotated way + interceptor used in conjunction.




achieve

Step 1: Create annotations.

Here Insert Picture Description

package com.study.it.entity.annotation;

import java.lang.annotation.*;

//写到哪里
@Target({ElementType.TYPE,ElementType.METHOD}) //表示注解的作用对象,ElementType.TYPE表示类,ElementType.METHOD表示方法
//什么时候起作用
@Retention(RetentionPolicy.RUNTIME) //表示注解的保留机制,RetentionPolicy.RUNTIME表示运行时注解
@Inherited //表示该注解可继承
@Documented //表示该注解可生成文档
public @interface Login {

}



Step 2: Create the interceptor.

Here Insert Picture Description

package com.study.it.ui.interceptor;

import com.bdqn.it.entity.annotation.Login;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 *  登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {

        // 从会话中取当前登录对象
        if (req.getSession().getAttribute("user") != null){
            // 已登录就放行
            return true;
        }

        HandlerMethod hm = (HandlerMethod)o;
        // 检查被请求方法头是否有注解   ----> @Login
        if (hm.getMethodAnnotation(Login.class) == null){
            // 没有注解就放行
            return true;
        }

        // req.getContextPath()动态获取工程路径
        // 没登录的话就重定向去登录
        resp.sendRedirect(req.getContextPath() + "/login");
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}



The third step: to spring MVC registered interceptors.

Here Insert Picture Description

	<!--拦截器配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
           <mvc:mapping path="/**"/>
           <bean class="com.study.it.ui.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>



The fourth step: the controller Riga annotation method first need to log in.

Here Insert Picture Description

Published 26 original articles · won praise 3 · Views 1414

Guess you like

Origin blog.csdn.net/CQWNB/article/details/104563443