主要是要注意spring-mvc.xml(spring 的 controller設定檔)中的相關配置項
<!-- 只掃描@Controller --><context:component-scan base-package="cn.com.sunnyrock.vimes.portal" use-default-filters="true"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!--編碼轉換,其預設為ISO-8859-1--><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="cacheSeconds" value="0" /> <property name="messageConverters"> <list> <bean class = "org.springframework.http.converter.StringHttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list></property> </bean>
<!--annotation自動注入,這個配置很重要--><bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!--必須去掉這個配置項 <mvc:annotation-driven /> -->
Controller中的方法
@RequestMapping(value = "/feedback", method = RequestMethod.POST)public @ResponseBodyString feedback(HttpServletRequest request, HttpServletResponse response, FeedbackModel feedback) throws Exception{//TODOreturn "非常感謝您對我們提出的寶貴意見或建議";}
JSP中的Ajax調用(這裡使用了jquery.form.js這個plugin)
var feedbackAdviceForm = "#feedbackAdviceForm";
$(feedbackAdviceForm).submit(function() {if($.trim($("#advice",feedbackAdviceForm).val())==""){alert("請輸入您的寶貴意見或建議。");$("#advice",feedbackAdviceForm).focus();return false;}$(this).ajaxSubmit({success: function(msg) {alert(msg);},error: function(context, xhr) {alert(context.responseText);}});});
<form id="feedbackAdviceForm" name="feedbackAdviceForm" action="<%=rootPath %>/member/feedback.html" method="post" onSubmit="return false;"><p><label for="advice">請輸入您的寶貴意見或建議</label><br> <textarea id="advice" name="advice" rows="3" cols="20"style="width: 200px; height: 120px;"></textarea></p><p><input type="submit" value="提交"></p></form>