spring-boot(thymeleaf)中th:field和th:value的区别

                               spring-boot中th:field和th:value的区别

一:常用th:标签简介:

我们再用spring-boot框架的时候,可能不会采用我们以往用的jsp页面的方式,而是通过采用thymeleaf渲染的方式进行

前后台数据的交互。常用的标签有

th:href,用法:th:href="/brand/selectbrand",(用来指明要要跳转的链接)

th:object,用法:th:object="${brand}",(用来接受后台传过来的对象)

样例:

    <form class="form form-horizontal" id="form-admin-add" action="#" th:action="@{/brand/updatebyid}" th:object="${brand}">

th:field,用法:th:field="*{name}",(用来绑定后台对象和表单数据)

th:value,用法:th:value="${brand.name}",(用对象对name值替换value属性)

总结:th:field

样例:

<form class="form form-horizontal" id="form-admin-add" action="#" th:action="@{/brand/updatebyid}" th:object="${brand}">

        <input type="text" class="input-text" value="" th:value="*{id}" name="id" />

        <input type="text" class="input-text"  value="" th:field="*{code}" placeholder="" id="code"/>

th:field和th:value的小结:

thymeleaf里的th:field等同于th:nameth:value,浏览器在解析th:field的时候,会解析成name="${th:field}"的值。

然后后台就可以接收到从前台传过来的值。而th:value可以接受到后台的的值,后台则可以根据name获取到前台的值。

th:field和th:value都有两种从后台接受值的方式:1、${obj.name} 2、*{name}。需要注意的是,th:field需要有th:object

指定前台传过来的参数,否则浏览器在解析的时候会出现错误。

th:each,用法:th:each="brand:${pageInfo.list}",(后台把对象放在了pageinfo的分页插件的List里,然后用th:each遍

历后台传过来的对象)。

样例:

<tr class="text-c" th:each="order:${pageInfo.list}">
     <td th:text="${order.id}"></td>
     <td th:text="${order.dicMethodDescription}"></td>
     <td th:text="${order.productBrandName}"></td>
     <td th:text="${order.productModelName}"></td>

th:if,用法:th:if="${pageInfo.list.size() == 0}",(判断传过来的对象是否为空,如果为空,则执行...)

th:unless,用法:th:unless="${pageInfo.list.size() == 0}"(判断传过来的对象是否为空,如果不为空,则执行...)

标签只有在th:if中条件成立时才显示,th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

样例:

<td th:if="${order.productStateName}==部分退款" th:text="交易成功" class="validate"></td>
<td th:unless="${order.productStateName}==部分退款" th:text="${order.productStateName}"></td>

三:thymeleaf实现动态访问controller:

我们一般链接地址都是写死了的,这样其实间接的降低了系统的灵活性,我们可以在th:href的链接里添加参数,这样

就可以动态的访问controller,举个栗子:

//static页面层:

<a title="编辑信息" href="javascript:;" th:οnclick="'javascript:brand_edit(\'编辑品牌信息\',\'/brand'+@{/updatebyid}+'/'+${brand.id}+'\',800,400)'" class="ml-5" style="text-decoration:none"><i class="Hui-iconfont">&#xe6df;</i></a>

//controller层:

    //根据品牌名更改品牌的名称和编号信息
    @RequestMapping(value = "/updatebyid/{id}")
    public String updatebyidBefore(Model model, @ModelAttribute(value = "brand") ProductBrand brand,
            @PathVariable("id") Long id) {
        // 根据ID查询用户 和对应的角色
        brand = operatebrand.selectByPrimaryKey(id);
        // 查询对应用户的角色
        model.addAttribute("brand", brand);
        return "maintenance-operate/editor-brand";
    }

四:对数据库的数据灵活筛选:

一般我们在访问数据库的时候,可能在数据库中查询的时候写出我们固定需要的值,比如我们想要查的字段需要在某一

范围内,例如需要查出状态表的状态在(1,3,5,7)状态里。这些状态可以在状态的字典表里查出。

你可能想到会这样写:select id ,name,code from table where state in(1,3,5,7)。但是别人也想查对应的字段,但是筛选

的状态不同,比如他筛选的是2,4,6,8。这时候他可能又需要写一套select语句。则这样也失去的代码灵活性。

我们可以传一个状态数组进去,这时候就会根据状态数组的值来进行筛选。我们来看看实现。

ServiceImpl层:

List<OrderInfoForm> result = null;
result=orderMapper.selectOrdersByStatesSelective(order, new Integer[] {3,4,6,7,8});

