2018-08-02 APBS服务总结

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

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

   <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>

添加编译插件

     <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
           <configuration>
            <source>1.7</source>
            <target>1.7</target>
           </configuration>
     </plugin>

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

     <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.8.2</version>
     </dependency>

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

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

json字符串反序列化为对象

...
 List<HPMCameraBean> tempList = new Gson().fromJson(data,new TypeToken<List<HPMCameraBean>>(){}.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 <M> implements Serializable {

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

    public PageData(List<M> 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<M> getRows() {
        return rows;
    }

    public void setRows(List<M> 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<HPMCameraBean> resultata = new PageData<HPMCameraBean>(cameraList, size, pagesize, page);
        result = ResultUtil.success(resultata);
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容