필터 토 큰 검사

필터 방법:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * web  token   
 * @author wanght
 * @date 09:27 2019/04/25
 * @return
 */
@Configuration
@WebFilter
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().indexOf("/login/") >= 0) {
            filterChain.doFilter(request, response);
        } else {
            //     url     /web/,   token   
            if (request.getRequestURI().indexOf("/web/") != -1) {
                Map result = new HashMap();
                String accessToken = request.getHeader("webToken");
                // Header     token ,          
                if (StringUtils.isEmpty(accessToken)) {
                    accessToken = request.getParameter("webToken");
                }
                //       token       
                String webTokenStr = redisTemplate.boundValueOps("webUsers:" + accessToken).get();
                if (null == accessToken) {
                    result.put("status",0);
                    result.put("message","token    ,   !");
                }else if (null == webTokenStr || webTokenStr.indexOf(accessToken) == -1){
                    result.put("status",0);
                    result.put("message","token   ,   !");
                }else{
                    if (webTokenStr != null) {
                        filterChain.doFilter(request, response);
                    } else {
                        result.put("status",1);
                        result.put("message","token   ,     !");
                    }
                }
                try {
                    responseOutWithJson(response, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                filterChain.doFilter(request, response);
            }
        }
    }

    protected void responseOutWithJson(HttpServletResponse response, Object responseObject) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(responseObject);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

 로그 인 방법:
@RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
        User users = userService.selectByNameOrPwd(user);
        if (users != null) {
            if (null != users.getStatus() && "0".equals(users.getStatus())){
                String token = fm.utils.number.UUIDTool.getUUID();
                RedisUserDto redisUserDto = new RedisUserDto(token, users);
                BoundValueOperations operations = redisTemplate.boundValueOps("webUsers:" + users.getId());
                sendOfflineNotifyMessage(operations);
                //operations.set(JSONObject.toJSONString(redisUserDto), 2, TimeUnit.HOURS);
                operations.set(JSONObject.toJSONString(redisUserDto), 30, TimeUnit.MINUTES);
                users.setToken(users.getId()+":"+token);
                return Result.success(users);
            }else{
                return Result.fail("15005", "      !");
            }
        } else {
            return Result.fail(ResultCode.ERRORMSG, "    !");
        }
    }

redis 정보 실체 저장:
/**
 * @Author: wanght
 * @Description:
 * @Date: 2019/1/10 14:20
 */
public class RedisUserDto {
    private String token;
    // user    
    private User user;

    public RedisUserDto(String token, User user) {
        this.token = token;
        this.user = user;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

좋은 웹페이지 즐겨찾기