1 24 package org.riotfamily.common.web.transaction; 25 26 import javax.servlet.http.HttpServletRequest ; 27 import javax.servlet.http.HttpServletResponse ; 28 29 import org.springframework.core.Ordered; 30 import org.springframework.transaction.PlatformTransactionManager; 31 import org.springframework.transaction.TransactionDefinition; 32 import org.springframework.transaction.TransactionStatus; 33 import org.springframework.transaction.support.DefaultTransactionDefinition; 34 import org.springframework.web.servlet.HandlerAdapter; 35 import org.springframework.web.servlet.ModelAndView; 36 import org.springframework.web.servlet.mvc.Controller; 37 import org.springframework.web.servlet.mvc.LastModified; 38 39 53 public class TransactionalControllerHandlerAdapter 54 implements HandlerAdapter, Ordered { 55 56 private PlatformTransactionManager transactionManager; 57 58 private int order = Integer.MAX_VALUE - 1; 59 60 public TransactionalControllerHandlerAdapter( 61 PlatformTransactionManager transactionManager) { 62 63 this.transactionManager = transactionManager; 64 } 65 66 public int getOrder() { 67 return this.order; 68 } 69 70 public void setOrder(int order) { 71 this.order = order; 72 } 73 74 public boolean supports(Object handler) { 75 return handler instanceof TransactionalController; 76 } 77 78 public ModelAndView handle(HttpServletRequest request, 79 HttpServletResponse response, Object handler) 80 throws Exception { 81 82 Controller controller = (Controller) handler; 83 84 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); 85 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); 86 87 TransactionStatus status = transactionManager.getTransaction(def); 88 ModelAndView mv; 89 try { 90 mv = controller.handleRequest(request, response); 91 } 92 catch (Exception ex) { 93 transactionManager.rollback(status); 94 throw ex; 95 } 96 transactionManager.commit(status); 97 return mv; 98 } 99 100 public long getLastModified(HttpServletRequest request, Object handler) { 101 if (handler instanceof LastModified) { 102 return ((LastModified) handler).getLastModified(request); 103 } 104 return -1L; 105 } 106 107 } 108 | Popular Tags |