thymeleaf中遇到的坑

本文介绍了在使用 Thymeleaf 模板引擎时遇到的一些问题和解决方案,包括th:href的字符串拼接,控制器取值,th:src与th:text的使用,以及如何获取后台传来的变量值。还提到了th:action的字符串拼接方法,th:if条件判断,th:each的循环展示,特别是如何限制循环范围,以及在th:each中取List值。此外,文章还讨论了在Thymeleaf中声明片段并传递参数,以及利用th:switch和th:case进行条件判断,以及通过th:datas.format对日期数据进行格式化的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

th:href

<a th:href="@{'/pageController?pageNum='+${pageNum}}" th:text="${pageNum}"></a>

格式:th:href="@{‘字符串’+${model中的nam值}}"。
controller取值

@RequestMapping(value = "/pageController",method = RequestMethod.GET)
    public String pageController(Model model, HttpServletRequest request){
        String pageNum = request.getParameter("pageNum");

th:src

th:src="@{/dist/img/admin.jpg}"   默认路径为static下面的

th:text下字符串拼接
user.name从后台传来的变量,${user.name}获得变量值。文本链接:用“+”符号,也可以用“|”符号。

若user.name=“张三”,解析结果为:Welcome,张三

<span th:text="'Welcome,'+${user.name}">
<span th:text="|Welcome, ${user.name}|">

th:action字符串拼接
若user.userId=1,解析结果为:

<form th:action="@{'/user/'+${user.userId}}"></form>
<form th:action="@{/user/{userId}(userId=${user.userId})}"></form>

th:if根据值判断是否显示标签

<div th:if="${hotel.chainName}!='No chain'">
</div>

这个就是根据hotel.chainName的值是否为’No chain’判断是否显示,如果是的话就不显示,不是的话就显示

th:each从List中取值循环显示

       <tr th:each="hotelinfo : ${hotels}">
          <td th:text="${hotelinfo.hotelId}">
          </td>
          <td th:text="${hotelinfo.hotelTranslatedName}">
          </td>
          <td th:text="${hotelinfo.addressline}">
          </td>
            <td>
                <a th:href="@{'/user/hotelInfo?hotel_id='+ ${hotelinfo.hotelId}}">
                <button type="button" class="btn btn-block btn-info hotel-info-btn">详情</button>
                </a>
            </td>
        </tr>

th:each中取List值如何有个限制如n:m

th:each属性用于迭代循环,语法:th:each="obj,iterStat:${objList}"
迭代对象可以是java.util.List,java.util.Map,数组等;
iterStat称作状态变量,属性有:
    index:当前迭代对象的index(从0开始计算)
    count: 当前迭代对象的index(从1开始计算)
    size:被迭代对象的大小
    current:当前迭代变量
    even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
    first:布尔值,当前循环是否是第一个
    last:布尔值,当前循环是否是最后一个

声明片段的时候 ,可以声明变量参数,在片段中使用变量参数

<span th:text="'Welcome,'+${user.name}">
<span th:text="|Welcome, ${user.name}|">



<form th:action="@{'/user/'+${user.userId}}"></form>
<form th:action="@{/user/{userId}(userId=${user.userId})}"></form>

switch和case条件判断

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

th中datas.format将后端传来的日期数据进行格式化

th:text="${#dates.format(h_order.getoOrdertime(), 'yyyy-MM-dd')
<think>好的,我现在要帮用户解决如何使用Spring Boot、MyBatis和Thymeleaf开发一个商品管理系统,包含数据库设计、添加、删除、查询功能以及三层架构的实现。首先,我需要理清用户的真实需求。用户提到JSP,但引用的资料中用的是Thymeleaf,这可能需要注意。不过根据用户的问题,他们可能混淆了JSP和Thymeleaf,但引用里提到的都是Thymeleaf,所以可能需要确认,但用户的问题明确提到了JSP,但提供的引用都是Thymeleaf,可能用户有误。但根据引用内容,可能用户实际上需要的是Thymeleaf,或者需要调整。但按照用户的问题描述,他们想用JSP,但Spring Boot默认不支持JSP,可能需要额外配置。不过用户提供的引用都是Thymeleaf,可能用户希望用Thymeleaf,或者需要指出这一点。需要处理这个矛盾。 接下来,我需要考虑如何设计数据库。用户需要商品管理,所以需要商品表,可能包含ID、名称、价格、库存、创建时间等字段。然后,三层架构通常包括Controller、Service、DAO层,结合MyBatis的Mapper接口。需要确保结构清晰。 然后,配置Spring Boot项目,添加MyBatis和数据库驱动依赖。如果使用Thymeleaf,需要添加对应的starter,但如果用户坚持用JSP,可能需要配置视图解析器,并添加Tomcat Jasper依赖。但根据引用中的内容,用户之前的项目用的是Thymeleaf,所以可能更合适使用Thymeleaf,但用户的问题提到了JSP,需要明确说明这一点,或者建议使用Thymeleaf,因为更符合Spring Boot的推荐做法,同时引用中的教程也是基于Thymeleaf的。这可能是一个需要用户澄清的地方,但在回答中可能需要指出两者区别,并给出Thymeleaf的方案,同时提到JSP的配置方式。 接着,数据库设计部分,给出商品表的SQL示例,包括字段和注释。然后,创建实体类,对应数据库表。MyBatis的Mapper接口需要定义增删查的方法,并在XML或注解中写SQL。这里可能需要指导用户如何配置MapperScan,如引用3中的示例,使用@MapperScan注解在启动类上,避免每个Mapper接口都加@Mapper。 三层架构的实现:Controller处理请求,调用Service层,Service调用DAO层(Mapper接口)。需要示例代码展示各层的结构,如Controller中的添加、删除、查询方法,Service的实现,以及Mapper接口的定义。 功能实现部分,添加商品需要表单提交,Thymeleaf模板中的表单处理,Controller接收参数并调用Service保存到数据库。删除功能可能需要通过GET或POST请求传递商品ID,执行删除操作。查询功能包括列表展示,可能需要从数据库获取所有商品,并显示在页面上。 测试部分,需要指导用户如何运行应用,访问不同URL进行测试,如/add, /delete, /list等。 最后,相关问题部分,需要生成与商品管理系统开发相关的问题,如分页、事务管理、前端验证、MyBatis优化、项目部署等。 需要注意引用中的内容,如引用3提到的@MapperScan配置,需要在代码示例中体现。引用2提到的用户管理模块的开发流程,可以作为参考,分层架构和模块设计类似。引用4提到的服务提供者的部署可能与当前问题无关,但可能需要忽略。 总结步骤: 1. 项目创建与依赖配置:Spring Boot、MyBatis、MySQL驱动、Thymeleaf(或JSP相关依赖)。 2. 数据库设计:建表语句。 3. 实体类创建:对应商品表。 4. Mapper接口与XML:定义CRUD方法。 5. Service层实现业务逻辑。 6. Controller处理HTTP请求。 7. 视图模板编写(Thymeleaf或JSP)。 8. 配置数据库连接和MyBatis。 9. 测试功能。 需要确保代码示例正确,比如使用@GetMapping和@PostMapping,参数传递,以及Thymeleaf模板中的循环展示商品列表。同时,处理异常情况,如删除时的成功或失败提示。 可能遇到的:依赖配置错误,数据库连接问题,MyBatis的Mapper扫描问题,Thymeleaf模板路径配置等。需要根据引用中的示例,特别是引用3中的@MapperScan配置,确保Mapper接口被正确扫描。 最后,确保回答结构清晰,分步骤说明,代码示例正确,并参考了用户提供的引用内容。</think>### Spring Boot+MyBatis商品管理系统开发教程 #### 一、数据库设计(MySQL示例) ```sql CREATE TABLE product ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL COMMENT '商品名称', price DECIMAL(10,2) NOT NULL COMMENT '商品价格', stock INT DEFAULT 0 COMMENT '库存数量', create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` #### 二、项目结构(三层架构) ``` src/main/java ├── com.example.demo │ ├── controller // 控制层 │ ├── service // 业务层 │ ├── dao // 数据访问层 │ └── entity // 实体类 resources ├── static // 静态资源 ├── templates // 模板文件 └── application.yml // 配置文件 ``` #### 三、核心代码实现 1. **实体类**(对应数据库字段) ```java public class Product { private Integer id; private String name; private BigDecimal price; private Integer stock; private LocalDateTime createTime; // getters/setters省略 } ``` 2. **Mapper接口**(MyBatis数据访问层) ```java @Mapper public interface ProductMapper { @Insert("INSERT INTO product(name, price, stock) VALUES(#{name}, #{price}, #{stock})") int insert(Product product); @Delete("DELETE FROM product WHERE id = #{id}") int deleteById(Integer id); @Select("SELECT * FROM product") List<Product> selectAll(); } ``` 3. **Service层** ```java @Service public class ProductService { @Autowired private ProductMapper productMapper; public void addProduct(Product product) { productMapper.insert(product); } public void deleteProduct(Integer id) { productMapper.deleteById(id); } public List<Product> listProducts() { return productMapper.selectAll(); } } ``` 4. **Controller层** ```java @Controller public class ProductController { @Autowired private ProductService productService; @GetMapping("/products") public String list(Model model) { model.addAttribute("products", productService.listProducts()); return "product/list"; } @PostMapping("/products") public String add(Product product) { productService.addProduct(product); return "redirect:/products"; } @GetMapping("/products/delete/{id}") public String delete(@PathVariable Integer id) { productService.deleteProduct(id); return "redirect:/products"; } } ``` #### 四、Thymeleaf视图示例(resources/templates/product/list.html) ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <form th:action="@{/products}" method="post"> <input type="text" name="name" placeholder="商品名称"> <input type="number" name="price" step="0.01" placeholder="价格"> <input type="number" name="stock" placeholder="库存"> <button type="submit">添加商品</button> </form> <table> <tr th:each="product : ${products}"> <td th:text="${product.name}"></td> <td th:text="${'¥'+#numbers.formatDecimal(product.price,1,2)}"></td> <td> <a th:href="@{/products/delete/}+${product.id}">删除</a> </td> </tr> </table> </body> </html> ``` #### 五、关键配置(application.yml) ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/demo?useSSL=false username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver thymeleaf: cache: false # 开发时关闭缓存 ``` #### 六、启动类配置(引用自[^3]) ```java @SpringBootApplication @MapperScan("com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值