2018-08-02 APBS服務(wù)總結(jié)

1.maven部分jar包下載不到捐韩,要看看是不是springboot版本問(wèn)題退唠,可以在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時(shí)荤胁,需要添加配置編譯插件瞧预。

   <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>

用法如下
對(duì)象序列化為json字符串

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

json字符串反序列化為對(duì)象

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

4.解決跨域訪問(wèn)攔截器

/**
 *   攔截器
 * Created by lin on 2017/8/21.
 */
public class AccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //解決跨域請(qǐng)求
      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類應(yīng)用(重要)

WebMvcConfigurerAdapter配置類其實(shí)是Spring內(nèi)部的一種配置方式,采用JavaBean的形式來(lái)代替?zhèn)鹘y(tǒng)的xml配置文件形式進(jìn)行針對(duì)框架個(gè)性化定制仅政。

在配置類上添加了注解@Configuration垢油,標(biāo)明了該類是一個(gè)配置類并且會(huì)將該類作為一個(gè)SpringBean添加到IOC容器內(nèi)。

@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請(qǐng)求的路徑
        //addResourceLocations是圖片存放的真實(shí)路徑
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+uploadFilePath);
        super.addResourceHandlers(registry);
    }
}

6.全局異常處理

業(yè)務(wù)異常類

/**
 * Created by lin on 2017/10/20.
 * 實(shí)際業(yè)務(wù)異常
 */
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;
    }
}

異常處理器

/**
 * 異常處理器圆丹,捕獲所有異常滩愁,并按照統(tǒng)一格式返回
 * 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("系統(tǒng)異常: RequestURI=" +request.getRequestURL()) ;
        logger.error("系統(tǒng)異常:" +e.toString());
        logger.error("系統(tǒng)異常:" +e.getMessage(),e);
        e.printStackTrace();
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return ResultUtil.error(ErrorCode.REQUEST_METHOD_ERROR.getValue(), "HttpRequestMethodNotSupportedException:請(qǐng)求方式(Get/Post)錯(cuò)誤");
        }
        if (e instanceof MissingServletRequestParameterException) {
            return ResultUtil.error(ErrorCode.MISSING_PARAMETERS.getValue(),"MissingServletRequestParameterException: 缺少參數(shù)");
        }
        if (e instanceof MethodArgumentTypeMismatchException) {
            return ResultUtil.error(ErrorCode.INVALID_PARAMETERS.getValue(),"MethodArgumentTypeMismatchException:參數(shù)類型錯(cuò)誤");
        }
       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(),"系統(tǒng)異常" );
    }
}

拋出業(yè)務(wù)異常

   @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 在攔截器驗(yàn)證成功>>>>>>>>>>>>>>>>>>");
            return true;// 只有返回true才會(huì)繼續(xù)向下執(zhí)行,返回false取消當(dāng)前請(qǐng)求 3c3d2eacb5d0435c9918f4c1eac50f0f
        } else {
            String url = httpServletRequest.getRequestURI();
            logger.warn(">>>>>>>>>>>>>>>>>token:" + token + "\t 在攔截器驗(yàn)證失敗>>>>>>>>>>>>>>>>>>");
            logger.warn(">>>>>>>>>>>>>>>>>驗(yàn)證失敗url:" + url);
            throw new BusinessException("token incorrect or expired");
        }

    }

7.統(tǒng)一接口返回格式

分頁(yè)數(shù)據(jù)格式類

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

    private static final long serialVersionUID = 1L;
    private Integer currentPage;// 當(dāng)前頁(yè)數(shù)
    private Integer pageSize;// 每頁(yè)的大小
    private Long total;// 數(shù)據(jù)總條數(shù)
    private List<M> rows;// 當(dāng)前頁(yè)的數(shù)據(jù)

    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;
    }

}

統(tǒng)一結(jié)果數(shù)據(jù)格式類

/**
 * 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;
    }
}

統(tǒng)一結(jié)果數(shù)據(jù)格式工具類

/**
 * 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);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末辫封,一起剝皮案震驚了整個(gè)濱河市硝枉,隨后出現(xiàn)的幾起案子廉丽,更是在濱河造成了極大的恐慌,老刑警劉巖妻味,帶你破解...
    沈念sama閱讀 222,865評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件正压,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡弧可,警方通過(guò)查閱死者的電腦和手機(jī)指攒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,296評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)氯庆,“玉大人瓤漏,你說(shuō)我怎么就攤上這事⌒L祝” “怎么了价脾?”我有些...
    開封第一講書人閱讀 169,631評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)笛匙。 經(jīng)常有香客問(wèn)我侨把,道長(zhǎng),這世上最難降的妖魔是什么妹孙? 我笑而不...
    開封第一講書人閱讀 60,199評(píng)論 1 300
  • 正文 為了忘掉前任秋柄,我火速辦了婚禮,結(jié)果婚禮上蠢正,老公的妹妹穿的比我還像新娘骇笔。我一直安慰自己,他們只是感情好嚣崭,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,196評(píng)論 6 398
  • 文/花漫 我一把揭開白布笨触。 她就那樣靜靜地躺著,像睡著了一般雹舀。 火紅的嫁衣襯著肌膚如雪芦劣。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,793評(píng)論 1 314
  • 那天说榆,我揣著相機(jī)與錄音虚吟,去河邊找鬼。 笑死签财,一個(gè)胖子當(dāng)著我的面吹牛稍味,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播荠卷,決...
    沈念sama閱讀 41,221評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼模庐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了油宜?” 一聲冷哼從身側(cè)響起掂碱,我...
    開封第一講書人閱讀 40,174評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤怜姿,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后疼燥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體沧卢,經(jīng)...
    沈念sama閱讀 46,699評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,770評(píng)論 3 343
  • 正文 我和宋清朗相戀三年醉者,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了但狭。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,918評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡撬即,死狀恐怖立磁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情剥槐,我是刑警寧澤唱歧,帶...
    沈念sama閱讀 36,573評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站粒竖,受9級(jí)特大地震影響颅崩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蕊苗,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,255評(píng)論 3 336
  • 文/蒙蒙 一沿后、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧朽砰,春花似錦尖滚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,749評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)饱搏。三九已至非剃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間推沸,已是汗流浹背备绽。 一陣腳步聲響...
    開封第一講書人閱讀 33,862評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鬓催,地道東北人肺素。 一個(gè)月前我還...
    沈念sama閱讀 49,364評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像宇驾,于是被迫代替她去往敵國(guó)和親倍靡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,926評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理课舍,服務(wù)發(fā)現(xiàn)塌西,斷路器他挎,智...
    卡卡羅2017閱讀 134,719評(píng)論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,868評(píng)論 6 342
  • 1、通過(guò)CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明先生_X自主閱讀 15,988評(píng)論 3 119
  • 原材料引用(Materials):Without lifesaving measures, the brain s...
    斷刺飄雪閱讀 286評(píng)論 0 0
  • 文/姜希米勵(lì) 2013年11月份,閨女跟隨奶奶回到了老家站辉,從此開始了我和我閨女寧寧的兩地分居的生活呢撞。 寧...
    姜希米勵(lì)閱讀 301評(píng)論 0 1