当前位置 : 主页 > 编程语言 > java >

常用

来源:互联网 收集:自由互联 发布时间:2021-06-28
系统自定义异常类 package org.woke.admincore.common.exception;import lombok.Getter;import org.woke.admincore.common.emuns.AdminCoreCodeEmun;/** * 系统自定义异常类 * * @author songshengqi * @version Id: AdminCoreException.java
系统自定义异常类
package org.woke.admincore.common.exception;

import lombok.Getter;
import org.woke.admincore.common.emuns.AdminCoreCodeEmun;

/**
 * 系统自定义异常类
 *
 * @author songshengqi
 * @version Id: AdminCoreException.java, v 0.1 2017/9/26 17:58   Exp $$
 */
public class AdminCoreException extends Exception {

    @Getter
    private String errCode = "";

    @Getter
    private String errReason = "";

    /**
     * 有参构造方法
     * @param errCode 错误编码
     * @param errReason 描述信息
     */
    public AdminCoreException(String errCode, String errReason) {
        super("[" + errCode + "]" + errReason);
        this.errCode = errCode;
        this.errReason = errReason;
    }

    /**
     * 有参构造方法
     * @param errorCodeEnum 错误对象
     */
    public AdminCoreException(AdminCoreCodeEmun errorCodeEnum){
        super("[" + errorCodeEnum.getErrorcode() + "]" + errorCodeEnum.getErrordesc());
        this.errCode = errorCodeEnum.getErrorcode();
        this.errReason = errorCodeEnum.getErrordesc();
    }

    /**
     * 有参构造方法
     * @param msg 错误信息描述
     */
    public AdminCoreException(String msg) {
        super(msg);
    }
}
系统自定义枚举
package org.woke.admincore.common.emuns;

import lombok.Getter;

/**
 * 系统自定义枚举
 *
 * @author songshengqi
 * @version Id: AdminCoreException.java, v 0.1 2017/9/26 17:58   Exp $$
 */
public enum AdminCoreCodeEmun {

    REQUEST_NO_PERMISSION("011000", "没有相关权限"),

    
    SERVICE_IS_BUSY("999","服务繁忙"),
    NO_LOGIN("023999", "用户没有登录请登录");



    @Getter
    private String errorcode;

    @Getter
    private String errordesc;

    /**
     * 构造函数
     *
     * @param errorCode 枚举key
     * @param errorDesc 枚举信息
     */
    AdminCoreCodeEmun(String errorCode, String errorDesc) {
        this.errorcode = errorCode;
        this.errordesc = errorDesc;
    }

    /**
     * 通过枚举key获取枚举信息
     *
     * @param errorCode 枚举key
     * @return 枚举信息
     */
    public static String getDesc(String errorCode) {
        for (AdminCoreCodeEmun bussErrorCode : AdminCoreCodeEmun.values()) {
            if (bussErrorCode.errorcode.equals(errorCode)) {
                return bussErrorCode.errordesc;
            }
        }
        return errorCode;
    }

    @Override
    public String toString() {
        return "AdminCoreCodeEmun[" + errorcode + "][" + errordesc + "]";
    }
}
格式化日期
//创建时间
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    //结束时间
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;
注释 get set toString方法
@Data


 
  1.16.4
 


 
      
 
        
  
   org.projectlombok
  
        
  
   lombok
  
        
  
   ${lombok.version}
  
      
 
解决Filter的流只能被加载一次 的Filter
package org.woke.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.common.serveradmin.conston.Constant;
import org.common.serveradmin.emuns.ServerAdminCodeEmun;
import org.common.serveradmin.exception.ServerAdminException;
import org.common.serveradmin.utils.RedisUtils;
import org.common.serveradmin.utils.RsaTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.woke.serveradfa.request.BaseRequest;
import org.woke.serveradfa.response.BaseRespose;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:LiuHao
 * @Date: Create in 12:13 2017/11/10
 **/
@Slf4j
@Service
public class TokenFilter implements Filter {

