1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.krad.web.controller;
17
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.beans.factory.annotation.Qualifier;
20 import org.springframework.transaction.PlatformTransactionManager;
21 import org.springframework.transaction.TransactionDefinition;
22 import org.springframework.transaction.TransactionStatus;
23 import org.springframework.transaction.support.DefaultTransactionDefinition;
24 import org.springframework.web.servlet.HandlerInterceptor;
25 import org.springframework.web.servlet.ModelAndView;
26
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29
30
31
32
33
34
35
36
37
38
39
40 public class TransactionHandlerInterceptor implements HandlerInterceptor {
41
42 private static final ThreadLocal<TransactionStatus> context = new ThreadLocal<TransactionStatus>();
43
44 @Autowired()
45 @Qualifier("transactionManager")
46 PlatformTransactionManager txManager;
47
48
49
50
51 @Override
52 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
53 throws Exception {
54 DefaultTransactionDefinition def = new DefaultTransactionDefinition();
55 def.setName("request");
56 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
57
58 TransactionStatus status = txManager.getTransaction(def);
59 context.set(status);
60
61 return true;
62 }
63
64
65
66
67 @Override
68 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
69 ModelAndView modelAndView) throws Exception {
70 completeTransaction(null);
71 }
72
73
74
75
76 @Override
77 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
78 throws Exception {
79 completeTransaction(ex);
80 }
81
82
83
84
85
86
87 protected void completeTransaction(Exception ex) {
88 TransactionStatus status = context.get();
89
90 if (status == null) {
91 return;
92 }
93
94 try {
95 if (!status.isCompleted()) {
96 if (ex == null && !status.isRollbackOnly()) {
97 txManager.commit(status);
98 } else {
99 txManager.rollback(status);
100 }
101 }
102 } finally {
103 context.remove();
104 }
105 }
106 }