SpringMVC4+thymeleaf3的一个简单实例(篇三:页面参数获取)

来源:互联网 发布:linux安装源码包下载站 编辑:程序博客网 时间:2024/06/05 11:16

本篇将通过示例介绍页面参数是如何传递到后台的。我们继续沿用之前搭好的程序结构,如果你不知道,请参照前两篇。


为方便跳转页面,我们在首页以及zoolist.html页面都加上彼此地址的链接:

首页加上

zoolist.html页

运行tomcat看看结果

如果页面显示出来是乱码,请参照本文第二篇:springMVC与thymeleaf的整合中解决页面乱码的代码。


好,我们开始页面传值。

这之前请将unbescape-1.1.4.RELEASE.jar文件放入WEB-INF/lib目录下,thymeleaf解析页面的标签要用到,此文件在你之前下载thymeleaf-3.0.2.RELEASE-dist.zip里面。


一、修改zoolist.html页面

给页面添加form,text输入框,文件代码如下:

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>zoo list</title></head><body><a href='.'>首页</a>->动物列表<br><br><form id="iform" th:action="@{/list.html?save}" th:method="post" th:object="${animalForm}"><table border="1">    <tr>     <th>动物名称</th>      <th>数量</th>     <th>备注</th>    <th>Action</th>  </tr>    <tr>     <td><input type="text" name="oname" value="" th:value="*{oname}"/></td>    <td><input type="text" name="ocount" value="" th:value="*{ocount}"/></td>    <td><input type="text" name="memo" value="" th:value="*{memo}"/></td>    <td><input type="submit" value="添加"/></td>  </tr></table></form><hr><table border="1">    <tr>    <th>序号</th>    <th>动物名称</th>      <th>数量</th>     <th>备注</th>  </tr>  <tr>    <td>1</td>    <td>大马猴</td>    <td>10</td>    <td>机灵古怪,俏皮活泼</td>  </tr>  <tr>    <td>2</td>    <td>大熊猫</td>    <td>80</td>    <td>体型笨重,喜欢吃竹子</td>  </tr>  <tr>    <td>3</td>    <td>澳洲羊驼</td>    <td>13</td>    <td>长相奇特,大国人俗称其草泥马</td>  </tr>  <tr>    <td>4</td>    <td>峨眉山猴</td>    <td>90</td>    <td>不怕人,有时候发贱抢游客面包吃</td>  </tr></table></body></html>

解释:

我们在<html>标签里加了个xmlns:th="http://www.thymeleaf.org"属性,如果没有这个声明属性,你的IDE可能会对th:*标签报告没有定义命名空间的错误,仅此而已,没有它页面照样正常解析。

th:action属性,其值为"@{/list.html?save}",意思是在thymeleaf解析时会将"@{/list.html?save}"代替静态页面的action的值;th:method表示其值将代替静态页面的method的值;@{/list.html?save}是thymeleaf的url链接表达式,其通用格式为@{...},举个栗子,假如我们的form标签是这样的:<form id="iform" action='abclist.html'  method="get" th:action="@{/list.html?save}"  th:method="post" >,那么在我们的环境中解析后的结果会是:<form id="iform" action=“/zoo/list.html?save" method="post">。

th:object="${animalForm}"属性,表示有一个属性名为"animalForm"的java bean(其属性要有get set方法)会传递到页面上来,这个名字一定和下面ZooController里的属性名称对应起来,一般我们会把这个bean用于表示html中form里的字段,注意form里只能放一个th:object,否则会出现编译错误: org.attoparser.ParseException: (Line = 10, Column = 96) Malformed markup: Attribute "th:object" appears more than once in element。

th:value="*{oname}"表示取得animalForm实例中的oname字段的值,也就是通过调用animalForm.getOname()获得,举个例子,假如后台传到页面的animalForm中的oname字段值为“大马猴”,那么运行结果将是<td><input type="text" name="oname" value="大马猴" /></td>。

最后注意th:object的作用范围,这个属性仅在所在标签范围内有效,比如本例只在iform这个表单内有效,只有在这个form标签范围内,使用星号表达式*{fieldName}才能取得其值。


二、在src下添加package:com.zoo.web.form,并在此包下新建类:AnimalForm.java,代码如下:

package com.zoo.web.form;public class AnimalForm {private long id;private String oname;private int ocount;private String memo;/** * @return the id */public long getId() {return id;}/** * @param id the id to set */public void setId(long id) {this.id = id;}/** * @return the oname */public String getOname() {return oname;}/** * @param oname the oname to set */public void setOname(String oname) {this.oname = oname;}/** * @return the ocount */public int getOcount() {return ocount;}/** * @param ocount the ocount to set */public void setOcount(int ocount) {this.ocount = ocount;}/** * @return the memo */public String getMemo() {return memo;}/** * @param memo the memo to set */public void setMemo(String memo) {this.memo = memo;}}


