Controller:
@AuthPassport//这里可以
@Controller
@RequestMapping(value = "/account")
public class AccountController {
@AuthPassport//这里可以
@RequestMapping(value="/login", method = {RequestMethod.GET})
public String login(){
return "login";
}
}
自定义注解:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthPassport {
boolean validate() default true;
}
拦截器:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
//没有声明需要权限,或者声明不验证权限
if(authPassport == null || authPassport.validate() == false)
return true;
else{
//在这里实现自己的权限验证逻辑
if(false)//如果验证成功返回true(这里直接写false来模拟验证失败的处理)
return true;
else//如果验证失败
{
//返回到登录界面
response.sendRedirect("account/login");
return false;
}
}
}
else
return true;
}
}
XML:
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->
<bean class="com.demo.web.auth.AuthInterceptor"></bean>
</mvc:interceptors>