2018-08-02 APBS服务总结

1.maven部分jar包下载不到,要看看是不是springboot版本问题,可以在pom.xml文件更改版本试试。

   
        org.springframework.boot
        spring-boot-starter-parent
        1.5.6.RELEASE
         
    

2.pom.xml中java版本为1.7时,需要添加配置编译插件。

   
    UTF-8
        UTF-8
        1.7
    

添加编译插件

     
        maven-compiler-plugin
           
            1.7
            1.7
           
     

3.谷歌json字符串序列化和反序列化工具类

     
       com.google.code.gson
       gson
       2.8.2
     

用法如下
对象序列化为json字符串

...
String data = new Gson().toJson(appgpsBean);
...

json字符串反序列化为对象

...
 List tempList = new Gson().fromJson(data,new TypeToken>(){}.getType());
...

4.解决跨域访问拦截器

/**
 *   拦截器
 * Created by lin on 2017/8/21.
 */
public class AccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //解决跨域请求
      if(httpServletResponse!=null){
          httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
          httpServletResponse.addHeader("Access-Control-Allow-Methods", "get, post, put, delete, options");
          httpServletResponse.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept");
          httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
      }
        return true;
    }

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

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

5.WebMvcConfigurerAdapter类应用(重要)

WebMvcConfigurerAdapter配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制。

在配置类上添加了注解@Configuration,标明了该类是一个配置类并且会将该类作为一个SpringBean添加到IOC容器内。

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
   @Value("${tokenEnabled}")
   Boolean tokenEnabled;
    @Value("${uploadFilePath}")
    String uploadFilePath;

   @Bean
   public TokenInterceptor getTokenInterceptor(){
       return new TokenInterceptor();
   }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AccessInterceptor()).addPathPatterns("/**");
        if(tokenEnabled)
            registry.addInterceptor(getTokenInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/","/user/login","/images/**","/expand/getLatestVersion","/test/**","/APBS/error");
        super.addInterceptors(registry);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceHandler是指你想在url请求的路径
        //addResourceLocations是图片存放的真实路径
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+uploadFilePath);
        super.addResourceHandlers(registry);
    }
}

6.全局异常处理

业务异常类

/**
 * Created by lin on 2017/10/20.
 * 实际业务异常
 */
public class BusinessException extends RuntimeException{
    private int code=-1;

    public BusinessException(String message, int code) {
        super(message);
        this.code = code;
    }

    public BusinessException(String message) {
        super(message);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

异常处理器

/**
 * 异常处理器,捕获所有异常,并按照统一格式返回
 * Created by lin on 2017/8/21.
 */
@ControllerAdvice
public class ExceptionHandler {
    Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(HttpServletRequest request, Exception e) {

        logger.error("系统异常: RequestURI=" +request.getRequestURL()) ;
        logger.error("系统异常:" +e.toString());
        logger.error("系统异常:" +e.getMessage(),e);
        e.printStackTrace();
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return ResultUtil.error(ErrorCode.REQUEST_METHOD_ERROR.getValue(), "HttpRequestMethodNotSupportedException:请求方式(Get/Post)错误");
        }
        if (e instanceof MissingServletRequestParameterException) {
            return ResultUtil.error(ErrorCode.MISSING_PARAMETERS.getValue(),"MissingServletRequestParameterException: 缺少参数");
        }
        if (e instanceof MethodArgumentTypeMismatchException) {
            return ResultUtil.error(ErrorCode.INVALID_PARAMETERS.getValue(),"MethodArgumentTypeMismatchException:参数类型错误");
        }
       if (e instanceof BusinessException) {

            if(e.getMessage() == "token missing")
            {
                return ResultUtil.error(ErrorCode.TOKEN_MISSING.getValue(),e.getMessage());
            }
            else
                if(e.getMessage() == "token incorrect or expired")
                {
                    return ResultUtil.error(ErrorCode.TOKEN_OVERTIME.getValue(),e.getMessage());
                }
            return ResultUtil.error(e.getMessage());
        }

        return ResultUtil.error(ErrorCode.FAILED.getValue(),"系统异常" );
    }
}

抛出业务异常

   @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
       String token="" ;
        try {
            token = httpServletRequest.getParameter("token");
        }catch (Exception e){
            throw new BusinessException("token missing");
        }
        if (tokenService.verifyToken(token)) {
            logger.warn(">>>>>>>>>>>>>>>>>token:" + token + "\t 在拦截器验证成功>>>>>>>>>>>>>>>>>>");
            return true;// 只有返回true才会继续向下执行,返回false取消当前请求 3c3d2eacb5d0435c9918f4c1eac50f0f
        } else {
            String url = httpServletRequest.getRequestURI();
            logger.warn(">>>>>>>>>>>>>>>>>token:" + token + "\t 在拦截器验证失败>>>>>>>>>>>>>>>>>>");
            logger.warn(">>>>>>>>>>>>>>>>>验证失败url:" + url);
            throw new BusinessException("token incorrect or expired");
        }

    }

7.统一接口返回格式

分页数据格式类

/**
 * Created by lin on 2017/8/15.
 */
public class PageData  implements Serializable {

    private static final long serialVersionUID = 1L;
    private Integer currentPage;// 当前页数
    private Integer pageSize;// 每页的大小
    private Long total;// 数据总条数
    private List rows;// 当前页的数据

    public PageData(List rows, Long total, Integer pageSize,
                    Integer currentPage) {
        this.total = total;
        this.rows = rows;
        this.pageSize = pageSize;
        this.currentPage = currentPage;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public List getRows() {
        return rows;
    }

    public void setRows(List rows) {
        this.rows = rows;
    }

}

统一结果数据格式类

/**
 * Created by lin on 2017/8/15.
 */
public class Result implements Serializable {
    Integer code;
    String msg;
    Object data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

统一结果数据格式工具类

/**
 * Created by lin on 2017/8/15.
 */
public class ResultUtil {

    public static Result success(){
        Result result=new Result();
        result.setCode(0);
        result.setMsg("success");
        return result;
    }

    public static Result success(Object o){
        Result result=new Result();
        result.setCode(0);
        result.setMsg("success");
        result.setData(o);
        return result;
    }
    public static Result error(){
        Result result=new Result();
        result.setCode(-1);
        result.setMsg("error");
        return result;
    }
    public static Result error(String msg){
        Result result=new Result();
        result.setCode(-1);
        result.setMsg(msg);
        return result;
    }

    public static Result error(Integer code, String msg){
        Result result=new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

用法

        Result result;
        long size = cameraList.size();
        PageData resultata = new PageData(cameraList, size, pagesize, page);
        result = ResultUtil.success(resultata);

你可能感兴趣的:(2018-08-02 APBS服务总结)