1.创建注解文件 (文件格式为注解) 这里面什么都不需要写 文件名就是注解名称 如下 是@anno
package com.ABC123.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解. 在方法上添加这个注解. 必须登录之后才能执行这个方法
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface anno {
}
2.创建一个类先实现HandlerInterceptor接口里面的方法 当然不想要全部都实现可以继承他的适配器HandlerInterceptorAdapter类
package com.ABC123.inter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.ABC123.anno.anno;
import com.ABC123.utils.UserContext;
public class LoginInter extends HandlerInterceptorAdapter {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
//之前拦截
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception {
//你请求的目标必须是方法
if(obj instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) obj;
Object o = hm.getMethodAnnotation(anno.class);
if(o==null) {//没有这个注解
return true;
}else {//有注解
if(UserContext.getCurrent() == null) {//没有登录
resp.sendRedirect("/paike/login.jsp");
return false;
}else { //登录了
return true;
}
}
}
return true;
}
}
3.最后配置springmvc的xml文件
<!-- 开启mvc --> <mvc:annotation-driven /> <bean id="inter" class="com.ABC123.inter.LoginInter"></bean> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/><!-- 拦截所有 --> <ref bean="inter"/> </mvc:interceptor> </mvc:interceptors>
4.在需要拦截的类上面写生注解@anno

当进入这个已经有注解的方法时会先经过拦截 符合的才放行