Multiaction Simple Form ใน Spring

วันนี้นั่งปั่น Topic ว่าจะให้ได้ 25% กับอีก 1 Usecase (% progress ตอนนี้นับตาม Usecase อ่ะ เอา Usecase ที่เสร็จ / Usecase ทั้งหมด x 100) แล้วก็เสร็จจนได้ก่อนไปเชียงใหม่ (ที่จริงมันก็ไม่ยากอะไร แค่ register เหอะๆ) ก็เล่นทำตั้งแต่เช้า จนเย็นจะไม่เสร็จได้ไงเนอะ (จริงๆ มันมีอะไรมาขัดเยอะ เช่น เล่นเกม ดูการ์ตูน … จนทำจริงๆ แค่ไม่กี่ชม แหะๆ) แล้วก็ได้โค้ดการทำ Simple Multi Action Form Controller มาใครที่เล่น Spring MVC คงรู้ว่า Spring Multiaction Controller มันโคตรจะน่าเล่นเลย เพราะมันรวม path ของเว็บมาอยู่ที่ class เดียว แต่มันดันทำ form แบบ Form Controller ไม่ได้ ><” ก็เลยต้องออกแรงขุดซะหน่อยถึงวิธีการทำของมัน แล้วก็ได้ SimpleMultiActionFormController มา ดูโค้ดกันดีกว่าFrom : http://forum.springframework.org/showthread.php?t=11702& amp;highlight=spring+form+multiactionอันนี้แก้ MethodNameResolver ให้รับ parameter และเซท default method ที่จะให้วิ่งไป


public class SubmitParameterPropertiesMethodNameResolver implements MethodNameResolver
{
	private String defaultMethodName;
	private Properties mappings;

	/**
	 * Set URL to method name mappings from a Properties object.
	 * @param mappings properties with URL as key and method name as value
	 */
	public void setMappings(Properties mappings) {
		this.mappings = mappings;
	}

	/**
	 * @param defaultMethodName The defaultMethodName to set.
	 */
	public void setDefaultMethodName(String defaultMethodName) {
		this.defaultMethodName = defaultMethodName;
	}

	public void afterPropertiesSet() {
		if (this.mappings == null || this.mappings.isEmpty()) {
			throw new IllegalArgumentException("'mappings' property is required");
		}
	}	

	public String getHandlerMethodName(HttpServletRequest request) throws NoSuchRequestHandlingMethodException {
		for (Iterator it = this.mappings.keySet().iterator(); it.hasNext();) {
			String submitParamter = (String) it.next();
			if (WebUtils.hasSubmitParameter(request, submitParamter)) {
				return (String) this.mappings.get(submitParamter);
			}
		}
		return defaultMethodName;
	}

อันนี้เป็นโค้ดของ SimpleMultiaActionFormController


public abstract class SimpleMultiActionFormController extends SimpleFormController {
	private MethodNameResolver methodNameResolver = new SubmitParameterPropertiesMethodNameResolver();

	public final void setMethodNameResolver(MethodNameResolver methodNameResolver) {
		this.methodNameResolver = methodNameResolver;
	}

	public final MethodNameResolver getMethodNameResolver() {
		return this.methodNameResolver;
	}

	protected ModelAndView processFormSubmission(HttpServletRequest request,
						     HttpServletResponse response,
						     Object command,
						     BindException errors) throws Exception {
		if (errors.hasErrors() || isFormChangeRequest(request)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Data binding errors: " + errors.getErrorCount());
			}
			return showForm(request, response, errors);
		} else {
			String methodName = this.methodNameResolver.getHandlerMethodName(request);
			Method m = (Method) this.getClass().getMethod(methodName,
								      new Class[] {
								      HttpServletRequest.class,
								      Object.class,
								      BindException.class});

			if (m == null) {
				throw new NoSuchRequestHandlingMethodException(methodName, getClass());
			}
			List params = new ArrayList(3);
			params.add(request);
			params.add(command);
			params.add(errors);
			return (ModelAndView) m.invoke(this, params.toArray(new Object[params.size()]));
		}
	}
}

ตัวอย่างๆ


<bean id="submitActionParamResolver" class="com.codebitches.springframework.web.servlet.mvc.multiaction.SubmitParameterPropertiesMethodNameResolver">
<property name="mappings">
<props>
<prop key="_addSubject">addSubject</prop>
<prop key="_finish">finalSubmit</prop>
</props>
</property>
<property name="defaultMethodName">
<value>finalSubmit</value>
</property>
</bean>
<bean id="createEditItemFormController" class="com.codebitches.springxmldb.examples.tilesnews.web.spring.CreateEditItemFormController">
<property name="methodNameResolver">
<ref bean="submitActionParamResolver"/>
</property>
<property name="sessionForm">
<value>true</value>
</property>
<property name="successView">
<value>
createEditItemConfirmation</value>
</property>
<property name="commandName">
<value>item</value>
</property>
<property name="formView">
<value>createEditItemForm</value>
</property>
</bean>

สร้าง Controller ที่ extend จาก SimpleMultiActionFormController


public class CreateEditItemFormController extends SimpleMultiActionFormController {
	private ITilesNewsCMS cms;
	private static Log log = LogFactory.getLog(CreateEditItemFormController.class);
	/**
	 * @param cms The cms to set.
	 */
	public void setCms(ITilesNewsCMS cms) {
		this.cms = cms;
	}
	public CreateEditItemFormController() {	}
	protected Object formBackingObject(HttpServletRequest request) throws ModelAndViewDefiningException {
		String id = request.getParameter("itemId");
		Item item = new Item();
		if (id != null && !id.equals("")) {
			item = cms.getItem(id);
		}
		return item;
	}

	public ModelAndView addSubject(HttpServletRequest request, Object command, BindException errors) throws Exception {
		Item item = (Item) command;
		Collection subs = item.getMetadata().getSubjects();
		subs.add(new ItemSubject());
		return this.showForm(request, errors, getFormView());
	}

	public ModelAndView finalSubmit(HttpServletRequest request, Object command, BindException errors) throws Exception {
		Item item = (Item) command;
		item = cms.createOrUpdateItem(item);
		Map model = new HashMap();
		model.put("item", item);
		return new ModelAndView(getSuccessView(), model);
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
	 */
	protected Map referenceData(HttpServletRequest request) throws Exception {
		return super.referenceData(request);
	}

ปล.บ่นเกี่ยวกับ SDH(Spring + DWR + Hibernate) หน่อย ช่วงแรกๆ ใช้โคตรยากเลย ใช้เป็นแล้วมันจะเป็นอะไรที่อำนวยความสะดวกสุดๆ ชอบจริงๆ เลย โดยเฉพาะตอน Test
ปล2. ต่อไปถ้ามีโอกาสจะแว๊บไป EJB3 ^ ^
ปล3. Google Web Toolkit(GWT) ใครๆ บอกใช้ง่าย + โคตรดี แต่ไมลองใช้เอง ใช้ไม่เป็นเลยฟะ ><”



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow



About Author

llun

Apple addict programmer