2016年9月12日 星期一

使用Form傳遞參數

使用Form傳遞參數
參考:
http://viralpatel.net/blogs/spring-3-mvc-handling-forms/

前置步驟
【web.xml】
加入下段程式碼,以避免POST中的中文參數變成亂碼
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!-- async-supported>true</async-supported -->
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- web.xml中,这段配置要放在所有filter的最前面,否则会不生效。可參考:http://www.jianshu.com/p/435c13cfc769 -->





-------------------------------------------------------------------------------------------------------------------------
1 建立FORM


package mysite.model;

public class CharaTestForm {
private String teststr;
private CharainfoDto charainfoDto;

public String getTeststr() {
return teststr;
}
public void setTeststr(String teststr) {
this.teststr = teststr;
}
public CharainfoDto getCharainfoDto() {
return charainfoDto;
}
public void setCharainfoDto(CharainfoDto charainfoDto) {
this.charainfoDto = charainfoDto;
}
}

-------------------------------------------------------------------------------------------------------------------------
【Controller】

(import都省略)

預先宣告會使用的FORM
CharaTestForm charaTestForm = new CharaTestForm();

// 將資料透過Form傳入頁面:
@RequestMapping("editPage")
public String to_editPage(Model model) throws SQLException, IOException {
CharainfoDto charainfoDto = cypherswikiService.getCharainfo("Loras");

// 設定Form裡的值
charaTestForm.setTeststr("中文");
charaTestForm.setCharainfoDto(charainfoDto);

// 傳入Form
model.addAttribute("testForm", charaTestForm);
}

// 從頁面傳回的Form取得值:
@RequestMapping(value="saveChara" ,method = RequestMethod.POST)
public void to_saveChara(@ModelAttribute("testForm") CharaTestForm charaTestForm,
Model model) throws SQLException, IOException {

String teststr = charaTestForm.getTeststr(); // 取得值!
}


-------------------------------------------------------------------------------------------------------------------------

【JSP頁面中】
最上面增加
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>



<form:form action="saveChara" method="post" modelAttribute="testForm">
                                                            ^^^^^^^^^參數名稱

直接使用參數 ${testForm.charainfoDtot.title}

<table border="1" style="width: 60%">
<tr><td>TEST</td><td><form:input type="text" path="teststr"/></td></tr>
<tr><td>TEST2</td><td><form:input type="text" path="charainfoDto.title"/></td></tr>
<input type="submit" value="按此儲存">


</form:form>