首页 » Java » spring mvc 整合 thymeleaf 使用java配置实现

spring mvc 整合 thymeleaf 使用java配置实现

原文 http://blog.csdn.net/qq_36666651/article/details/78688964

2017-12-02 02:00:50阅读(441)

spring mvc 整个 thymeleaf小demo

项目地址:https://github.com/wkcaeser/springThymeleaf
http://download.csdn.net/download/qq_36666651/10141120

先附上依赖(主要为后面几个包):

group 'springThymeleaf'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = 1.8
def tomcatVersion = "9.0.0.M21"
def jstlVersion = "1.2"
def springVersion = "4.3.8.RELEASE"
def mybatisVersion = "3.4.4"
def mybatisSpringVersion = "1.3.1"
def mysqlConnectorVersion = "6.0.6"
def dbcpVersion = "2.1.1"
def log4jVersion = "2.10.0"
def gsonVersion = "2.8.1"
def jjwtVersion = "0.7.0"
def fileupload = "1.3.3"
def commonsIo = "2.2"
repositories {
    mavenCentral()
}
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile "org.apache.tomcat:tomcat-servlet-api:$tomcatVersion"
    compile "org.apache.tomcat:tomcat-jsp-api:$tomcatVersion"
    compile "javax.servlet:jstl:$jstlVersion"
    compile "org.springframework:spring-webmvc:$springVersion"
    compile "org.springframework:spring-jdbc:$springVersion"
    compile "org.mybatis:mybatis:$mybatisVersion"
    compile "org.mybatis:mybatis-spring:$mybatisSpringVersion"
    compile "mysql:mysql-connector-java:$mysqlConnectorVersion"
    compile "org.apache.commons:commons-dbcp2:$dbcpVersion"
    compile "org.apache.logging.log4j:log4j-core:$log4jVersion"
    compile "com.google.code.gson:gson:$gsonVersion"
    compile "io.jsonwebtoken:jjwt:$jjwtVersion"
    compile "commons-io:commons-io:$commonsIo"
    compile "commons-fileupload:commons-fileupload:$fileupload"
    compile "org.apache.tiles:tiles-jsp:3.0.8"
    // https://mvnrepository.com/artifact/javax.validation/validation-api
    compile group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final'
    // https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator
    compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.5.Final'
    // https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.25'
    // https://mvnrepository.com/artifact/javax.mail/javax.mail-api
    compile group: 'javax.mail', name: 'javax.mail-api', version: '1.6.0'
    // https://mvnrepository.com/artifact/org.apache.geronimo.specs/geronimo-activation_1.1_spec
    compile group: 'org.apache.geronimo.specs', name: 'geronimo-activation_1.1_spec', version: '1.1'
    // https://mvnrepository.com/artifact/org.attoparser/attoparser
    compile group: 'org.attoparser', name: 'attoparser', version: '2.0.4.RELEASE'
    // https://mvnrepository.com/artifact/org.unbescape/unbescape
    compile group: 'org.unbescape', name: 'unbescape', version: '1.1.5.RELEASE'
    // https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4
    compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '3.0.9.RELEASE'
}

首先配置模板解析器,代码如下:

//模板解析器
    @Bean
    public ITemplateResolver templateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
//        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
//        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("/WEB-INF/thymeleaf/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);
        return templateResolver;
    }

注释部分也是一种配置方法,这里需要注意的是返回的接口不同的版本有些区别,低版本的为TemplateResolver,最新版本的接口ITemplateResolve。

然后配置模板引擎,代码如下:

//模板引擎
    @Bean
    public TemplateEngine templateEngine(ITemplateResolver templateResolver){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

最后配置Thymeleaf视图解析器:

//thymeleaf视图解析器
    @Bean
    public ViewResolver viewResolver(TemplateEngine templateEngine){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }

配置到这里就完成了。
下面为一个注册小demo案例:
控制器部分:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
@Controller
public class MainController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model){
        model.addAttribute(new User());
        return "home";
    }
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(@Valid User user, Errors errors, Model model){
        model.addAttribute(user);
        System.out.println(user);
        if(errors.hasErrors()){
            return "home";
        }
        return "redirect:/";
    }
}

User实体类:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
    @NotNull
    @Size(min = 5, max = 10)
    private String username;
    @NotNull
    @Size(min = 5, max = 10)
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

html页面部分:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"><!-- 声明Thymeleaf的命名空间 -->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .errorStyle{
            background-color: red;
        }
    </style>
</head>
<body>
<form method="get" th:object="${user}" th:action="register">
    <lable th:class="${#fields.hasErrors('username')}? 'errorStyle'">username:</lable>
    <input type="text" th:field="*{username}" th:class="${#fields.hasErrors('username')}? 'errorStyle'"/><br>
    <lable th:class="${#fields.hasErrors('password')}? 'errorStyle'">username:</lable>
    <input type="text" th:field="*{password}" th:class="${#fields.hasErrors('password')}? 'errorStyle'"/><br>
    <input type="submit" value="register">
</form>
</body>
</html>

th:class会渲染成html标签的class,th:field会渲染成input的value属性,${}为SpEL表达式,*{}为选择表达式,选择表达式的计算方式为基于整个SpELl上下文计算,form标签中的th:object绑定了model中的user对象,那么这个解析就是user的属性。

这个demo的意思就是注册框输入不合法的话会返回注册界面并将注册信息回显,不符合约束要求的字段会被标红。

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