ajax传递给springmvc数据中包含token,如何在interceptor中取出token数据
我试图实现一个防止表单重复提交的功能,可是我不知道如何在Interceptor中获取我在ajax中提交的token数据。我的代码基本如下:
TokenInterceptor.java
public class TokenInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = Logger.getLogger(TokenInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Token annotation = method.getAnnotation(Token.class);
if (annotation != null) {
boolean needSaveSession = annotation.save();
if (needSaveSession) {
request.getSession(false).setAttribute(SessionProperties.TOKEN, UUIDGenerator.generateUUID());
}
boolean needRemoveSession = annotation.remove();
if (needRemoveSession) {
if (isRepeatSubmit(request, SessionProperties.TOKEN)) {
return false;
}
request.getSession(false).removeAttribute(SessionProperties.TOKEN);
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
private boolean isRepeatSubmit(HttpServletRequest request, String tokenName) {
String serverToken = (String) request.getSession(false).getAttribute(tokenName);
if (serverToken == null) {
return true;
}
String clientToken = request.getParameter(tokenName);
if (clientToken == null) {
return true;
}
if (!serverToken.equals(clientToken)) {
return true;
}
return false;
}
}
ajax数据
var product = {
'token' : token,
'name' : name,
'shortId' : shortId,
'serializedId' : serializedId,
'categoryId' : categoryId,
'comment' : comment,
'productSpecBeans' : specs==null ? [] : specs,
'tags' : tags==null ? [] : tags,
}
服务器端controller
@Token(save = true)
@RequestMapping(value = "add", method = RequestMethod.GET)
public ModelAndView add( HttpServletRequest servletRequest){
ModelMap modelMap = new ModelMap();
ProductBean productBean = new ProductBean();
modelMap.addAttribute(SessionProperties.PRODUCT_ADD_BEAN, productBean);
return new ModelAndView("product_add", modelMap);
}
Token标签
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
boolean save() default false;
boolean remove() default false;
}
这里的interceptor参考了网上的代码设计,但是网上一般采用form来提交表单,如果采用ajax的data如何提取token呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论