dao层:

List<OrderInfoForm> selectOrdersByStatesSelective(@Param(value="order")Order order,
    @Param(value="states")Integer[] states);

mapper层:

<select id="selectOrdersByStatesSelective" resultMap="AllResultMap" >
    select 
    <include refid="All_Column_List" />
    from order_list
	LEFT JOIN product_method ON product_method.`code` = order_list.purchase_method
	LEFT JOIN product_color ON product_color.`code` = order_list.color
	LEFT JOIN product_guarantee ON product_guarantee.`code` = order_list.guarantee
	LEFT JOIN product_info ON order_list.product_id = product_info.id
	LEFT JOIN product_model ON product_info.model = product_model.`code`
	LEFT JOIN product_standard ON product_info.standard = product_standard.`code`
	LEFT JOIN product_state ON product_state.`code` = order_list.order_state
	LEFT JOIN product_apperance ON product_apperance.`code` = order_list.apperance
	LEFT JOIN product_brand ON product_brand.`code` = product_info.brand
    <where>
    	<if test="order.orderNum != null " >
	        order_num like "%"#{order.orderNum,jdbcType=VARCHAR}"%"
	    </if>
	    <if test="order.operator != null " >
	        and operator like "%"#{order.operator,jdbcType=VARCHAR}"%"
	    </if>
	    <if test="order.purchaseTime != null" >
	        and purchase_time = #{order.purchaseTime,jdbcType=DATE}
	    </if>
	    <if test="order.orderState != null" >
	        and order_state = #{order.orderState,jdbcType=VARCHAR}
	    </if>
	    <if test="order.serialNum != null" >
	        and serial_num like "%"#{order.serialNum,jdbcType=VARCHAR}"%"
	    </if>
	    
		<if test="states != null and states.length >0">
			<foreach collection="states" item="state" separator="," open=" and order_state in (" close=")">
				#{state,jdbcType=BIGINT}
			</foreach>
		</if>
	</where>
  </select>

注意最后的test的条件:

解释一下各个的参数:

1、foreach collection="传过来的状态数组名称"

2、item="state"用于遍历每个状态

3、separator=",":用于分割各个状态

4、open=" 用于在对应位置添加双引号

5、and order_state in (" close=")"用于在对应结束位置添加双引号

