1、我們項目中會經常使用帶springmvc 的攔截器來校驗當前請求的前置規則,比如是不是有訪問權限,參數合法等。
2、攔截器說明:
我的項目是自定義類繼承
org.springframework.web.servlet.handler.HandlerInterceptorAdapter,然后實現其中的三個前置、后置和最后渲染的攔截方法。主要業務一般寫在
preHandle(request,response,object);方法中,比如參數校驗。
3、為了解決攔截失敗返回參數的一致性,我們需要返回自己的回調信息
package com.cloudstore.v4.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.init.entity.initMember;
import com.cloudstore.init.service.initMemberService;
import com.cloudstore.v4.entity.TAuthMember;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
public class AuthHandler extends HandlerInterceptorAdapter {
@Autowired
private initMemberService memberService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String ecId = httpServletRequest.getParameter("ecId");
if(StringUtils.isEmpty(ecId)){
writeFailure(httpServletResponse);
return false;
}
return true;
}
private void writeFailure(HttpServletResponse response) throws IOException {
JSONObject result = new JSONObject();
result.put("code",0);
result.put("errMsg","對不起,你沒有權限!");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.write(result.toString());
writer.flush();
writer.close();
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
以上是一個簡單的參數校驗。如果不為空就放過,否則,就返回{code:0,errMsg:'你沒有權限'}這樣的數據格式。和我們api的返回格式一樣
