Thymleaf中携带数据到前端

本文详细介绍了在Thymeleaf中如何通过ModelAndView和Model两种方式将数据从前端传递到后端,以及如何在前端页面中正确接收并显示这些数据。通过具体的代码示例,展示了不同角色登录后的数据处理流程。

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

Thymleaf中携带数据到前端

一、ModelAndView 的使用

(1)control层(规范性上有点问题,业务处理应该写在service层的)

该方法主要用的是ModelAndView来进行传值,new ModelAndView时可以指定跳转页面,addObject方法将信息封装,return 该对象就可以在对应页面使用对应数据

package com.example.demo.common.control;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.manager.entity.Manager;
import com.example.demo.manager.service.ManagerServiceImp;
import com.example.demo.student.entity.Student;
import com.example.demo.student.service.StudentServiceImp;
import com.example.demo.teacher.entity.Teacher;
import com.example.demo.teacher.service.TeacherServiceImp;

@Controller
public class UserLoginController {

	@Autowired
	StudentServiceImp studentServiceImp;
	@Autowired
	TeacherServiceImp teacherServiceImp;
	@Autowired
	ManagerServiceImp managerServiceImp;

	// 判断登录是否成功
	@RequestMapping(value = "/login" ,method = RequestMethod.POST)
	public ModelAndView login(String username, String password, String userType) {
		
		String type = isType(userType);//判断数据类型
		ModelAndView mavError = new ModelAndView("error");//用于传回数据,并跳转到error.html
		Logger logger = LoggerFactory.getLogger(UserLoginController.class);//日志
		String errorMsg = "登陆失败!";
		mavError.addObject("errorMsg",errorMsg);
		//判断登录角色类型
		if (type == "student") {
            //用于传回数据,并跳转到student.html
			ModelAndView mavStudent = new ModelAndView("student");
			Student student = studentServiceImp.findByname(username);
			if (student == null) {//如果为空直接跳转错误提示页面
				return mavError;//返回ModelAndView对象,跳转到生成对象时指定的跳转页面
			}
			if (student.getStupassword().equals(password.trim())) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("number",student.getStunumber());
				map.put("name",student.getStuname());
				map.put("sex",student.getStusex());
				map.put("major",student.getStumajor());
				map.put("qq",student.getStuqq());
                //将封装信息添加到此对象,用于将信息返回到前端
				mavStudent.addObject("student", map);
				logger.info("msg======>" + student.getStuname() + " " + student.getStupassword());
				return mavStudent;
			}

			logger.info("failmsg======>" + student.getStuname() + " " + student.getStupassword());
			return mavError;
		} else if (type == "teacher") {
             //用于传回数据,并跳转到teacher.html
			ModelAndView mavTeacher = new ModelAndView("teacher");
			Teacher teacher = teacherServiceImp.findByname(username);
			if (teacher == null) {//如果为空直接跳转错误提示页面
				return mavError;
			}
			if (teacher.getTeapassword().equals(password.trim())) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("number",teacher.getTeanumber());
				map.put("name",teacher.getTeaname());
				map.put("sex",teacher.getTeasex());
				map.put("qq",teacher.getTeaqq());
				mavTeacher.addObject("teacher", map);
				logger.info("msg======>" + teacher.getTeaname() + " " + teacher.getTeapassword());
				return mavTeacher;
			}

			logger.info("failmsg======>" + teacher.getTeaname() + " " + teacher.getTeapassword());
			return mavError;
		} else if (type == "manager") {
             //用于传回数据,并跳转到teacher.html
			ModelAndView mavManager = new ModelAndView("mamager");
			Manager mamager = managerServiceImp.findByname(username);
			if (mamager == null) {//如果为空直接跳转错误提示页面
				return mavError;
			}
			if (mamager.getManpassword().equals(password.trim())) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("name",mamager.getManname());
				map.put("sex",mamager.getMansex());
				map.put("qq",mamager.getManqq());
				mavManager.addObject("manager", map);
				logger.info("msg======>" + mamager.getManname() + " " + mamager.getManpassword());
				return mavManager;
			}

			logger.info("failmsg======>" + mamager.getManname() + " " + mamager.getManpassword());
			return mavError;
		} else {
			return mavError;
		}
	}

	// 判断登录角色的类型
	public String isType(String type) {
		if (type == null) {
			return "error";
		}
		if (type.equals("学生")) {
			return "student";
		} else if (type.equals("老师")) {
			return "teacher";
		} else if (type.equals("管理员")) {
			return "manager";
		} else {
			return "error";
		}
	}

}

(2)接受返回数据前端页面。

,添加就可以使用thymleaf模板了

${student.number} ,student 是 后台ModelAndView用addObject时封装的对象。

student.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleleaf.org">
	<head>
		<meta charset="utf-8" />
		<title>student</title>
		<link rel="stylesheet" href="css/student.css" />
	</head>
	<body>
		<div id="BackGround">
			<div id="headimg">
				
				<img src="img/headimg.jpg" />
			</div>
			<div id="usermsg">
				<div id="umsgcontent" >
					<div id="number">
						<div class="nam">学号:</div><div class="con" th:text="${student.number}"></div>
					</div>
					<div id="name">
						<div class="nam">姓名:</div><div class="con" th:text="${student.name}"></div>
					</div>
					<div id="sex">
						<div class="nam">性别:</div><div class="con" th:text="${student.sex}"></div>
					</div>
					<div id="major">
						<div class="nam">专业:</div><div class="con" th:text="${student.major}"></div>
					</div>
					<div id="qq">
						<div class="nam">QQ:</div><div class="con" th:text="${student.qq}"></div>
					</div>
					
				</div>
				<div id="logout">
					退出
				</div>
			</div>
			<div id="feature">
					<div>选择指导老师</div>
					<div>选择课题</div>
					<div>提交课题报告</div>
					<div>提交任务书</div>
					<div>提交作品</div>
					<div>提交论文</div>
			</div>
			<div id="content">
				<div id="conhead">
					<form id="upfileForm" action="upfile" method="post" enctype="multipart/form-data">
						<input type="file" name="file" />
						<input type="submit" value="提交" />
					</form>
				</div>
				<div id="conbody"></div>
			</div>
		</div>
	</body>
	<script type="text/javascript" src="/webjars/jquery/3.3.1-1/jquery.js"></script>
	<script type="text/javascript" src="/js/logout.js"></script>
	<script type="text/javascript" src="/js/upload.js"></script>
</html>

二、Model的使用

(1)control层

package com.example.demo.teacher.control;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test")
public class TestThymleaf {
	@RequestMapping("/login")
	public String login(Model model,String name,String password){
		if(password.equals("1234") && name.equals("李明")) {
			model.addAttribute("msg", name+"登录成功");
		}
		return "msg";
	}
}

(2)发送数据的前端页面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="/test/login" method="post">
	账号:<input name="name" id="name" type="text"><br/>
	密码:<input name="password" id="password" type="password"><br/>
	<input type="submit" value="提交">
</form>
</body>
</html>

(3)接受返回数据的前端

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleleaf.org">
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
   <div class="con" th:text="${msg}">失败</div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值