統(tǒng)一返回restful數(shù)據(jù):
首先確定需要返回的json數(shù)據(jù)的格式,定義一個(gè)統(tǒng)一返回類
package com.unicom.microservice.peixun.peixun_matb3.Response;
import com.unicom.microservice.peixun.peixun_matb3.enums.UnicomResponseEnums;
/**
* @program: 測(cè)試
* @description:返回的JSON數(shù)據(jù)結(jié)構(gòu)標(biāo)準(zhǔn)
* @author: mtb
* @create: 2018-10-17 09:01
**/
public class ResponseBean <T>{
private boolean success;
private T data;
private String errCode;
private String errMsg;
public ResponseBean(){}
public ResponseBean(boolean success, T data) {
super();
this.success = success;
this.data = data;
}
@Override
public String toString() {
return "ResponseBean{" +
"success=" + success +
", data=" + data +
", errCode='" + errCode + '\'' +
", errMsg='" + errMsg + '\'' +
'}';
}
public ResponseBean(boolean success, T data, String errCode, String errMsg) {
super();
this.success = success;
this.data = data;
this.errCode = errCode;
this.errMsg = errMsg;
}
public ResponseBean(boolean success, String errCode, String errMsg) {
this.success = success;
this.errCode = errCode;
this.errMsg = errMsg;
}
public ResponseBean(boolean success,UnicomResponseEnums enums){
this.success=success;
this.errCode=enums.getCode();
this.errMsg=enums.getMsg();
}
public ResponseBean(boolean success,T data,UnicomResponseEnums enums){
this.success=success;
this.data=data;
this.errCode=enums.getCode();
this.errMsg=enums.getMsg();
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
}
新建一個(gè)枚舉類脱货,將常用提示信息及錯(cuò)誤信息寫(xiě)入:
package com.unicom.microservice.peixun.peixun_matb3.enums;
/**
* @program: 測(cè)試
* @description:友好提示枚舉
* @author: mtb
* @create: 2018-10-17 08:52
**/
public enum UnicomResponseEnums {
SYSTEM_ERROR("-001","系統(tǒng)異常"),
BAD_REQUEST("-002","錯(cuò)誤的請(qǐng)求參數(shù)"),
NOT_FOUND("-003","找不到請(qǐng)求路徑碘菜!"),
CONNECTION_ERROR("-004","網(wǎng)絡(luò)連接請(qǐng)求失敗米苹!"),
METHOD_NOT_ALLOWED("-005","不合法的請(qǐng)求方式"),
DATABASE_ERROR("-004","數(shù)據(jù)庫(kù)異常"),
BOUND_STATEMENT_NOT_FOUNT("-006","找不到方法糕伐!"),
REPEAT_REGISTER("001","重復(fù)注冊(cè)"),
NO_USER_EXIST("002","用戶不存在"),
INVALID_PASSWORD("003","密碼錯(cuò)誤"),
NO_PERMISSION("004","非法請(qǐng)求!"),
SUCCESS_OPTION("005","操作成功蘸嘶!"),
NOT_MATCH("-007","用戶名和密碼不匹配"),
FAIL_GETDATA("-008","獲取信息失敗"),
BAD_REQUEST_TYPE("-009","錯(cuò)誤的請(qǐng)求類型"),
INVALID_MOBILE("010","無(wú)效的手機(jī)號(hào)碼"),
INVALID_EMAIL("011","無(wú)效的郵箱"),
INVALID_GENDER("012","無(wú)效的性別"),
REPEAT_MOBILE("014","已存在此手機(jī)號(hào)"),
REPEAT_EMAIL("015","已存在此郵箱地址"),
NO_RECORD("016","沒(méi)有查到相關(guān)記錄"),
LOGIN_SUCCESS("017","登陸成功"),
LOGOUT_SUCCESS("018","已退出登錄"),
SENDEMAIL_SUCCESS("019","郵件已發(fā)送良瞧,請(qǐng)注意查收"),
EDITPWD_SUCCESS("020","修改密碼成功"),
No_FileSELECT("021","未選擇文件"),
FILEUPLOAD_SUCCESS("022","上傳成功"),
NOLOGIN("023","未登陸"),
ILLEGAL_ARGUMENT("024","參數(shù)不合法"),
ERROR_IDCODE("025","驗(yàn)證碼不正確");
private String code;
private String msg;
private UnicomResponseEnums(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
建立一個(gè)自定義異常繼承 RuntimeException類,以便拋出自定義異常
package com.unicom.microservice.peixun.peixun_matb3.exception;
import com.unicom.microservice.peixun.peixun_matb3.enums.UnicomResponseEnums;
/**
* @program: 測(cè)試
* @description:自定義異常
* @author: mtb
* @create: 2018-10-17 08:57
**/
public class UnicomRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
protected String code;
protected String msg;
protected String message;//打印出的日志信息
public UnicomRuntimeException(UnicomResponseEnums enums, String message) {
super();
this.code = enums.getCode();
this.msg = enums.getMsg();
this.message = message;
}
public UnicomRuntimeException(UnicomResponseEnums enums) {
super();
this.code = enums.getCode();
this.msg = enums.getMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public UnicomRuntimeException() {
super();
}
public UnicomRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public UnicomRuntimeException(String message) {
super(message);
}
}
新建一個(gè)異常處理類:
package com.unicom.microservice.peixun.peixun_matb3.exception;
import javax.servlet.http.HttpServletRequest;
import com.unicom.microservice.peixun.peixun_matb3.Response.ResponseBean;
import com.unicom.microservice.peixun.peixun_matb3.enums.UnicomResponseEnums;
import org.apache.ibatis.binding.BindingException;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.net.ConnectException;
import java.sql.SQLException;
/**
* @program: 測(cè)試
* @description:全局的異常處理類
* @author: mtb
* @create: 2018-10-19 11:38
**/
@RestControllerAdvice(annotations={RestController.class,Controller.class})
public class SpringExceptionHandle {
private static final Logger logger = LoggerFactory.getLogger(SpringExceptionHandle.class);
/**
* 請(qǐng)求參數(shù)類型錯(cuò)誤異常的捕獲
* @param e
* @return
*/
@ExceptionHandler(value={BindException.class})
@ResponseBody
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public ResponseBean<String> badRequest(BindException e){
logger.error("occurs error when execute method ,message {}",e.getMessage());
return new ResponseBean<>(false, UnicomResponseEnums.BAD_REQUEST);
}
/**
* 404錯(cuò)誤異常的捕獲
* @param e
* @return
*/
@ExceptionHandler(value={NoHandlerFoundException.class})
@ResponseBody
@ResponseStatus(value=HttpStatus.NOT_FOUND)
public ResponseBean<String> badRequestNotFound(BindException e){
logger.error("occurs error when execute method ,message {}",e.getMessage());
return new ResponseBean<>(false,null, UnicomResponseEnums.NOT_FOUND);
}
/**
* mybatis未綁定異常
* @param e
* @return
*/
@ExceptionHandler(BindingException.class)
@ResponseBody
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBean<String> mybatis(Exception e){
logger.error("occurs error when execute method ,message {}",e.getMessage());
return new ResponseBean<>(false,UnicomResponseEnums.BOUND_STATEMENT_NOT_FOUNT);
}
/**
* 自定義異常的捕獲
* 自定義拋出異常训唱。統(tǒng)一的在這里捕獲返回JSON格式的友好提示褥蚯。
* @param exception
* @param request
* @return
*/
@ExceptionHandler(value={UnicomRuntimeException.class})
@ResponseBody
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public <T> ResponseBean<T> sendError(UnicomRuntimeException exception,HttpServletRequest request){
String requestURI = request.getRequestURI();
logger.error("occurs error when execute url ={} ,message {}",requestURI,exception.getMsg());
return new ResponseBean<>(false,exception.getCode(),exception.getMsg());
}
/**
* 數(shù)據(jù)庫(kù)操作出現(xiàn)異常
* @param e
* @return
*/
@ExceptionHandler(value={SQLException.class,DataAccessException.class})
@ResponseBody
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBean<String> systemError(Exception e){
logger.error("occurs error when execute method ,message {}",e.getMessage());
return new ResponseBean<>(false, UnicomResponseEnums.DATABASE_ERROR);
}
/**
* 網(wǎng)絡(luò)連接失敗况增!
* @param e
* @return
*/
@ExceptionHandler(value={ConnectException.class})
@ResponseBody
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBean<String> connect(Exception e){
logger.error("occurs error when execute method ,message {}",e.getMessage());
return new ResponseBean<>(false, UnicomResponseEnums.CONNECTION_ERROR);
}
@ExceptionHandler(value={Exception.class})
@ResponseBody
@ResponseStatus(value=HttpStatus.METHOD_NOT_ALLOWED)
public ResponseBean<String> notAllowed(Exception e){
logger.error("occurs error when execute method ,message {}",e.getMessage());
return new ResponseBean<>(false, UnicomResponseEnums.METHOD_NOT_ALLOWED);
}
}
建立一個(gè)測(cè)試controller類:
package com.unicom.microservice.peixun.peixun_matb3.web;/**
* Created by matengbing on 2018/10/15.
*/
import com.unicom.microservice.peixun.peixun_matb3.Response.ResponseBean;
import com.unicom.microservice.peixun.peixun_matb3.enums.UnicomResponseEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
/**
* @program: 測(cè)試
* @description:測(cè)試接口
* @author: mtb
* @create: 2018-10-15 11:26
**/
@RestController
@ApiIgnore
//@RequestMapping(value = "sayHello")
public class HelloController {
@CrossOrigin
@ApiOperation(value = "hello")
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public ResponseBean<UnicomResponseEnums> sayHello(){
ResponseBean responseBean=new ResponseBean(true,UnicomResponseEnums.SUCCESS_OPTION);
return responseBean;
}
}
使用postman測(cè)試接口:
注意要配置springboot啟動(dòng)類赞庶,掃描controller等注解類被掃描到
@API等注解是swagger的注解,如果沒(méi)有使用到可以刪除
我們?cè)趯?shí)現(xiàn)數(shù)據(jù)庫(kù)操作的方法中try澳骤,catch歧强,捕捉到異常后,拋出一個(gè)自定義異常
@Transactional
@Override
public int addUser(User user) {
try {
user.setUserpwd(DigestUtils.md5DigestAsHex(user.getUserpwd().getBytes()));
userMapper.insertUser(user);
return user.getId();
}catch (Exception e){
throw new UnicomRuntimeException(UnicomResponseEnums.FAIL_INSERTUSER);
}
}
接著攔截404錯(cuò)誤
package com.unicom.peixun.web;
import com.unicom.peixun.Response.ResponseBean;
import com.unicom.peixun.enums.UnicomResponseEnums;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* @program: peixun_matb3
* @description:
* @author: matengbing
* @create: 2018-10-20 09:08
**/
@RestController
public class MyBasicErrorController implements ErrorController {
private static final String ERROR_PATH="/error";
@RequestMapping("/error")
public ResponseBean<Object> handleError(HttpServletRequest request){
//獲取statusCode:401,404,500
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if(statusCode==404){
return new ResponseBean<>(false,null,UnicomResponseEnums.NOT_FOUND);
}else {
return new ResponseBean<>(false,null,UnicomResponseEnums.METHOD_NOT_ALLOWED);
}
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}
用于登錄攔截的攔截器實(shí)現(xiàn)返回restful數(shù)據(jù):
package com.unicom.peixun.inteceptor;
import com.alibaba.fastjson.JSON;
import com.unicom.peixun.Response.ResponseBean;
import com.unicom.peixun.domain.User;
import com.unicom.peixun.enums.UnicomResponseEnums;
import com.unicom.peixun.web.UserController;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
/**
* @program: peixun_matb3
* @description:
* @author: matengbing
* @create: 2018-10-18 10:40
**/
@Component
public class LoginInterceptor implements HandlerInterceptor {
private static Logger logger=Logger.getLogger(LoginInterceptor.class);
@Autowired
UserController userController;
// 在請(qǐng)求處理之前調(diào)用,只有返回true才會(huì)執(zhí)行請(qǐng)求
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
HttpSession session=httpServletRequest.getSession();
User user=(User) session.getAttribute("user");
//登錄過(guò)得用戶直接通過(guò)
if(user!=null){
return true;
}
//未登錄用戶攔截为肮,返回json數(shù)據(jù)
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json; charset=utf-8");
PrintWriter out = httpServletResponse.getWriter() ;
try{
ResponseBean<Object> responseBean=new ResponseBean<>(false,null,UnicomResponseEnums.NOLOGIN);
out = httpServletResponse.getWriter();
out.append(JSON.toJSON(responseBean).toString());
return false;
}
catch (Exception e) {
e.printStackTrace();
httpServletResponse.sendError(500);
return false;
}
}
@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 {
}
}
攔截器需要配置@configuration
package com.unicom.peixun.configuration;
import com.unicom.peixun.inteceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @program:
* @description:
* @author: mtb
* @create: 2018-10-18 10:50
**/
@Configuration
public class LoginAdapter extends WebMvcConfigurerAdapter {
@Autowired
LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
super.addInterceptors(registry);
}
/**
* 配置靜態(tài)訪問(wèn)資源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
配置了攔截器攔截所有請(qǐng)求摊册,不攔截/login,swagger的相關(guān)請(qǐng)求颊艳,靜態(tài)資源的請(qǐng)求茅特,
如果攔截了/login會(huì)出現(xiàn)循環(huán)重定向報(bào)錯(cuò)
如果攔截了swagger的相關(guān)請(qǐng)求忘分,查看swagger文檔時(shí)看不到相應(yīng)資源
喜歡的點(diǎn)點(diǎn)關(guān)注,點(diǎn)點(diǎn)贊温治。
對(duì)Java技術(shù)饭庞,架構(gòu)技術(shù)感興趣的同學(xué),歡迎加QQ群585550789熬荆,一起學(xué)習(xí)舟山,相互討論。
群內(nèi)已經(jīng)有小伙伴將知識(shí)體系整理好(源碼卤恳,筆記累盗,PPT,學(xué)習(xí)視頻)突琳,歡迎加群領(lǐng)取若债。