p4jmvc 내 측 판

8881 단어 mvc
(성명: 현재 p4jmvc 내 측 판 은 Spring MVC 만 지원 하 며, 여러분 의 기술 참고 로 만 사용 합 니 다.)
첨부 파일 원본 다운로드 주소:http://download.csdn.net/detail/partner4java/5220557
역할: Controller 를 간소화 하고 자주 사용 하 는 CURD 작업, Controller 는 코드 를 한 줄 쓰 지 않 고 계승 만 하면 됩 니 다.
주의: p4jmvc 는 주로 p4jorm 을 빌 렸 습 니 다.
예 를 들 어 우 리 는 도시 관리 에 대한 Controller (도시 정보 수정 삭제 등 고정 매개 변수 id 만 입력 해 야 합 니 다)
BaseManageView 에서 계승 하려 면 추가 두 가지 만 완성 해 야 합 니 다.
1. 두 개의 범 형 유형, entity 와 formbean 유형 을 전달한다.
2. 매개 변수 구조 기 를 가지 고 BaseManageViewP4jdao 에 전달 합 니 다.
@Controller
@RequestMapping("/manage/city/*")
public class CityManageView extends BaseManageView<City, CityForm>{
	@SuppressWarnings("unused")
	private CityService cityService;
	
	@Autowired
	public CityManageView(CityService cityService) {
		super(cityService);
		this.cityService = cityService;
	}

}
핵심 기능 은 클래스 BaseManageView 에서 제공 합 니 다 (첨부 파일 원본 코드 를 구체 적 으로 보기).
package com.partner4java.mvc.controller;

import java.util.LinkedHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.partner4java.mvc.formbean.BaseForm;
import com.partner4java.orm.bean.page.PageData;
import com.partner4java.orm.bean.page.PageIndex;
import com.partner4java.orm.dao.P4jDao;
import com.partner4java.orm.dao.enums.OrderType;
import com.partner4java.tools.generic.GenericsGetHelper;
import com.partner4java.tools.reflection.ReflectionDataHelper;

/**
 * Controller   <br/>
 *       CURD    ,      Spring MVC。<br/>
 * <br/>
 * <b>  :</b>                , viewResolver prefix  ,      CURD                :<br/>
 *    Authority    ,     "authority/manage.jsp",
 * "authority/add.jsp","authority/edit.jsp"
 * 
 * @author partner4java
 * 
 * @param <E>
 *                      (entity)
 * @param <F>
 *                FormBean    (entity)
 */
public class BaseManageView<E, F extends BaseForm> {
	public static final String SET_VISIBLE = "setVisible";
	public static final String VISIBLE = "visible";
	public static final String ID = "id";
	public static final String DELETE_DO = "delete.do";
	public static final String CLOSE_DO = "close.do";
	public static final String OPEN_DO = "open.do";

	public static final String EDIT_DO = "edit.do";
	public static final String EDIT = "/edit";

	public static final String ADD_DO = "add.do";
	public static final String ADD = "/add";

	public static final String VIEW_LIST_DO = "viewlist.do";
	public static final String VIEW_LIST = "/viewlist";

	public static final String REDIRECT_VIEW_LIST = "redirect:viewlist.do";

	protected String entityClassNameL;
	protected String entityClassFullName;
	protected String formBeanFullName;
	protected String view_list;
	protected String add;
	protected String edit;

	protected P4jDao<E> dao;

	private Log logger = LogFactory.getLog(BaseManageView.class);

	@SuppressWarnings("unchecked")
	protected Class<E> entityClass = GenericsGetHelper.getSuperGenericsClass(this.getClass(),
			BaseManageView.class.getTypeParameters()[0]);

	@SuppressWarnings("unchecked")
	protected Class<F> formClass = GenericsGetHelper.getSuperGenericsClass(this.getClass(),
			BaseManageView.class.getTypeParameters()[1]);

	/**
	 *           
	 * 
	 * @param dao
	 *                 Service
	 */
	public BaseManageView(P4jDao<E> dao) {
		super();
		this.dao = dao;

		this.formBeanFullName = formClass.getName();

		this.entityClassFullName = entityClass.getName();
		this.entityClassNameL = entityClass.getSimpleName().toLowerCase();

		view_list = entityClassNameL + VIEW_LIST;
		add = entityClassNameL + ADD;
		edit = entityClassNameL + EDIT;
	}

