一、简单介绍:
1、先调用接口一 获取一个图片标识码,
2、根据图片标识码再调用接口二 获取图片验证码,
3、再根据图片验证码 、用户名 、密码调用登录接口,获取一个token,此时这个token保存到数据库,并且需要返回出去给用户,
4、下次请求其他接口的时候携带此token过来,在这里我们使用了SpringMvc的拦截器,可以在applicationcontent-mvc.xml中配置拦截器的
路径,
5、如果不需要被拦截的路径就配置在其中,比如我们的获取图片标识码、图片验证码、登录接口就不需要拦截,其他都需要拦截,
此时再调用其他接口的时候用户携带返回的token,此时的token在SpringMvc中的拦截器中就判断是否有效,有效的话其他接口才
能调用其他的接口。
6、在这里一二步骤可以省略哟,还有token也不定需要在拦截器中判断哟,如果只有两三个接口的时候直接在每一个接口判断token是否
有效就行了
7、使用场景:商城中的会员登录、http请求的各种接口、单点登录等
二、代码操作:
2.1 SpringMvc拦截器配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="net.shopnc.b2b2c.apiseller.action"/>
<!-- 会员访问权限过滤 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/logout"/>
<mvc:exclude-mapping path="/unauth"/>
<mvc:exclude-mapping path="/captcha/**"/>
<mvc:exclude-mapping path="/common/**"/>
<bean class="net.shopnc.b2b2c.apiseller.common.SecurityInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<mvc:annotation-driven ignore-default-model-on-redirect = "true" />
<mvc:default-servlet-handler/>
</beans>
2.2 再用此类SecurityInterceptor(配置中)去继承
public class SecurityInterceptor implements HandlerInterceptor {
protected final Logger logger = Logger.getLogger(getClass());
@Autowired
private ApiSellerTokenService apiSellerTokenService;
@Autowired
private StoreService storeService;
/**
* 在处理器调用之前被调用
*/
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws ServletException, IOException {
if("OPTIONS".equals(req.getMethod())) {
return true;
}
String token = req.getParameter("token");
//token不存在直接返回401
if (token == null || token.equals("")) {
req.getRequestDispatcher("/unauth").forward(req, res);
}
try {
Seller seller = apiSellerTokenService.getSellerByToken(token);
req.setAttribute("seller", seller);
Store store = storeService.getStoreByStoreId(seller.getStoreId());
req.setAttribute("store", store);
} catch (ShopException e) {
//令牌失效直接返回401
req.getRequestDispatcher("/unauth").forward(req, res);
}
return true;
}
/**
* 在处理器调用之后执行
*/
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object arg2, ModelAndView arg3) throws Exception {
}
/**
* 在请求结束之后调用
*/
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object arg2, Exception arg3) throws Exception {
}
三、获取图片标识码接口
返回一个随机加密的标识码
四、 获取图片验证码接口
返回一个4位数的随机字符串,保存到数据库
五、登录接口
1、主要就是保存用户信息加以判断是否正确
2、以及token ,再返回一个token出去,
3、登录是先验证验证码是否正确,先删除一小前的过期验证码,查询验证码,判断验证码,删除验证码
六、返回实体类工具类代码:
@Controller
public class BaseAction {
protected final Logger logger = Logger.getLogger(getClass());
@Autowired
protected LangHelper langHelper;
@Autowired
private SellerService sellerService;
/**
* 获取成功返回实体
* @param datas
* @return
*/
protected ApiResultEntity getSuccessEntity(HashMap<String, Object> datas) {
ApiResultEntity apiResultEntity = new ApiResultEntity();
apiResultEntity.setCode(ApiResultEntity.SUCCESS);
apiResultEntity.setDatas(datas);
return apiResultEntity;
}
/**
* 记录日志
*
* @param content
*/
public void addSellerLog(String content) {
try {
addSellerLog(content, ShopHelper.getAddressIP());
} catch (Exception ex) {
//处理所有异常,仅记录日志
ex.printStackTrace();
logger.warn("Seller日志记录失败" + ex.toString());
}
}
/**
* 记录日志
* @param content
* @param ip
*/
private void addSellerLog(String content, String ip) {
int sellerId = 0;
String sellerName = "";
int storeId = 0;
try {
sellerId = ApiSellerSessionHelper.getSeller().getSellerId();
sellerName = ApiSellerSessionHelper.getSeller().getSellerName();
storeId = ApiSellerSessionHelper.getStore().getStoreId();
} catch (Exception ex) {
logger.warn("商家操作日志记录,商家信息获取失败");
}
SellerLog sellerLog = new SellerLog();
sellerLog.setSellerId(sellerId);
sellerLog.setSellerName(sellerName);
sellerLog.setStoreId(storeId);
sellerLog.setAddTime(ShopHelper.getCurrentTimestamp());
sellerLog.setLogContent(content);
sellerLog.setLogIp(ip);
sellerService.saveSellerLog(sellerLog);
}
/**
* 获取成功返回实体
* @return
*/
protected ApiResultEntity getSuccessEntity(){
ApiResultEntity apiResultEntity = new ApiResultEntity();
apiResultEntity.setCode(ApiResultEntity.SUCCESS);
HashMap<String, Object> datas = new HashMap<>();
datas.put("success", "操作成功");
apiResultEntity.setDatas(datas);
return apiResultEntity;
}
/**
* 获取失败返回实体
* @param error
* @return
*/
protected ApiResultEntity getErrorEntity(String error) {
ApiResultEntity apiResultEntity = new ApiResultEntity();
apiResultEntity.setCode(ApiResultEntity.FAIL);
HashMap<String, Object> datas = new HashMap<>();
datas.put("error", error);
apiResultEntity.setDatas(datas);
return apiResultEntity;
}
/**
* 获取失败返回实体
* @return
*/
protected ApiResultEntity getErrorEntity() {
ApiResultEntity apiResultEntity = new ApiResultEntity();
apiResultEntity.setCode(ApiResultEntity.FAIL);
HashMap<String, Object> datas = new HashMap<>();
datas.put("error", "操作失败");
apiResultEntity.setDatas(datas);
return apiResultEntity;
}
/**
* 获取失败返回实体
* @param error
* @return
*/
protected ApiResultEntity getErrorEntity(String error, HashMap<String, Object> datas) {
ApiResultEntity apiResultEntity = new ApiResultEntity();
apiResultEntity.setCode(ApiResultEntity.FAIL);
datas.put("error", error);
apiResultEntity.setDatas(datas);
return apiResultEntity;
}
/**
* 获取未授权返回实体
* @return
*/
protected ApiResultEntity getUnauthEntity() {
ApiResultEntity apiResultEntity = new ApiResultEntity();
apiResultEntity.setCode(ApiResultEntity.NOAUTH);
HashMap<String, Object> datas = new HashMap<>();
datas.put("error", "授权失败");
apiResultEntity.setDatas(datas);
return apiResultEntity;
}
/**
* 全局ConstraintViolationException异常处理
*
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler({ConstraintViolationException.class})
public ApiResultEntity constraintViolationException(ConstraintViolationException e) {
logger.error(e.toString(), e);
List<String> messageList = new ArrayList<>();
for(ConstraintViolation value : e.getConstraintViolations()){
messageList.add(value.getMessage());
}
String messageStr = "";
if (messageList!=null && messageList.size()>0) {
messageStr = StringUtils.join(messageList.toArray(), ",");
}else{
messageStr = "操作失败";
}
return getErrorEntity(messageStr);
}
/**
* 全局Shop异常处理
*/
@ResponseBody
@ExceptionHandler({ShopException.class})
public ApiResultEntity shopException(ShopException e) {
logger.error(e.toString(), e);
return getErrorEntity(e.getMessage());
}
/**
* 全局异常处理
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler({Exception.class})
public ApiResultEntity exception(Exception e) {
e.printStackTrace();
logger.error(e.toString(), e);
return getErrorEntity("参数错误");
}
}
========================================
public class ApiResultEntity {
public static final int SUCCESS = 200;
public static final int FAIL = 400;
public static final int NOAUTH = 401;
private int code;
private HashMap<String, Object> datas;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public HashMap<String, Object> getDatas() {
return datas;
}
public void setDatas(HashMap<String, Object> datas) {
this.datas = datas;
}
@Override
public String toString() {
return "ApiResultEntity{" +
"code=" + code +
", datas=" + datas +
'}';
}
}
接下来写自己的接口继承BaseAction:
@Controller
public class GoodsAction extends BaseAction {
@Autowired
private GoodsSellerService goodsSellerService;
@Autowired
private SpecService specService;
@Autowired
private SecurityHelper securityHelper;
@Autowired
private GoodsService goodsService;
@Autowired
private StoreService storeService;
/**
* 商品列表
* @param page
* @param type
* @param keyword
* @return
*/
@ResponseBody
@RequestMapping(value = "goods/list", method = RequestMethod.POST)
public ApiResultEntity goodsList(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(name = "type", required = false, defaultValue = "0") Integer type,
@RequestParam(name = "keyword", required = false, defaultValue = "") String keyword,
@RequestParam(name = "status", required = false, defaultValue = "default") String status
) throws ShopException {
List<String> ordersStateList = Arrays.asList("default", "online", "offline", "ban", "wait", "fail");
if (ordersStateList.contains(status) == false) {
logger.info("apiseller -> GoodsAction -> goodsList() -> status参数错误,“”、“default”、“online”、“offline”、“ban”、“wait”、“fail”");
logger.info("apiseller -> GoodsAction -> goodsList() -> status参数错误,status值为:" + status);
throw new ShopException();
}
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("page", page);
paramMap.put("type", type);
paramMap.put("keyword", keyword);
PageEntity<GoodsVo> pageEntity = goodsSellerService.getList(ApiSellerSessionHelper.getStore().getStoreId(), paramMap, status);
HashMap<String, Object> map = new HashMap<>();
map.put("goodsCommonList", pageEntity.getList());
map.put("pageEntity", pageEntity.getApiPageEntity());
return getSuccessEntity(map);
}
七、普通增删改的返回工具类:
package net.shopnc.common.entity;
/**
* Copyright: Bizpower多用户商城系统
* Copyright: www.bizpower.com
* Copyright: 天津网城商动科技有限责任公司
*
* 通用返回结果对象
*
* @author dqw
* Created 2017/4/17 12:02
*/
public class ResultEntity {
public static final int SUCCESS = 200;
public static final int FAIL = 400;
public static final int NO_LOGIN = 401;
private int code;
private String message = "";
private String url = "";
private Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
====================================================
增加操作:
/**
* 添加一个赠品
* @param activityGift
* @return
*/
@ResponseBody
@RequestMapping("/activity/gift/save.json")
public ResultEntity saveActivityGift(@Valid ActivityGift activityGift ){
ResultEntity resultEntity = new ResultEntity();
try {
activityGiftService.saveActivityGift(activityGift); ;
resultEntity.setCode(ResultEntity.SUCCESS);
} catch (Exception e) {
logger.error(e.getMessage());
resultEntity.setMessage(e.getMessage());
resultEntity.setCode(ResultEntity.FAIL);
}
return resultEntity;
}