在struts2 in action中所见,这样封装后省去了大部分crud反复代码。尽管还不能理悟。先记下来。
abstract class BaseAction extends ActionSupport { protected DB db; protected static Log log = LogFactory.getLog(BaseAction.class); private long requestId; private boolean readOnly = false; private String mappedRequest; @SkipValidation public String show(){ setReadOnly(true); setMappedRequest(Constants.LIST); return SUCCESS; } @SkipValidation public String add(){ setMappedRequest(Constants.SAVE); return SUCCESS; } public String save(){ db.save(getModel()); return list(); } @SkipValidation public String edit(){ setMappingRequest(Constants.UPDATE); return SUCCESS; } public String update(){ db.save(getModel()); return list(); } @SkipValidation public String destroy(){ setReadOnly(true); setMappingRequest(Constants.REMOVE); return Constants.SUCCESS; } public String remove(){ db.remove(getModel()); return list(); } @SkipValidation public String list(){ setMappingedRequest(Constants.LIST); return Constants.LIST; } public String getActionClass(){ return getClass().getSimpleName(); } public String getDestination(){ return getClass().getSimpleName(); } public String getActionMethod(){ return mappedRequest; } public void setActionMethod(String method){ this.mappedRequest = method; } public void setMappedRequest(String actionMethed){ this.mappedRequest = getActionClass() + "_" + actionMethed; log.debug("setting mappedRequest to "+ getActionClass() + "_" + actionMethed); } public void setReadOnly(boolean readOnly){ this.readOnly = readOnly; log.debug("setting readOnly to "+readOnly); } public long getRequestId(){ return requestId; } public void setRequestId(long requestId){ this.requestId = requestId; } public void setDb(DB db){ this.db = db; } public boolean isReadOnly(){ return readOnly; } public abstract Object getModel(); }
public class MemberAction extends BaseAction implements ModelDriven,Preparable { private Member model; public Member getModel(){ return model; } public void prepare() throws Exception{ if(getRequestId() == 0){ model = new Member(); }else{ model = (Member) db.get(getRequestId); } } }