SpEL:即Spring Expression Language,是一种强大的表达式语言。在Spring产品组合中,它是表达式计算的基础。它支持在运行时查询和操作对象图,它可以与基于XML和基于注解的Spring配置还有bean定义一起使用。由于它能够在运行时动态分配值,因此可以为我们节省大量Java代码。可以用于解析特殊字符串(比如Bean的属性可以直接在字符串中的点出来)。
- 创建一个注解:
package org.demo.controller;
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 Role {
String value() default "hello";
}
- 编写拦截器实现 :EmbeddedValueResolverAware
package org.demo.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.demo.controller.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Component // 类名首字母小写
public class LoginInterceptor extends HandlerInterceptorAdapter implements EmbeddedValueResolverAware {
private StringValueResolver svr;
private Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
/**
* 请求处理完成后执行 视图渲染之后执行, 收尾工作,资源的清理
*
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
log.info("after....");
}
/**
* handler执行完毕,视图渲染前执行
*
* 返回值:校验/检查/添加/脱敏
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
log.info("posthandler....");
}
/**
* 执行handler之前调用, 如果返回true ,则放行 返回false:则阻挡
*
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("prehandler....");
if (handler instanceof HandlerMethod) {
HandlerMethod had = (HandlerMethod) handler;
Role role = had.getMethodAnnotation(Role.class);
String str = svr.resolveStringValue(role.value());
log.info(str);//str就是解析出来的值
}
return true;// 放行
}
@Override
public void setEmbeddedValueResolver(StringValueResolver arg0) {
this.svr = arg0;
}
}
- controller中使用注解
@Role("${user}")
public List<Shxx> list() {
log.info("list.......");
// 1.调用sevice查询
List<Shxx> sl = sds.getList();
// 2. 查询出的数据转为json
return sl;
}
- 编写一个pro文件
user=admin
5.测试ok
网友评论