01: package com.mockrunner.example.struts;
02:
03: import javax.servlet.ServletContext;
04: import javax.servlet.http.HttpServletRequest;
05: import javax.servlet.http.HttpServletResponse;
06:
07: import org.apache.struts.action.Action;
08: import org.apache.struts.action.ActionForm;
09: import org.apache.struts.action.ActionForward;
10: import org.apache.struts.action.ActionMapping;
11:
12: /**
13: * This example action demonstrates the access to a data repository
14: * stored in the <code>ServletContext</code>. Since the repository
15: * is not thread safe we have to synchronize the access. Used to
16: * demonstrate how to do multithread testing. Check out
17: * {@link StoreDataActionTest}.
18: */
19: public class StoreDataAction extends Action {
20: public ActionForward execute(ActionMapping mapping,
21: ActionForm form, HttpServletRequest request,
22: HttpServletResponse response) throws Exception {
23: ServletContext context = request.getSession()
24: .getServletContext();
25: synchronized (context) {
26: String id = request.getParameter("id");
27: String data = request.getParameter("data");
28: MemoryBasedRepository repository = MemoryBasedRepository
29: .instance(context);
30: if (repository.get(id) != null)
31: return mapping.findForward("failure");
32: System.out.println("Thread "
33: + Thread.currentThread().getName()
34: + " wins the race");
35: repository.set(id, data);
36: return mapping.findForward("success");
37: }
38: }
39: }
|