拦截器springmvc防止表单重复提交【3】自己实际项目

1:【定义注解】

 1 package com.jspxcms.ext.interceptor;
 2 import java.lang.annotation.ElementType;
 3 import java.lang.annotation.Retention;
 4 import java.lang.annotation.RetentionPolicy;
 5 import java.lang.annotation.Target;
 6 
 7 @Target(ElementType.METHOD)
 8 @Retention(RetentionPolicy.RUNTIME)
 9 public @interface Token  {
10     
11      boolean save() default false;
12 
13      boolean remove() default false;
14 
15 }

2:定义拦截器

 1 package com.jspxcms.ext.interceptor;
 2 
 3 import java.lang.reflect.Method;
 4 import java.util.UUID;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import org.apache.log4j.Logger;
10 import org.springframework.web.method.HandlerMethod;
11 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
12 
13 import com.jspxcms.core.support.CmsException;
14 
15 public class TokenInterceptor extends HandlerInterceptorAdapter {
16     private static final Logger LOG = Logger.getLogger(TokenInterceptor.class);
17     
18     
19     
20     @Override
21     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
22         if (handler instanceof HandlerMethod) {
23             HandlerMethod handlerMethod = (HandlerMethod) handler;
24             Method method = handlerMethod.getMethod();
25             Token  annotation = method.getAnnotation(Token.class);
26             if (annotation != null) {
27                 boolean needSaveSession = annotation.save();
28                 if (needSaveSession) {
29                     request.getSession(true).setAttribute("token", UUID.randomUUID().toString());
30                 }
31                 boolean needRemoveSession = annotation.remove();
32                 if (needRemoveSession) {
33                     if (isRepeatSubmit(request)) {
34                          LOG.warn("please don't repeat submit,url:"+ request.getServletPath());
35                          throw new CmsException("不能重复提交申请页面!");
36                        // return false;
37                     }
38                     request.getSession(true).removeAttribute("token");
39                 }
40             }
41             return true;
42         } else {
43             return super.preHandle(request, response, handler);
44         }
45     }
46 
47     private boolean isRepeatSubmit(HttpServletRequest request) {
48         String serverToken = (String) request.getSession(true).getAttribute("token");
49         if (serverToken == null) {
50             return true;
51         }
52         String clinetToken = request.getParameter("token");
53         if (clinetToken == null) {
54             return true;
55         }
56         if (!serverToken.equals(clinetToken)) {
57             return true;
58         }
59         return false;
60     }
61 }

3:spring配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
 9         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"
10     default-lazy-init="true">
11 
12     <context:annotation-config/>
13     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
14         <property name="webBindingInitializer">
15             <bean class="com.jspxcms.common.web.BindingInitializer"/>
16         </property>
17         <property name="customArgumentResolvers">
18             <list>
19                 <bean class="com.jspxcms.common.web.PageableArgumentResolver" />
20             </list>
21         </property>
22     </bean>
23   
24   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
25   </bean>
26  
27     <mvc:annotation-driven />
28     <mvc:interceptors>
29         <bean class="com.jspxcms.core.support.ForeInterceptor"/>
30         <mvc:interceptor>
31              <mvc:mapping path="/**"/>
32             <bean class="com.jspxcms.ext.interceptor.TokenInterceptor"></bean>
33         </mvc:interceptor>
34     </mvc:interceptors>    
35 
36     <bean id="viewResolver" class="com.jspxcms.common.freemarker.FreeMarkerViewResolver">
37         <property name="contentType" value="text/html; charset=UTF-8"/>
38         <property name="cacheUnresolved" value="false"/>
39     <property name="redirectHttp10Compatible" value="false"/>
40     </bean>
41 </beans>

4:方法使用

 1     @Token(save=true)
 2     @RequestMapping( value = "/expertJoinForm.jspx" )
 3     public String expertJoinForm(HttpServletRequest request,
 4             HttpServletResponse response, org.springframework.ui.Model modelMap ) {
 5         User user = Context.getCurrentUser( request );
 6         if( user == null ) {
 7             String id = request.getParameter( "id" );
 8             Response resp = new Response( request, response, modelMap );
 9             Site site = Context.getCurrentSite( request );
10             GlobalRegister registerConf = site.getGlobal().getRegister();
11             String orgId = request.getParameter( "orgId" );
12             if( orgId == null || orgId.trim().equals( "" ) ) {
13                 orgId = "1";
14             }
15             if( id != null && id != "1" ) {
16                 Org org = orgService.get( Integer.parseInt( id ) );
17                 List<Org> orgList = new ArrayList<Org>();
18                 orgList.add( org );
19                 modelMap.addAttribute( "orgList", orgList );
20             }
21             else {
22                 List<Org> orgList = orgService.findList( null, 1, false, null, null );
23                 modelMap.addAttribute( "orgList", orgList );
24             }
25             Org org = orgService.get( Integer.parseInt( orgId ) );
26             modelMap.addAttribute( "org", org );
27             if( registerConf.getMode() == GlobalRegister.MODE_OFF ) {
28                 return resp.warning( "register.off" );
29             }
30             Map<String, Object> data = modelMap.asMap();
31             ForeContext.setData( data, request );
32             return "/1/hongchuang/sys_member_register.html";
33         }else{        
34             CmsAdvisor advisor=new CmsAdvisor();
35             modelMap.addAttribute( "advisor", advisor);
36             Map<String, Object> data = modelMap.asMap();
37             ForeContext.setData( data, request );
38             return "/1/hongchuang/expertJoinForm1.html";
39         }
40     }
41 
42     /**
43      * 前台申请加入专家功能
44      * @author DIXIN
45      * @since 0727
46      * @param advisor
47      * @param request
48      * @param response
49      * @param modelMap
50      * @return
51      */
52     @Token(remove=true)
53     @RequestMapping( value = "/saveExpertJoinForm.jspx" )
54     public String saveExpertJoinForm(CmsAdvisor advisor, HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model modelMap ) {
55         Response resp = new Response( request, response, modelMap );
56         advisorService.save( advisor);
57         Map<String, Object> data = modelMap.asMap();
58         ForeContext.setData( data, request );
59         return "/1/hongchuang/expertJoinForm2.html";
60     }

5:页面使用

需要放在form里面

<input type="hidden" name="token" value="${token}" />

 

posted @ 2016-09-01 17:48  涤新云  阅读(3618)  评论(0编辑  收藏  举报