SpringMVC+Thymeleaf 处理表单提交
thymleaf处理表单提交的方式和jsp有些类似,也有点不同之处,这里操作一个小Demo,并说明:
1.demo的结构图如下所示:
pom.xml:
4.0.0
com
thymleaf-form
1.0-SNAPSHOT
war
thymleaf-form Maven Webapp
http://www.example.com
UTF-8
1.7
1.7
junit
junit
4.11
test
org.slf4j
slf4j-api
1.7.12
ch.qos.logback
logback-core
1.1.1
provided
ch.qos.logback
logback-classic
1.1.1
provided
com.alibaba
druid
1.0.25
org.mybatis
mybatis
3.3.0
org.mybatis
mybatis-spring
1.3.2
taglibs
standard
1.1.2
jstl
jstl
1.2
com.fasterxml.jackson.core
jackson-databind
2.5.4
javax.servlet
javax.servlet-api
3.1.0
provided
org.springframework
spring-core
4.3.14.RELEASE
org.springframework
spring-beans
4.3.14.RELEASE
org.springframework
spring-context
4.3.14.RELEASE
org.springframework
spring-jdbc
4.3.14.RELEASE
org.springframework
spring-tx
4.3.14.RELEASE
org.springframework
spring-web
4.3.14.RELEASE
org.springframework
spring-webmvc
4.3.14.RELEASE
org.springframework
spring-test
4.3.14.RELEASE
mysql
mysql-connector-java
5.1.35
runtime
org.aspectj
aspectjweaver
1.8.9
org.json
json
20170516
org.thymeleaf
thymeleaf-spring4
3.0.9.RELEASE
javax.validation
validation-api
2.0.1.Final
com.google.guava
guava
18.0
com.google.guava
guava
18.0
org.hibernate
hibernate-validator
5.3.6.Final
thymleaf-form
maven-clean-plugin
3.0.0
maven-resources-plugin
3.0.2
maven-compiler-plugin
3.7.0
maven-surefire-plugin
2.20.1
maven-war-plugin
3.2.0
maven-install-plugin
2.5.2
maven-deploy-plugin
2.8.2
FormController:
package com.home.controller;
import com.home.entity.Animal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
@RequestMapping("/")
public class FormController {
@RequestMapping("/shouye")
public String shouye(){
return "shouye";
}
@RequestMapping("/login")
public String login(ModelMap map){
map.put("title","这是标题");
Animal animal = new Animal();
animal.setId(1);
animal.setName("熊猫");
animal.setCount(5);
map.put("animal", animal);
return "login";
}
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add( Model model,@Valid Animal animal,BindingResult result){
String name = animal.getName();
Integer count = animal.getCount();
model.addAttribute("name",name);
model.addAttribute("count",count);
if(result.hasErrors()){
model.addAttribute("MSG", "出错啦!");
// model.addAttribute("result",result);
String defaultMessage = result.getFieldError().getDefaultMessage();
model.addAttribute("defaultMessage",defaultMessage);
}else{
model.addAttribute("MSG", "提交成功!");
}
return "result";
}
}
Animal:
package com.home.entity;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Animal {
@NotNull(message="id: 不能为空")
private Integer id;
@Size(max = 10, message="备注: 长度不能超过10个字符")
private String name;
@Range(min = 1, message="数量: 必须大于0")
@NotNull(message="数量: 不能为空")
private Integer count;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public String toString() {
return "Animal{" +
"id=" + id +
", name='" + name + '\'' +
", count=" + count +
'}';
}
}
applicationContext-mvc.xml:
注意这里的的跳转路径由原来的jsp改为了template的文件夹的路径,并且将characterEncoding统一为了UTF-8,防止出现中文乱码,当然web.xml中也要设置,如下可以见:
web.xml:
contextConfigLocation
classpath:/applicationContext-mvc.xml
org.springframework.web.context.ContextLoaderListener
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:applicationContext-mvc.xml
1
springMVC
/
org.springframework.web.context.request.RequestContextListener
login.html:
result.html:
Title
这边我是用的表单的验证并返回相关的错误信息,配置完成后我们启动这个项目,访问:
http://localhost:8080/login
这边我们如果输入相关的参数进行演示:
需要注意的地方:
引用命名空间
如果我们刚开始没有值,也可以像jsp那样进行编写相关的参数,然后提交,如下:
日期的表达:
controller层增加如下代码:
map.put("today",new Date());
html中增加如下代码:
13 May 2011
附相关代码的查看地址:
其它公共对象参考: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects
重点:thymeleaf与jsp相关的对照:
1,变量表达式
Thymeleaf模板引擎在进行模板渲染时,还会附带一个Context存放进行模板渲染的变量,在模板中定义的表达式本质上就是从Context中获取对应的变量的值
Today is: 2 November 2016.
1
假设day的值为2016年11月2日,那么渲染结果为:Today is: 2016年11月2日.
。
注意 : 渲染后,模板中span值2 November 2016将被覆盖
123
2,选择(星号)表达式
可以简单理解为内层是对外层对象的引用
Name: Sebastian.
Surname: Pepper.
Nationality: Saturn.
12345
等同于以下方式:
Name: Sebastian.
Surname: Pepper.
Nationality: Saturn.
12345
也可以混用,如下:
Name: Sebastian.
Surname: Pepper.
Nationality: Saturn.
12345
如何没有与th:object结合使用,*{}与${}效果一样,因为其范围自动扩展到context。
12
3,URL表达式
URL表达式指的是把一个有用的上下文或会话信息添加到URL,这个过程经常被叫做URL重写。
Thymeleaf对于URL的处理是通过语法@{…}来处理的
view
view
view12345678910
Thymeleaf支持相对路径和绝对路径
(orderId=${o.id})表示将括号内的内容作为URL参数处理
@{...}表达式中可以通过{orderId}访问Context中的orderId变量
@{/order}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order
12345
4,文字国际化表达式
文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties)
使用Key-Value方式,还可以提供一组参数(可选).
.properties
#{main.title}
#{message.entrycreated(${entryId})}12
模板引用:
...
...
1234
二.thymeleaf-字面值
1.文本文字:’one text’, ‘Another one!’,…
2.文字数量:0, 34, 3.0, 12.3,…
3.布尔型常量:true, false
4.空的文字:null
5.文字标记:one, sometext, main,…
三:thymeleaf-文本处理
1.字符串拼接:+
1
2.文字替换:|The name is ${name}|
1
相比以上两种方式都可以实现字符串合并,但是,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等。
四.表达基本对象
1.#ctx:上下文对象
2.#vars:上下文变量
3.#locale:上下文语言环境
4.#httpServletRequest:(只有在Web上下文)HttpServletRequest对象
5.#httpSession:(只有在Web上下文)HttpSession对象。
例如:
US.
th:text="${#calendars.format(today,'dd MMMM yyyy')}"123
五,表达式预处理
表达式预处理,它被定义在_之间:
#{selection.__${sel.code}__}1
${sel.code}将先被执行,结果(假如是AAA)将被看做表达式的一部分被执行
结果#{为selection.AAA}。
123
六,thymeleaf运算符
在表达式中可以使用各类算术运算符,例如+, -, *, /, %
th:with="isEven=(${prodStat.count} % 2 == 0)"1
逻辑运算符>, <, <=,>=,==,!=都可以使用
需要注意的是使用 > ,<, >=, <=时需要用它的HTML转义符(> gt; < lt; >= ge; gte; <= le; lte; == eq; != ne; neq;)
th:if="${prodStat.count} > 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"12
布尔运算符 and,or
七,thymeleaf循环
数据集合必须是可以遍历的,使用th:each标签:
Product list
NAME
PRICE
IN STOCK
Onions
2.41
yes
1234567891011121314151617181920
被循环渲染的元素中加入th:each标签
th:each="prod : ${prods}"对集合变量prods进行遍历,对象prod在循环体中可通过表达式访问
123
八,thymeleaf条件求值
1,If/Unless
Thymeleaf中使用th:if和th:unless属性进行条件判断
设置标签只有在th:if中条件成立时才显示:
Login1
th:unless与th:if相反,表达式条件不成立时显示内容。
2,Switch
多路选择Switch结构,默认属性default,用*表示
User is an administrator
User is a manager
User is some other thing
12345
3.If-then-else: (if)?(then):else 三元运算符
三元运算控制class属性选择
1
三元运算嵌套
1
还可以省略else部分,当表达式结果为false,返回null,否则返回’alt’
...
123
4.If-then: (if) ? (then) ,省略了else部分,如果条件不成立,返回null
如果第一个表达式的计算结果为null,则取第二个表达式的结果
Age: 27.
123
等效于:
Age: 27.
1
条件表达式嵌套:
Name: Sebastian.
1
九,Thymeleaf-Utilities
Thymeleaf提供了套Utility对象,内置于Context中,可通过#直接访问:
- #dates: java.util的实用方法。对象:日期格式、组件提取等.
- #calendars: 类似于#日期,但对于java.util。日历对象
- #numbers: 格式化数字对象的实用方法。
- #strings:字符串对象的实用方法:包含startsWith,将/附加等。
- #objects: 实用方法的对象。
- #bools: 布尔评价的实用方法。
- #arrays: 数组的实用方法。
- #lists: list集合。
- #sets:set集合。
- #maps: map集合。
- #aggregates: 实用程序方法用于创建聚集在数组或集合.
- #messages: 实用程序方法获取外部信息内部变量表达式,以同样的方式,因为他们将获得使用# {…}语法
- #ids: 实用程序方法来处理可能重复的id属性(例如,由于迭代)。
你可能感兴趣的:(SpringMVC+Thymeleaf 处理表单提交)