三、修改ZooController.java里的showZooList()方法,文件代码:

package com.zoo.web.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;import com.zoo.web.form.AnimalForm;@Controllerpublic class ZooController {@RequestMapping(path = "/list", method = RequestMethod.GET)public ModelAndView showZooList(){ModelAndView mav = new ModelAndView();mav.setViewName("zoolist");mav.addObject("animalForm", new AnimalForm());return mav;}}
解释:之前的代码我们做了以上修改,我们用到了springMVC里的ModelAndView,为的是将animalForm这个bean传递到页面上去;之前这个方法返回的是"zoolist"字符串,现在修改为返回一个ModelAndView类型,并把viewname设置为"zoolist",其实它对应的就是WEB-INF/pages下的zoolist.html页面,所有这些操作都会由springMVC框架完成,非常方便,感谢为spring开源社区做出贡献的每一个人。


重新启动tomcat,进入动物列表页面看看:

恭喜你!修改成功!


四、在ZooController里添加一个方法来响应按钮【添加】这个动作:

@RequestMapping(path = "/list", params = {"save"}, method = RequestMethod.POST)public String doAdd(AnimalForm form){System.out.println("动物名:" + form.getOname());System.out.println("数量:" + form.getOcount());System.out.println("备注:" + form.getMemo());return "zoolist";}

解释:注意这个注解里多了一个值为"save"的params参数,它表示只对含有save这个参数的url请求起作用,如果发现客户端传递来的参数里没有“save”这个参数则不与应答,对于doAdd方法来说,http://localhost:8080/zoo/list.html?save或者http://localhost:8080/zoo/list.html?save=123或者http://localhost:8080/zoo/list.html?save&age=9等都可以响应,不过前提必须是form的method为post。

这个方法带一个AnimalForm参数,页面提交后form中的字段能够传递到后台的秘密就在这里,粗心的你有没有注意到AnimalForm这个bean里的字段名称和zoolist.html页面里form中的字段名称一模一样一字不差,也就是和input text框的name属性值是一样的。这期间你什么都没做页面的数据怎会填充进这个bean的呢?对了,还是伟大的spring frame work给我们做了无缝连接,无论你定义什么名称以及什么类型的bean,只要bean里的字段名称在页面上也有(字段必须有get set方法),那么spring就会给你赋值进来;你也可以这样:doAdd(AnimalForm form, AnotherAnimalForm1 form1, AnotherAnimalForm2 form2......),只要form bean里有和页面form对应的字段,这些bean都会被填充。

眼尖的同学已经发现了doAdd和showZooList这两个方法响应的都是"/list",没错,是这样的,但是别忘了注解RequestMapping的参数是不一样的,首先method的不一样,不同的method会调用不同的方法,再就是params不一样,你可以通过这些参数对请求做范围限制。RequestMapping的可选元素有 consumes,headers,method,name,params,path,produces,value,详细解释请参照 springAPI文档http://docs.spring.io/spring/docs/current/javadoc-api/ 


接下来我们重启tomcat,浏览动物列表页面,并在text框内输入一些文字:


点击【添加】按钮:


哎呦我去,怎么页面form传到后台的数据是乱码,再看看控制台,果真:


也是乱码呀,哪里缺少了设置呢,让我喝杯绝对零度的红茶压压惊!


编辑web.xml,加入这段代码:

  <!-- 从页面过来的数据都转为UTF-8 -->  <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>  </filter>  <filter-mapping>    <filter-name>encodingFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>

整个web.xml现在是这个样子:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>zoo</display-name>  <display-name>springMVC-test</display-name>    <!-- 从页面过来的数据都转为UTF-8 -->  <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>  </filter>  <filter-mapping>    <filter-name>encodingFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>     <servlet>    <servlet-name>springMVC</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:com/xmlconfig/spring-mvc.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>*.html</url-pattern>  </servlet-mapping>    <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>

再次重启小猫米,这下完美了吧!看看console:


好了,解决了!


我们的下一篇将是form数据验证。


篇末语:当你用thymeleaf模板时,在eclipse中修改了html页面,并在浏览器中刷新想看看效果,却发现页面没有变化,只有重启tomcat才有反应,这个时候只需把<property name="cacheable" value="false" />属性添加到配置文件spring-mvc.xm中的  <bean id="templateResolver"    class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">里面即可,而不再要重启web server啦。

有关thymeleaf语法的详细介绍请参照thymeleaf文档:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

以及thymeleaf+spring文档:http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html


END.



1 0
原创粉丝点击