1.创建@interface自定义注解
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface HandlerLJ {
}
2.写一个实现HandlerInterceptor拦截器的类
import com.alibaba.fastjson.JSON;
import com.hx.slj.modules.zybGrzx.service.zybGrzxService;
import org.codehaus.jackson.map.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import static com.sun.xml.internal.ws.api.message.Packet.State.ServerResponse;
public class HandlerLJInterceptor implements HandlerInterceptor {
@Autowired
private zybGrzxService zybGrzxService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag = false;
if (!(handler instanceof HandlerMethod)) { return true; }
HandlerLJ handlerLJ = ((HandlerMethod)handler).getMethodAnnotation(HandlerLJ.class);
if (null == handlerLJ){
flag = true;
}else{
String YzToken = request.getHeader("token");
if("".equals(YzToken)){
PrintWriter pw = response.getWriter();
flag = false;
Map<String,Object> map = new HashMap<>();
map.put("code","1");
map.put("message","请先登录!");
pw.write(JSON.toJSONString(map));
pw.flush();
pw.close();
}else{
flag = true;
}
System.err.println(flag);
}
return flag;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
3.在spring-mvc.xml中配置拦截器
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<mvc:mapping path="${adminPath}/**"/>
<!--被排除拦截的资源-->
<mvc:exclude-mapping path="${adminPath}/zybGrzx/grzxLogin"/>
<mvc:exclude-mapping path="${adminPath}/zybGrzx/grzxSubmit"/>
<bean class="com.hx.slj.modules.zybGrzx.config.HandlerLJInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
4.类中调用
@RequestMapping("/test")
@HandlerLJ
@ResponseBody
public Map<String,Object> test(){
Map<String,Object> map = new HashMap<>();
map.put("data","成功!");
return map;
}