首页 > 程序开发 > 综合编程 > 其他综合 >

使用ssm框架后台对app接口进行登录验证

2017-10-24

使用ssm框架后台对app接口进行登录验证。

1 pom依赖 我的spring版本是4.3.9 还有jackson版本2.8.8


    com.fasterxml.jackson.core
    jackson-annotations
    2.8.8


    com.fasterxml.jackson.core
    jackson-core
    2.8.8


    com.fasterxml.jackson.core
    jackson-databind
    2.8.8

2 spring-web.xml配置:

 
vc:interceptors>  
    
      
        
       
         
      
 

3 自己定义一个注解

package com.datebook.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by wangH on 2017/10/24.
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}

4 自定义拦截器

package com.datebook.aop;

import java.lang.reflect.Method;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.datebook.common.JsonResult;
import com.datebook.common.LoginRequired;
import com.datebook.common.ResultCode;
import com.datebook.service.WebTokenService;
import com.datebook.vo.WebToken;

/** 
 * 登录认证的拦截器 
 */  
@Configuration
public class LoginInterceptor extends HandlerInterceptorAdapter{  

    @Autowired
    public WebTokenService tokenService; 
     /** 
     * Handler执行之前调用这个方法 
     */ 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final HttpServletResponse httpResponse = (HttpServletResponse) response;
        final String authHeaderVal = httpRequest.getHeader("token");

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String name = request.getServletPath().toString();

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        if (methodAnnotation != null) {
            if (StringUtils.isNotEmpty(authHeaderVal)) {
                try {
                    WebToken webToken = tokenService.getToken(authHeaderVal);
                    int userId = Integer.valueOf(webToken.getId());
                    System.out.println("========"+name+"===>LoginInterceptor preHandle 验证成功放行"); 
                    return true; 
                } catch (Exception e) {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(JSON.toJSONString(new JsonResult(ResultCode.INVALID_AUTHCODE, "登录已过期,请重新登录!")));
                    System.out.println("========"+name+"===>LoginInterceptor preHandle 拦截,登录已过期,请重新登录!"); 
                    return false;
                }
            } else {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JSON.toJSONString(new JsonResult(ResultCode.NOT_LOGIN,"尚未登录")));
                System.out.println("========"+name+"===>LoginInterceptor preHandle 拦截,尚未登录!");
                return false;
            }
        }   
        System.out.println("========"+name+"===>LoginInterceptor preHandle 没加验证注解放行");
        return true;   
    } 

    /** 
     * Handler执行之后,ModelAndView返回之前调用这个方法 
     */ 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,  
            Object handler, ModelAndView modelAndView) throws Exception { 
        String name = request.getServletPath().toString();
        System.out.println("========"+name+"===>LoginInterceptor postHandle"); 
    }  

    /** 
     * Handler执行完成之后调用这个方法 
     */
    @Override
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception exc)  
            throws Exception { 
        String name = request.getServletPath().toString();
        System.out.println("========"+name+"===>LoginInterceptor afterCompletion"); 
    }  
}  

最后在需要调用的接口上面加@LoginRequired注解就行。

/** 
     * 通过手机号获取用户个人资料
     * 
     * */
    @LoginRequired
    @RequestMapping(value = "/getByMobile", method = RequestMethod.POST)
    private JsonResult getByMobile(@RequestBody Map params) {
        if (params == null||
                StringUtils.isEmpty(params.get("mobile").toString())) {
            return new JsonResult(ResultCode.PARAMS_ERROR, "参数错误");
        }
        User user = userService.getUserByMobile(params.get("mobile").toString());
        Map map = new HashMap<>();
        user.setPassword("不告诉你");
        map.put("userInfo", user);
        return new JsonResult(ResultCode.SUCCESS,"成功",map);
    }
相关文章
最新文章
热点推荐