今天小编给大家分享一下thymeleaf如何实现前后端数据交换的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。
用户在登录界面输入用户名和密码传给后端controller,由后端判断是否正确!
在html界面中要传递的数据name命名,通过表单的提交按钮会传递给响应的controller,在controller将需要的name接收!
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}">
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}">
在controller中使用@RequestParam来对应接收前端要传递的参数,此时参数名严格对应html界面中提交的数据name名称!
@RequestMapping("/user/login")
public String Login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model md){
}
此时后端就实现接收前端传递的数据
controller通过上述参数会接受到html,传递的数据,对数据进行判断。并且通过msg将信息传递回去。
if(!StringUtils.isEmpty(username)&& "123123".equals(password)){
return "redirect:/main.html";
}else{
md.addAttribute("msg","用户名或者密码错误!");
return "index";
}
html页面使用thymeleaf引擎接收并且显示数据在界面!
<p th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
完整的两个代码块如下:
<form class="form-signin" th:action="@{user/login}">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h2 class="h4 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h2>
<p th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="" >
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="" >
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" th:text="#{login.remember}">
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">sign in</button>
<p class="mt-5 mb-3 text-muted">© 2022-7-8//21:41</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}" rel="external nofollow" >中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}" rel="external nofollow" >English</a>
</form>
java
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String Login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model md){
if(!StringUtils.isEmpty(username)&& "123123".equals(password)){
return "redirect:/main.html";
}else{
md.addAttribute("msg","用户名或者密码错误!");
return "index";
}
}
}
以上就是“thymeleaf如何实现前后端数据交换”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。