	/**
	 *       <br/>
	 *            
	 * 
	 * @param model
	 *            spring Model  
	 * @param form
	 *                FormBean
	 * @return
	 */
	@RequestMapping(VIEW_LIST_DO)
	public String viewList(Model model, @ModelAttribute("form") F form) {
		return doViewList(model, form, null);
	}

	/**
	 *         
	 * 
	 * @param model
	 * @param form
	 * @param orderby
	 * @return
	 */
	protected String doViewList(Model model, F form, LinkedHashMap<String, OrderType> orderby) {
		try {
			PageData<E> pageData = dao.query(form, new PageIndex(form.getCurrentPage()), orderby);
			model.addAttribute("pageData", pageData);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view_list;
	}

	/**
	 *       
	 * 
	 * @param model
	 *            spring Model  
	 * @return
	 */
	@RequestMapping(value = ADD_DO, method = RequestMethod.GET)
	public String addView(Model model) {
		try {
			model.addAttribute("form", Class.forName(formBeanFullName).newInstance());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return add;
	}

	/**
	 *         
	 * 
	 * @param model
	 *            spring Model  
	 * @param form
	 *                FormBean
	 * @return     
	 */
	@RequestMapping(value = ADD_DO, method = RequestMethod.POST)
	public String add(Model model, @ModelAttribute("form") F form) {
		try {
			@SuppressWarnings("unchecked")
			E entity = (E) Class.forName(entityClassFullName).newInstance();
			BeanUtils.copyProperties(form, entity);
			dao.save(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return REDIRECT_VIEW_LIST;
	}

	/**
	 *       
	 * 
	 * @param model
	 *            spring Model  
	 * @param id
	 *                 id
	 * @return
	 */
	@RequestMapping(value = EDIT_DO, method = RequestMethod.GET)
	public String editView(Model model, @RequestParam(ID) int id) {
		try {
			E entity = dao.get(id);
			idExistException(entity,"editView");
			@SuppressWarnings("unchecked")
			F form = (F) Class.forName(formBeanFullName).newInstance();
			BeanUtils.copyProperties(entity, form);
			form.setId(id);
			model.addAttribute("form", form);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return edit;
	}

	/**
	 *       <br/>
	 *  form      “”    
	 * 
	 * @param model
	 *            spring Model  
	 * @param form
	 *                FormBean
	 * @param id
	 *                 id
	 * @return     
	 */
	@RequestMapping(value = EDIT_DO, method = RequestMethod.POST)
	public String edit(Model model, @ModelAttribute("form") F form) {
		try {
			E entity = dao.get(form.getId());
			idExistException(entity,"edit");
			BeanUtils.copyProperties(form, entity);
			dao.update(entity);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return REDIRECT_VIEW_LIST;
	}

	/**
	 *       
	 * 
	 * @param id
	 *                 id
	 * @return
	 */
	@RequestMapping(value = DELETE_DO, method = RequestMethod.GET)
	public String delete(@RequestParam("id") int id) {
		try {
			dao.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return REDIRECT_VIEW_LIST;
	}

	/**
	 *       <br/>
	 *       ,                “private boolean visible;”   
	 * 
	 * @param id
	 *              id
	 * @return
	 */
	@RequestMapping(value = CLOSE_DO, method = RequestMethod.GET)
	public String close(@RequestParam(ID) int id) {
		try {
			E entity = dao.get(id);
			idExistException(entity,"close");
			if (logger.isDebugEnabled()) {
				logger.debug("close() entity:" + entity.getClass() + " value:" + entity.toString());
			}
			ReflectionDataHelper.invokeMethod(entity, SET_VISIBLE, false);
			dao.update(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return REDIRECT_VIEW_LIST;
	}

	/**
	 *       <br/>
	 *       ,                “private boolean visible;”   
	 * 
	 * @param id
	 *              id
	 * @return
	 */
	@RequestMapping(value = OPEN_DO, method = RequestMethod.GET)
	public String open(@RequestParam(ID) int id) {
		try {
			E entity = dao.get(id);
			idExistException(entity,"open");
			if (logger.isDebugEnabled()) {
				logger.debug("open() entity:" + entity.getClass() + " value:" + entity.toString());
			}
			ReflectionDataHelper.invokeMethod(entity, SET_VISIBLE, true);
			dao.update(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return REDIRECT_VIEW_LIST;
	}

	private void idExistException(E entity,String methodName) {
		if(entity == null){
			throw new IllegalArgumentException(methodName + " id is not exist");
		}
	}
}

좋은 웹페이지 즐겨찾기