    @Autowired
    RedisUtils redisUtils;
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("token验证过滤器");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        BaseRespose baseResponse=new BaseRespose();
        try {
            HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
            requestWrapper = new BodyReaderServletWrapper((HttpServletRequest) servletRequest);
            BufferedReader br = requestWrapper.getReader();
            String temp = "";
            String decryptStr = "";
            while ((temp = br.readLine()) != null) {
                decryptStr = decryptStr + temp;
            }
            BaseRequest baseRequest= JSON.parseObject(decryptStr, BaseRequest.class);
            log.info("请求参数为{}",baseRequest);
            String tokenCode=baseRequest.getTokenCode();
            if(ObjectUtils.isEmpty(tokenCode)||ObjectUtils.isEmpty(baseRequest.getUserId())){
                throw new ServerAdminException(ServerAdminCodeEmun.TOKEN_CODE_IS_NULL);
            }

            String hasTokenCode= null;
            String userId= RsaTool.privateKeyDecryptionForUserId(baseRequest.getUserId());
            //token是否配对
            hasTokenCode = redisUtils.getCachesData(userId+"token");
            if(ObjectUtils.isEmpty(hasTokenCode)){
               throw new ServerAdminException(ServerAdminCodeEmun.TOKEN_CODE_IS_FAIL);
           }
            if (!tokenCode.equals(hasTokenCode)){
              throw new ServerAdminException(ServerAdminCodeEmun.TOKEN_CODE_IS_FAIL);
            }
            filterChain.doFilter(requestWrapper, servletResponse);
            return;

        }
        catch (ServerAdminException e){
            baseResponse.setResponseCode(e.getErrCode());
            baseResponse.setResoponseDisp(e.getErrReason());
            rsponse( servletResponse, baseResponse);
            log.info("访问异常,{}");
        }
        catch (Exception e){
            e.printStackTrace();
            baseResponse.setResponseCode(Constant.RESPONSE_FAIL_CODE);
            baseResponse.setResoponseDisp(Constant.RESPONSE_FAIL_DESP);
            rsponse( servletResponse, baseResponse);
        }


    }

    public void destroy() {

    }

    /**
     * 返回异常结果
     *
     * @param servletResponse
     * @param baseResponse
     */
    public void rsponse(ServletResponse servletResponse, BaseRespose baseResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();

            out.write(JSON.toJSONString(baseResponse));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    /***
     * 获取 request 中 json 字符串的内容
     *
     * @param request
     * @return : 
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * 
     * 举例:
     * 
* @param request * @return * @throws IOException */ public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if(contentLength<0){ return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength;) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; } /** * 描述:获取 post 请求内容 *
     * 举例:
     * 
* @param request * @return * @throws IOException */ public static String getRequestPostStr(HttpServletRequest request) throws IOException { byte buffer[] = getRequestPostBytes(request); String charEncoding = request.getCharacterEncoding(); if (charEncoding == null) { charEncoding = "UTF-8"; } return new String(buffer, charEncoding); } }byte[]
解决Filter的流只能被加载一次 的请求Servlet类
/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2016 All Rights Reserved.
 */
package org.woke.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * 请求Servlet类,处理输入流不能多次读取的问题
 *
 * @author songshengqi
 * @version Id: BodyReaderServletWrapper.java, v 0.1 2016/08/12  songshengqi Exp $$
 */
@Slf4j
public class BodyReaderServletWrapper extends HttpServletRequestWrapper {


    private final byte[] body;

    /**
     * 获取body的内容并解密
     *
     * @param request 请求对象
     * @throws Exception
     */
    public BodyReaderServletWrapper(HttpServletRequest request) throws Exception {

        super(request);
        InputStream is = request.getInputStream();
        body = getRequestPostBytes(request);
    }

    /**
     * 获取Reader对象
     *
     * @return BufferedReader
     * @throws IOException
     */
    @Override
    public BufferedReader getReader() throws IOException {

        return new BufferedReader(new InputStreamReader(getInputStream(), "utf-8"));
    }

    /**
     * 获取HTTP流
     *
     * @return ServletInputStream
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }


    /***
     * 获取 request 中 json 字符串的内容
     *
     * @param request
     * @return : 
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * 
     * 举例:
     * 
* @param request * @return * @throws IOException */ public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if(contentLength<0){ return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength;) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; } /** * 描述:获取 post 请求内容 *
     * 举例:
     * 
* @param request * @return * @throws IOException */ public static String getRequestPostStr(HttpServletRequest request) throws IOException { byte buffer[] = getRequestPostBytes(request); String charEncoding = request.getCharacterEncoding(); if (charEncoding == null) { charEncoding = "UTF-8"; } return new String(buffer, charEncoding); } }byte[]
web.xml
 
    
  
   tokenFilter
  
    
  
   org.springframework.web.filter.DelegatingFilterProxy
  
    
   
   
    targetFilterLifecycle
    
   
    true
    
  
  
 

  
 
    
  
   tokenFilter
  
    
  
   /verify/*
  
  
 
日志打印 logback.xml
 

 
    
  
    
   
    
    
     [%d] [%keep] [%thread] [%level] [%file:%line] %msg%n
     
    
  
    
  
    
   
   
    /home/logs/serveradmin-woke.log
    
    
    
     [%d] [%keep] [%thread] [%level] [%file:%line] %msg%n
     
    
     UTF-8
     
    
    
    
     /home/logs/serveradmin-woke-%d{yyyy-MM-dd}.%i.log
     
    
     30
     
     
     
      512MB
      
     
    
  

    
  
    
   
   
    /home/logs/serveradmin-woke-error.log
    
    
    
     [%d] [%keep] [%thread] [%level] [%file:%line] %msg%n
     
    
     UTF-8
     
    
    
    
     /home/logs/serveradmin-woke-error-%d{yyyy-MM-dd}.%i.log
     
    
     30
     
     
     
      512MB
      
     
    
    
    
     ERROR
     
    
     ACCEPT
     
    
     DENY
     
    
  
    
    
  

    
  
    
    
    
    
    
    
    
    

    
  
    
    
    
    
    

    
    
    
    
    
  
    


 
上一篇:maven中pom.xml配置文件
下一篇:短信发送
网友评论