Thymeleaf的普通表单提交与AJAX提交

为Java实体对象添加后台校验注解:
	//String类型的校验: @NotEmpty -- 不能为空  max=16 -- 最大长度为16
	@NotEmpty(message = "songName不能为空")
    @Size(max = 16 , message = "songName长度不能超过16")
    private String songName;

    @NotEmpty(message = "singer不能为空")
    @Size(max = 12 , message = "singer长度不能超过12")
    private String singer;
	
	//int类型的校验: @NotNull -- 不能为空 min=1 max=127 -- 值在1~127之间
	@Range(min = 1, max = 127, message = "age的范围在1~127")
    @NotNull(message = "age不能为空")
    private Integer age;
一般这些校验都不会用到,因为更多的时候我们都是在前端进行校验的。这里只是进行示范。
普通表单的提交与SpringMVC没多大区别,前端代码如下(insertSong.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>insert Song</title>
</head>
<body>
<br><br>
<div th:text="${hintMessage}">信息提示!!!!</div>
<br>
<div th:errors="${song.songName}"></div>
<div th:errors="${song.singer}"></div>
<br>
<form id="iform" th:action="@{/song/save.action}" th:method="post" th:object="${song}">
    <table border="1">
        <tr>
            <th>歌曲名</th>
            <th>演唱者</th>
            <th>Action</th>
        </tr>
        <tr>
            <!--th:field="*{songName}" 加上这个属性时报错-->
            <td><input type="text" name="songName"/></td>
            <td><input type="text" name="singer"/></td>
            <td><input type="submit" value="添加"/></td>
        </tr>
    </table>
</form>
<hr>
</body>
</html>
后台代码:
@PostMapping("/song/save.action")
    public ModelAndView insertSong(@Valid Song song, BindingResult result){
		//@Valid注解启动后台校验,
		ModelAndView modelAndView = new ModelAndView();

        System.out.println("歌手名称:"+ song.getSinger());

        if(result.hasErrors()){
            modelAndView.addObject("hintMessage", "出错啦!");
        }else{
            String songName = song.getSongName();
            Song dataSong = songService.findSongByName(songName);
            if(dataSong != null){
                modelAndView.addObject("hintMessage", "数据库已有该条记录!");
            }else{
                modelAndView.addObject("hintMessage", "提交成功!");
                songService.insertSong(song);
            }

        }

        modelAndView.setViewName("/success");

        return modelAndView;

    }
当然,要有一个方法跳转到指定的页面:
@GetMapping("/song/add")
    public ModelAndView addSong(){

        ModelAndView modelAndView = new ModelAndView();


        Song song = new Song(0, null, null);
        modelAndView.addObject("song", song);
        modelAndView.addObject("hintMessage", "初始化成功!");
        modelAndView.setViewName("/insertSong");

        return modelAndView;
    }
因为insertSong.html定义了如下代码:
<div th:text="${hintMessage}">信息提示!!!!</div>
	<div th:errors="${song.songName}"></div>
	<div th:errors="${song.singer}"></div>
所以要进行初始化,否则会报错:
	Song song = new Song(0, null, null);
    modelAndView.addObject("song", song);
    modelAndView.addObject("hintMessage", "初始化成功!");
如果不要后台校验,就跟平常的SpringMVC代码一样,只需要将url改成thymeleaf格式的就行了(th:action="@{/song/save.action}"),这里就不进行演示了。
下面进行Thymeleaf的ajax提交的演示:
Thymeleaf中使用javaS基本格式为:
	<script type="text/javascript" th:inline="javascript">
		 /*<![CDATA[*/
			....(这里写js代码)
		 /*]]>*/
	</script>
前端代码如下(ajaxTest.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Ajax Test</title>

    <script src="../static/jquery/jquery-1.7.2.js" type="text/javascript" th:src="@{/jquery/jquery-1.7.2.js}"></script>
    <script type="text/javascript" th:inline="javascript">

        /*<![CDATA[*/
            function ajaxSubmit(){
                var songName = $("#songName").val();
                var singer = $("#singer").val();

                $.ajax({
                    url: [[@{/song/ajaxTest.action}]],
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify({songName : songName,singer : singer}),
                    async: true,
                    success: function(data){
                        if(data != null){
                            alert('flag : ' + data.flag + " , hintMessage : " + data.hintMessage);
                        }
                    }
                });
            }

        /*]]>*/


    </script>
</head>
<body>
    <input type="text" name="songName" id="songName">
    <input type="text" name="singer" id="singer">
    <button onclick="ajaxSubmit()">提交</button>

</body>
</html>
要注意的地方就是ajax的url的格式:url: [[@{/song/ajaxTest.action}]],将url包含在[[url]]中。
后台代码,与普通的SpringMVC基本没有区别:
@GetMapping("/song/ajax")
public String toAjax(){
	return "/ajaxTest";
}
    
@PostMapping("/song/ajaxTest.action")
public void ajaxTest(@RequestBody Song song, HttpServletResponse resp)throws Exception{

	String songName = song.getSongName();
    Song dataSong = songService.findSongByName(songName);

    String flagMessage = "success";
    String hintMessage="数据添加成功!!!";
    if(dataSong != null){
	    flagMessage = "fail";
        hintMessage = "数据库已有该数据!!!";
    }else{
        songService.insertSong(song);
    }

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("flag",flagMessage);
    jsonObject.put("hintMessage",hintMessage);
    System.out.println(jsonObject.toJSONString());
    resp.setContentType("text/html;charset=UTF-8");
    resp.getWriter().println(jsonObject.toJSONString());
    resp.getWriter().close();

    }
目录结构如下:
![这里写图片描述](https://img-blog.csdn.net/20180702193541231?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1pIQU5HTElfV09SQg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
下面是几个需要注意的地方:
1.如果希望方法返回值是String时是跳转到指定页面(xxx.html),Controller层应该使用@Controller注解,而不是@RestController
2.springboot默认的目录是/resources/static,所以在使用具体的目录时只需要以staic的下一个子目录开始即可。如:/resources/static/jquery/jquery-1.7.2.js,在使用Thymeleaf表示路径地址时的格式: th:src="@{/jquery/jquery-1.7.2.js}"
3.如果直接通过url就可以访问到index.html,只需要把index.html放在static目录下即可,即:/static/index.html

如果大家对Thymeleaf的配置不太清楚的话,可以看看我的上一篇博客(SpringCloud与Thymeleaf整合demo),Thymeleaf的表单提交的实现基本就是这样,希望对大家有所帮助。
同时发现了一个问题: 当我使用 th:field 这个属性时,Thymeleaf直接抛异常,暂时也没找到解决方法,如果有知道什么原因的朋友求告知。

关于我


    可以扫描关注下面的公众号(公众号:猿类进化论)
在这里插入图片描述

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Thymeleaf是一种Java模板引擎,而Bootstrap是一种前端框架,可以使Web开发更加高效。要使用Thymeleaf和Bootstrap5发送Ajax请求,我们可以使用jQuery的Ajax函数来实现。 首先,我们需要在HTML文件中引入jQuery库和Bootstrap样式库。然后,在需要发送Ajax请求的按钮或链接上添加一个ID或特定的类,并使用JavaScript代码将其与Ajax事件绑定。在Ajax事件中,我们可以指定请求类型、URL、数据等,还可以定义成功或失败时要执行的代码。 对于Thymeleaf,我们可以使用其内置的表达式语言将数据绑定到HTML元素中,例如将表格中的数据使用循环结构进行填充,或将表单的数据传递到控制器中。 具体而言,我们可以使用如下代码来实现Thymeleaf Bootstrap5发送Ajax请求: HTML代码: ```html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Thymeleaf Bootstrap5 Ajax Request Demo</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <h2>Thymeleaf Bootstrap5 Ajax Request Demo</h2> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr th:each="user: ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td> <a href="javascript:void(0)" class="btn btn-info btn-xs edit-btn" th:data-id="${user.id}">Edit</a> <a href="javascript:void(0)" class="btn btn-danger btn-xs delete-btn" th:data-id="${user.id}">Delete</a> </td> </tr> </tbody> </table> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script> <script> $(document).ready(function () { // Edit button click event $('.edit-btn').click(function () { var id = $(this).data('id'); $.ajax({ type: "GET", url: "/user/" + id, success: function (data) { $('#id').val(data.id); $('#name').val(data.name); $('#age').val(data.age); $('#editModal').modal('show'); }, error: function (jqXHR, textStatus, errorThrown) { alert('Error getting user by ID'); } }); }); // Delete button click event $('.delete-btn').click(function () { var id = $(this).data('id'); if (confirm('Are you sure you want to delete this user?')) { $.ajax({ type: "DELETE", url: "/user/" + id, success: function (data) { window.location.reload(); }, error: function (jqXHR, textStatus, errorThrown) { alert('Error deleting user'); } }); } }); }); </script> </body> </html> ``` 这里我们为Edit按钮和Delete按钮分别添加了edit-btn和delete-btn类,并为其设置了数据属性th:data-id,用于记录需要编辑或删除的用户ID。在JavaScript代码中,我们使用jQuery的Ajax函数分别为这两个按钮绑定了点击事件,并在事件中分别发送了GET和DELETE类型的Ajax请求,获取或删除对应的用户数据。 需要注意的是,我们使用了Thymeleaf的内置表达式语言将数据渲染到了HTML中,并在用户单击Edit按钮时使用了Bootstrap的Modal组件来显示编辑面板。此外,我们还为删除按钮添加了一个确认框,以防止误操作。 总的来说,使用Thymeleaf Bootstrap5发送Ajax请求非常方便,能够大大提高Web开发效率和用户体验。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值