thymeleaf如何实现前后端数据交换(thymeleaf,开发技术)

时间:2024-05-03 01:42:54 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。

1.前端传数据后端接收:

用户在登录界面输入用户名和密码传给后端controller,由后端判断是否正确!

在html界面中要传递的数据name命名,通过表单的提交按钮会传递给响应的controller,在controller将需要的name接收!

<inputtype="text"name="username"class="form-control"th:placeholder="#{login.username}"><inputtype="password"name="password"class="form-control"th:placeholder="#{login.password}">

在controller中使用@RequestParam来对应接收前端要传递的参数,此时参数名严格对应html界面中提交的数据name名称!

@RequestMapping("/user/login")publicStringLogin(@RequestParam("username")Stringusername,@RequestParam("password")Stringpassword,Modelmd){}

此时后端就实现接收前端传递的数据

2.后端对数据判断后返回信息给前端:

controller通过上述参数会接受到html,传递的数据,对数据进行判断。并且通过msg将信息传递回去。

if(!StringUtils.isEmpty(username)&&"123123".equals(password)){return"redirect:/main.html";}else{md.addAttribute("msg","用户名或者密码错误!");return"index";}

html页面使用thymeleaf引擎接收并且显示数据在界面!

<pth:text="${msg}"th:if="${not#strings.isEmpty(msg)}"></p>

完整的两个代码块如下:

<formclass="form-signin"th:action="@{user/login}"> <imgclass="mb-4"th:src="@{/img/bootstrap-solid.svg}"alt=""width="72"height="72"> <h2class="h4mb-3font-weight-normal"th:text="#{login.tip}">Pleasesignin</h2> <pth:text="${msg}"th:if="${not#strings.isEmpty(msg)}"></p> <inputtype="text"name="username"class="form-control"th:placeholder="#{login.username}"required=""autofocus=""> <inputtype="password"name="password"class="form-control"th:placeholder="#{login.password}"required=""> <divclass="checkboxmb-3"> <label><inputtype="checkbox"value="remember-me"th:text="#{login.remember}"></label> </div> <buttonclass="btnbtn-lgbtn-primarybtn-block"type="submit"th:text="#{login.btn}">signin</button> <pclass="mt-5mb-3text-muted">©2022-7-8//21:41</p> <aclass="btnbtn-sm"th:href="@{/index.html(l='zh_CN')}"rel="externalnofollow">中文</a> <aclass="btnbtn-sm"th:href="@{/index.html(l='en_US')}"rel="externalnofollow">English</a> </form>

java

@ControllerpublicclassLoginController{@RequestMapping("/user/login")publicStringLogin(@RequestParam("username")Stringusername,@RequestParam("password")Stringpassword,Modelmd){if(!StringUtils.isEmpty(username)&&"123123".equals(password)){return"redirect:/main.html";}else{md.addAttribute("msg","用户名或者密码错误!");return"index";}}}

thymeleaf如何实现前后端数据交换

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:thymeleaf如何实现前后端数据交换的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:跨域浏览器怎么设置解决前端跨域问题下一篇:

13 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18