⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 crudcontroller.java

📁 一个很好的开源项目管理系统源代码
💻 JAVA
字号:
package net.java.workeffort.webapp.action;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.java.workeffort.infrastructure.exception.IPropertyException;import net.java.workeffort.infrastructure.view.ViewHelper;import net.java.workeffort.service.support.ChildRowExistsFkException;import net.java.workeffort.service.support.OptimisticLockingException;import net.java.workeffort.service.support.UniqueConstraintException;import net.java.workeffort.webapp.support.InvalidSynchronizerTokenException;import net.java.workeffort.webapp.support.WebappUtils;import org.apache.commons.lang.Validate;import org.springframework.validation.BindException;import org.springframework.web.servlet.ModelAndView;/** * A generic controller for CRUD operations. The command object is stored in * session scope. * <p> * <b>Exposed configuration properties: (See BaseFormController also) </b> <br> * <table border="1"> * <tr> * <td><b>Name </b></td> * <td><b>Default </b></td> * <td><b>Description </b></td> * </tr> * <tr> * <td>service</td> * <td><i>null </i></td> * <td>The service. Required</td> * </tr> * <tr> * <td>formView</td> * <td><i>null </i></td> * <td>The form view. Required</td> * </tr> * <tr> * <td>commandClass</td> * <td><i>null </i></td> * <td>The command class. Required</td> * </tr> * <tr> * <td>primaryKeyParameterName</td> * <td><i>null </i></td> * <td>Name of the request parameter which will be used as the primary key for * querying the object. Required. Expects to find a property by this name in the * command object</td> * </tr> * <tr> * <td>commandClass</td> * <td><i>null </i></td> * <td>The command class. Required</td> * </tr> * <tr> * <td>insertMethodName</td> * <td><i>null </i></td> * <td>The insert method name in the service. Required</td> * </tr> * <tr> * <td>updateMethodName</td> * <td><i>null </i></td> * <td>The update method name in the service. Required</td> * </tr> * <tr> * <td>deleteMethodName</td> * <td><i>null </i></td> * <td>The delete method name in the service. Required</td> * </tr> * <tr> * <td>getObjectMethodName</td> * <td><i>null </i></td> * <td>The method name to retrive object in the service. Required</td> * </tr> * </table> * @author Antony Joseph */public class CrudController extends BaseFormController {    private String primaryKeyParameter;    private String insertMethodName;    private String updateMethodName;    private String deleteMethodName;    private String getObjectMethodName;    private Method insertMethod;    private Method updateMethod;    private Method deleteMethod;    private Method getObjectMethod;    private Class primaryKeyClass;    /**     * Initialize and validate whether this object is configured correctly.     */    protected void init() {        super.init();        Validate.notNull(service, "Service cannot be null");        Validate.notNull(getFormView(), "'formView' cannot be null");        Validate.notNull(getCommandClass(), "'commandClass' cannot be null");        Validate.notNull(insertMethodName, "'insertMethodName' cannot be null");        Validate.notNull(updateMethodName, "'updateMethodName' cannot be null");        Validate.notNull(deleteMethodName, "'deleteMethodName' cannot be null");        Validate.notNull(getObjectMethodName,                "'getObjectMethodName' cannot be null");        Validate.notEmpty(primaryKeyParameter,                "primaryKeyParameter cannot be null");        // get the primary key class using the configured primaryKeyParameter        // and command object Class        primaryKeyClass = WebappUtils.getPropertyType(primaryKeyParameter,                getCommandClass());        // get the insert/update/delete/getObject methods from the service        insertMethod = getServiceMethod(service.getClass(), insertMethodName,                new Class[] { getCommandClass() });        updateMethod = getServiceMethod(service.getClass(), updateMethodName,                new Class[] { getCommandClass() });        deleteMethod = getServiceMethod(service.getClass(), deleteMethodName,                new Class[] { getCommandClass() });        getObjectMethod = getServiceMethod(service.getClass(),                getObjectMethodName, new Class[] { primaryKeyClass });        // Make sure the form is stored in session scope.        setSessionForm(true);        setValidateOnBinding(false);    }    public void setDeleteMethodName(String deleteMethodName) {        this.deleteMethodName = deleteMethodName;    }    public void setGetObjectMethodName(String getObjectMethodName) {        this.getObjectMethodName = getObjectMethodName;    }    public void setInsertMethodName(String insertMethodName) {        this.insertMethodName = insertMethodName;    }    public void setUpdateMethodName(String updateMethodName) {        this.updateMethodName = updateMethodName;    }    public void setPrimaryKeyParameter(String primaryKeyParameter) {        this.primaryKeyParameter = primaryKeyParameter;    }    /**     * Gets the form backing object. When dispatch is 'query' retrieves the     * object from the database. When dispatch is 'new' creates a new command     * object and stores a transaction token as well as ViewHelper in users     * session     */    protected Object formBackingObject(HttpServletRequest request)            throws Exception {        if (logger.isInfoEnabled())            logger.info("formBackingObject() invoked.");        if (QUERY.equals(request.getParameter("dispatch"))) {            Object pk = getParameterValue(request, primaryKeyParameter,                    primaryKeyClass);            return getObject(request, pk);        }        else if (NEW.equals(request.getParameter("dispatch"))) {            // create new object screen. Show screen in insert mode and            // initialize the transaction token.            saveToken(request);            saveViewHelper(request, ViewHelper.INSERT_MODE);            return createCommand();        }        else            return createCommand();    }    /**     * During form submission, checks to make sure that the transaction token is     * valid. Also if the user is doing a delete, proceeds with the delete even     * if there are binding exceptions     */    protected ModelAndView processFormSubmission(HttpServletRequest request,            HttpServletResponse response, Object command, BindException errors)            throws Exception {        if (!isTokenValid(request)) {            clearToken(request);            throw new InvalidSynchronizerTokenException(                    "Invalid token. dispatch="                            + request.getParameter(DISPATCH_PARAMETER_NAME));        }        // Call onSubmit() when dispatch is delete even in the        // case where there are binding errors        if (DELETE.equals(request.getParameter(DISPATCH_PARAMETER_NAME))) {            logger.info("delete -> processing submit");            return onSubmit(request, response, command, errors);        }        else {            return super.processFormSubmission(request, response, command,                    errors);        }    }    protected ModelAndView onSubmit(HttpServletRequest request,            HttpServletResponse response, Object command, BindException errors)            throws Exception {        if (logger.isInfoEnabled())            logger.info("onSubmit() invoked.");        if (INSERT.equals(request.getParameter(DISPATCH_PARAMETER_NAME))) {            return insert(request, response, command, errors);        }        else if (UPDATE.equals(request.getParameter(DISPATCH_PARAMETER_NAME))) {            return update(request, response, command, errors);        }        else if (DELETE.equals(request.getParameter(DISPATCH_PARAMETER_NAME))) {            return delete(request, response, command, errors);        }        else            throw new RuntimeException("invalid dispatch:"                    + request.getParameter(DISPATCH_PARAMETER_NAME));    }    /**     * Inserts the object. Processes exceptions UniqueConstraintException and     * IPropertyException. Also saves a ViewHelper in session and saves a     * success message in message queue for jsps.     * @param request The request     * @param response The response     * @param command The command object     * @param errors The bind exception     * @return ModelAndView the model and view     * @throws Exception     */    protected ModelAndView insert(HttpServletRequest request,            HttpServletResponse response, Object command, BindException errors)            throws Exception {        try {            insertMethod.invoke(service, new Object[] { command });            saveViewHelper(request, ViewHelper.UPDATE_DELETE_MODE);            saveMessage(request, "insert.success");            // to prevent duplicate submissions create a new token            saveToken(request);            return showForm(request, response, errors);        }        catch (InvocationTargetException ite) {            Throwable t = ite.getTargetException();            if (t instanceof UniqueConstraintException) {                ((IPropertyException) t).setPropertyName(primaryKeyParameter);                populatePropertyErrors(errors, (IPropertyException) t);                return showForm(request, response, errors);            }            else if (t instanceof IPropertyException) {                populatePropertyErrors(errors, (IPropertyException) t);                return showForm(request, response, errors);            }            else                throw (Exception) t;        }    }    /**     * Updates the object. Processes exceptions OptimisitcLockingException and     * IPropertyException. Also saves a ViewHelper for the jsps to help render     * the view appropriately and transaction token to prevent multiple submits.     * @param request the request     * @param response the response     * @param command the command object     * @param errors the bind exception     * @return the model and view     * @throws Exception     */    protected ModelAndView update(HttpServletRequest request,            HttpServletResponse response, Object command, BindException errors)            throws Exception {        try {            updateMethod.invoke(service, new Object[] { command });            saveViewHelper(request, ViewHelper.UPDATE_DELETE_MODE);            saveMessage(request, "update.success");            // to prevent duplicate submissions create a new token            saveToken(request);            return showForm(request, response, errors);        }        catch (InvocationTargetException ite) {            Throwable t = ite.getTargetException();            if (t instanceof OptimisticLockingException) {                errors.reject(((OptimisticLockingException) t).getErrorCode());                return showForm(request, response, errors);            }            else if (t instanceof IPropertyException) {                populatePropertyErrors(errors, (IPropertyException) t);                return showForm(request, response, errors);            }            else                throw (Exception) t;        }    }    /**     * Deletes the object. Processes exceptions OptimisticLockingException and     * ChildRowExistsFkException. Also clears the transaction token if     * successful     * @param request the request     * @param response the response     * @param command the command object     * @param errors the bind exception     * @return the model and view     * @throws Exception     */    protected ModelAndView delete(HttpServletRequest request,            HttpServletResponse response, Object command, BindException errors)            throws Exception {        try {            deleteMethod.invoke(service, new Object[] { command });            saveMessage(request, "delete.success");            clearToken(request);            return new ModelAndView(".deleteSuccess");        }        catch (InvocationTargetException ite) {            Throwable t = ite.getTargetException();            if (t instanceof OptimisticLockingException) {                errors.reject(((OptimisticLockingException) t).getErrorCode());                return showForm(request, response, errors);            }            else if (t instanceof ChildRowExistsFkException) {                errors.reject(((ChildRowExistsFkException) t).getErrorCode());                return showForm(request, response, errors);            }            else                throw (Exception) t;        }    }    /**     * Gets the object from the service layer. Also saves a ViewHelper for the     * jsps to help render the view appropriately and transaction token to     * prevent multiple submits.     * @param request the http request     * @param pk The primary key     * @return The object     */    protected Object getObject(HttpServletRequest request, Object pk) {        if (logger.isInfoEnabled())            logger.info("getObject invoked.");        Object result = null;        try {            result = getObjectMethod.invoke(service, new Object[] { pk });            saveViewHelper(request, ViewHelper.UPDATE_DELETE_MODE);            // initialize the transaction token. Is used in submit            // processing to prevent duplicate submits            saveToken(request);        }        catch (Exception e) {            throw new RuntimeException(e);        }        return result;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -