zoukankan      html  css  js  c++  java
  • springboot的Web开发及thymeleaf

    springboot的Web开发

    web开发我们需要导入的依赖有: thymeleaf , Spring Web, mysql Driver, jdbc API, mybatis

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--数据库等依赖: 略-->
    

    服务器配置

    服务器配置也就是配置我们的servlet

    例如: 修改端口号 , 默认的端口号是8080

    server.port=8888
    

    配置上下文路径

    springboot服务器启动后, 默认的路径是localhost:8080/

    我们可以这样配置:

    server.servlet.context-path=/MyWeb
    

    这样我们的默认路径就是 localhost:8080/MyWeb/

    默认视图跳转

    thymeleaf文档[跳转]

    thymeleaf模板引擎的默认资源路径是classpath:/templates/resource/templates/

    当然我们也可以手动进行配置, 如下:

    # 配置前缀, 默认是`classpath:/templates
    spring.thymeleaf.prefix=classpath:/templates/pages/
    # 配置后缀
    spring.thymeleaf.suffix=.html
    

    这样我们配置好了视图的跳转

    例如我们有个controller, controller中有如下方法

    @Controller
    @RequestMapping("/goods")
    public class GoodsController {
        @RequestMapping("/doGoodsUI") 
        public String doGoodsUI(Model model) {
            // 1. 将此view返回给前端控制器
            // 2. 前端控制器会调用师徒解析器对view进行解析, 添加前缀和后缀
            // /templates/pages/goods.html
            // 3. 最后由DespatcherServlert将页面相应到客户端
            return "goods"; // view name
        }
    }
    

    那么我们访问:localhost:8080/goods/doGoodsUI 就会跳转到 resource/templates/pages/goods.html

    配置文件参考

    # server
    server.port=80
    # datasource
    spring.datasource.url=jdbc:mysql://localhost:3306/dbactivity?serverTimezone=GMT%2B8&characterEncoding=utf8
    spring.datasource.username=root
    spring.datasource.password=123456
    # spring mybatis
    mybatis.mapper-locations=classpath:/mapper/*/*.xml
    # spring
    spring.thymeleaf.prefix=classpath:/templates/pages/
    spring.thymeleaf.suffix=.html
    # log
    logging.level.com.cy=debug
    

    视图展示数据(thymeleaf)

    thymeleaf文档[跳转]

    视图展示数据我们依然可以使用ModelMap后者Model把数据传到前端页面

    例如: 查询所有的商品

    @RequestMapping("/doGoodsUI") 
    
    	@Autowired
    	private GoodsService goodsService;
    
    	public String doGoodsUI(Model model) {
    		// 假设goodsService中的findObjects()方法是查询到的所有商品, 我们把它传入model对象中
            // model会把数据发送到前端页面
    		model.addAttribute("list", goodsService.findObjects());
    		return "goods"; 
    	}
    

    现在我们在resource/templates/pages/下创建一个html: goods.html

    我已经配置了 spring.thymeleaf.prefix=classpath:/templates/pages/, 所以我把html文件放到了resource/templates/pages/下, 在创建前请确定你配置的路径

    我们需要添加xml命名空间, 新版本加不加都无所谓, 老版本可能无法使用th开头的标签属性

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        
    </body>
    

    这样就创建好了, 我们需要在body中写入内容

    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>remark</th>
                <th>createdTime</th>
            </tr>
        </thead>
        <tbody>
            <!-- 我们需要遍历controller传过来的集合 -->
        	<tr th:each="g : ${list}">
                <td th:text="${g.id}">1</td>
                <td th:text="${g.name}">MySQL</td>
                <td th:text="${g.remark}">oranges</td>
                <!--thymeleaf日期格式化功能-->
                <td th:text="${#calendars.format(g.createdTime, 'yyyy-MM-dd HH:mm')}">2020-01-01</td>
            </tr>
        </tbody>
    </table>
    

    进行测试测试

    浏览器输入:localhost:8080/goods/doGoodsUI

    可以看到数据库中的数据已经显示到了表格中

    扩展: 日期格式化

    @DateTimeFormat(pattern = "yyy-MM-dd")

    此注解用于描述属性或set方法, 告诉spring mvc按指定格式接收数据, 默认格式为yyyy/MM/dd HH:mm:ss

    例如:

    public class Activity {
    	private Long id;
    	private String title;
    	// 次注解用于描述属性或set方法, 告诉spring mvc按指定格式接收数据
    	@DateTimeFormat(pattern = "yyy-MM-dd")
        private Date startTime;
    	@DateTimeFormat(pattern = "yyy-MM-dd")
        private Date endTime;
    }
    

    前端显示指定日期的格式, thymeleaf支持日期格式化:

    格式: ${#calendars.format(日期对象,格式)}

    格式: 年-月-日 时:分:秒 -> yyyy-MM-dd HH:mm:ss

    Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>
    

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")

    此注解用来告诉日期类型数据转为json字符串的时候, 日期指定的格式, 对应其get方法

    pattern: 格式

    timezone: 时区, 必须设置, 否则可能差8小时

    Thymeleaf数据回显

    input回填

    <div class="form-group">
        <label class="col-sm-1 control-label">用户名:</label>
        <div class="col-sm-3">
            <input id="username" name="username" th:value="${user.username}" class="form-control" type="text">
        </div>  
    </div>
    

    单选回填

    <div class="form-group">
        <label class="col-sm-1 col-sm-offset-2 control-label">性别 :</label>
        <div class="col-sm-3">
            <label class="radio-inline" th:each="sex:${sexList}">
                <input type="radio" id="sex" name="sex" th:value="${sex.value}" th:text="${sex.name}" th:attr="checked=${user.sex == sex.value?true:false}" />
            </label>
        </div>
    </div>
    

    时间框回填

    <div class="form-group">
        <label class="col-sm-1 control-label">出生日期:</label>
        <div class="col-sm-3">
            <input type="text" class="laydate-icon layer-date form-control" id="birthday" name="birthday" th:value="${user.birthday}==null?null:${#dates.format(user.birthday,'yyyy-MM-dd')}" οnclick="laydate({istime: true, format: 'YYYY-MM-DD'})" style="background-color: #fff;" readonly="readonly" />
        </div>
    </div>
    

    下拉回填

    <div class="form-group">
        <label class="col-sm-1 col-sm-offset-2 control-label">职业:</label>
        <div class="col-sm-3">
            <select data-placeholder="--选择类别--" name="profession" id="profession" class="form-control chosen-select" tabindex="2" required>
                <option value="">--选择类别--</option>
                <option th:selected="${user.profession eq profession.value}" th:each="profession:${professionTypeList}" th:value="${profession.value}" th:text="${profession.name}"></option>
            </select>
        </div>
    </div>
    

    textarea数据回显

    thymeleaf的textarea数据回显用th:text,th:value不能回显

    集合的非空判断

    th:if="${not #lists.isEmpty(自定义集合)}"
    

    字符串拼接

    <span th:text="|Welcome to HeBei, ${user.name}!|">
    //这实际上相当于:
    <span th:text="'Welcome to HeBei, ' + ${user.name} + '!'">
    //文字替换可以与其他类型的表达相结合:
    <span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">
    

    小数(四舍五入)

    //显示1.24
    th:text="${#numbers.formatDecimal(1.235, 1, 2)}"
    

    a标签-超链接

    <a th:href="@{/user/doUpdate/(id=${companyUser.id},username=${user.username})}">view</a>
    <a th:href="@{/user/{user.id}/getUserByUserName>view</a>
    

    三元运算符判断

    th:text="'Execution mode is ' + ( ('0'!='0')? 'Development' : 'Production')"
    
  • 相关阅读:
    [置顶] cocos2dx sqllite 增删查改等操作
    BZOJ 2933([Poi1999]地图-区间Dp)
    java使用batik转换svg文件
    算法小题目小结。。。
    [置顶] shell变量赋值-linux
    高级IO复用应用:聊天室程序
    NSUserDefaults的使用
    动态链接库与静态链接库的区别
    阐明iOS证书和provision文件
    Hyperic Agent 安装配置报
  • 原文地址:https://www.cnblogs.com/zpKang/p/13232264.html
Copyright © 2011-2022 走看看