以下是一个简单的球队信息管理模块的代码示例: 1. 实体类: 球队信息实体类 Team.java ``` public class Team { private Integer id; private String name; // 省略getter和setter方法 } ``` 球员信息实体类 Player.java ``` public class Player { private Integer id; private String name; private Integer age; private String position; private String photoPath; private Team team; // 球队信息 // 省略getter和setter方法 } ``` 2. DAO层: 球队信息DAO接口 TeamMapper.java ``` public interface TeamMapper { List<Team> getAllTeams(); Team getTeamById(Integer id); void addTeam(Team team); void updateTeam(Team team); void deleteTeam(Integer id); } ``` 球员信息DAO接口 PlayerMapper.java ``` public interface PlayerMapper { List<Player> getAllPlayers(); List<Player> getPlayersByTeamName(String teamName); List<Player> getPlayersByName(String name); Player getPlayerById(Integer id); void addPlayer(Player player); void updatePlayer(Player player); void deletePlayer(Integer id); } ``` 3. Service层: 球队信息Service TeamService.java ``` @Service public class TeamService { @Autowired private TeamMapper teamMapper; public List<Team> getAllTeams() { return teamMapper.getAllTeams(); } public Team getTeamById(Integer id) { return teamMapper.getTeamById(id); } public void addTeam(Team team) { teamMapper.addTeam(team); } public void updateTeam(Team team) { teamMapper.updateTeam(team); } public void deleteTeam(Integer id) { teamMapper.deleteTeam(id); } } ``` 球员信息Service PlayerService.java ``` @Service public class PlayerService { @Autowired private PlayerMapper playerMapper; public List<Player> getAllPlayers() { return playerMapper.getAllPlayers(); } public List<Player> getPlayersByTeamName(String teamName) { return playerMapper.getPlayersByTeamName(teamName); } public List<Player> getPlayersByName(String name) { return playerMapper.getPlayersByName(name); } public Player getPlayerById(Integer id) { return playerMapper.getPlayerById(id); } public void addPlayer(Player player) { playerMapper.addPlayer(player); } public void updatePlayer(Player player) { playerMapper.updatePlayer(player); } public void deletePlayer(Integer id) { playerMapper.deletePlayer(id); } } ``` 4. Controller层: 球队信息Controller TeamController.java ``` @Controller @RequestMapping("/team") public class TeamController { @Autowired private TeamService teamService; @GetMapping("/list") public String list(Model model) { List<Team> teams = teamService.getAllTeams(); model.addAttribute("teams", teams); return "team/list"; } @GetMapping("/add") public String add(Model model) { model.addAttribute("team", new Team()); return "team/edit"; } @GetMapping("/edit/{id}") public String edit(@PathVariable Integer id, Model model) { Team team = teamService.getTeamById(id); model.addAttribute("team", team); return "team/edit"; } @PostMapping("/save") public String save(Team team) { if (team.getId() == null) { teamService.addTeam(team); } else { teamService.updateTeam(team); } return "redirect:/team/list"; } @GetMapping("/delete/{id}") public String delete(@PathVariable Integer id) { teamService.deleteTeam(id); return "redirect:/team/list"; } } ``` 球员信息Controller PlayerController.java ``` @Controller @RequestMapping("/player") public class PlayerController { @Autowired private PlayerService playerService; @GetMapping("/list") public String list(Model model) { List<Player> players = playerService.getAllPlayers(); model.addAttribute("players", players); return "player/list"; } @GetMapping("/add") public String add(Model model) { List<Team> teams = teamService.getAllTeams(); model.addAttribute("player", new Player()); model.addAttribute("teams", teams); return "player/edit"; } @GetMapping("/edit/{id}") public String edit(@PathVariable Integer id, Model model) { List<Team> teams = teamService.getAllTeams(); Player player = playerService.getPlayerById(id); model.addAttribute("player", player); model.addAttribute("teams", teams); return "player/edit"; } @PostMapping("/save") public String save(Player player, @RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { String photoPath = "upload/" + file.getOriginalFilename(); File dest = new File(photoPath); file.transferTo(dest); player.setPhotoPath(photoPath); } if (player.getId() == null) { playerService.addPlayer(player); } else { playerService.updatePlayer(player); } return "redirect:/player/list"; } @GetMapping("/delete/{id}") public String delete(@PathVariable Integer id) { playerService.deletePlayer(id); return "redirect:/player/list"; } } ``` 5. Thymeleaf视图: 球队信息list.html ``` <table> <thead> <tr> <th>ID</th> <th>名称</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="team : ${teams}"> <td th:text="${team.id}"></td> <td th:text="${team.name}"></td> <td> <a th:href="@{/team/edit/{id}(id=${team.id})}">编辑</a> <a th:href="@{/team/delete/{id}(id=${team.id})}">删除</a> </td> </tr> </tbody> </table> <a th:href="@{/team/add}">添加球队</a> ``` 球队信息edit.html ``` <form method="post" enctype="multipart/form-data" th:object="${team}" th:action="@{/team/save}"> <input type="hidden" th:field="*{id}"> <input type="text" th:field="*{name}"> <button type="submit">保存</button> </form> ``` 球员信息list.html ``` <table> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>位置</th> <th>球队</th> <th>照片</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="player : ${players}"> <td th:text="${player.id}"></td> <td th:text="${player.name}"></td> <td th:text="${player.age}"></td> <td th:text="${player.position}"></td> <td th:text="${player.team.name}"></td> <td><img th:src="@{|/${player.photoPath}|}" width="50" height="50"/></td> <td> <a th:href="@{/player/edit/{id}(id=${player.id})}">编辑</a> <a th:href="@{/player/delete/{id}(id=${player.id})}">删除</a> </td> </tr> </tbody> </table> <a th:href="@{/player/add}">添加球员</a> ``` 球员信息edit.html ``` <form method="post" enctype="multipart/form-data" th:object="${player}" th:action="@{/player/save}"> <input type="hidden" th:field="*{id}"> <input type="text" th:field="*{name}"> <input type="text" th:field="*{age}"> <input type="text" th:field="*{position}"> <select th:field="*{team.id}"> <option th:each="team : ${teams}" th:value="${team.id}" th:text="${team.name}"></option> </select> <input type="file" name="file"> <button type="submit">保存</button> </form> ``` 以上是一个简单的球队信息管理模块的代码示例,具体的实现过程需要根据实际情况进行具体的编写和调试。同时,为了提高开发效率,可以使用一些开源组件,比如MyBatis Plus、EasyExcel等,来简化开发流程。
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值