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