在html的js中获得后端request/session/model中的值

先看需求:

需要用户登录成功之后的购物车数据来初始化主页面购物车的商品数量,而在没有登录时,主页面的购物车不显示数量

没有登录

成功登录

那么这里需要在前端读到session/request/model任意一个中的值,就可以在js中做页面初始化 

前端时间用的都是jsp做前端,可以直接获得session和request的值,但是现在的前端是html中引入了thymeleaf模板,而在htnl的

<script>

……

</script>

中又没法直接获得request/session的值,于是一度陷入困境,好在看到这篇帖子

 Html中获取session中的值(实现登录后显示欢迎xxx)

其中有些细节说的不是很清楚,于是在此整理自己的思路

1.首先,没法在前端直接获取session/request/model中的值,但是,springboot支持的前端模板thymeleaf的标签语法支持直接从model中取值(或许也支持直接从request或session中直接取值,各位可以试试),例如

后端控制层写入了如下数据

那么在前端的html中,就可以使用如下方式,得到存在model中的字符串

 注意,这里没有使用的是span标签的,th:text属性来获取后端数据,这点至关重要,后面会详说

这是我们spingboot项目,前端页面获取值,最常规方法,

那么,现在就可以开始在js中获取这个值了

首先认识一些使用到的方法

document.getElementById("aa")

定位到当前页面,id值为 “aa” 的标签

innerHTML

innerHTML在JS是双向功能:获取对象的内容 或 向对象插入内容

我们可以通过 document.getElementById(‘aa’).innerHTML 来获取id为aa的对象的内嵌内容;


也可以对某对象插入内容,如 document.getElementById(‘abc’).innerHTML=’这是被插入的内容’;
这样就能向id为abc的对象插入内容。

那么,通过

document.getElementById("user").innerHTML

就可以获得html中的span标签中的值,但是innerHTML只能获取,两个标签中的值,例如

<span id=“user”>这是数据</span>

而document.getElementById("user").innerHTML就能获取到

这就是数据

这段文字

只要这里能获取到,那么我们就能在js中利用这个数据做别的处理,至此我们实现了需求,在html中获取后端model中的数据

那么还有些额外内容,

如果把获取到的值利用sessionStorage.setItem存入对应的键名,就能在别的页面也使用这个数据,

sessionStorage.setItem('USER_NAME',document.getElementById("user").innerHTML);

在别的页面使用

sessionStorage.getItem('USER_NAME')

来获取这个值

页面初始化方法

window.onload = myfun;
function myfun(){

……

}

在body中写入

<body οnlοad="load();">

这样在页面加载时,就会自动执行myfun()方法中的内容

利用js改变页面标签状态

document.getElementById('xtb1').setAttribute('href','#');

其中xtb1是对应标签的id,href是这个标签的属性,#是属性对应的值,

这样就可以在js中改变标签状态

后端代码

    @PostMapping("/denglu")
    public String denglu(String User_Pass, String User_Phone, Model model) {
        User u = new User();
        u.setUser_Phone(User_Phone);
        u.setUser_Pass(User_Pass);

        //调用登录方法
        User one = this.user1.selectdenglu(u);

        if (one != null) {

            model.addAttribute("User_Name", "----------登录成功数据-----------");
          
            return "index";
        } else {
            return "login";
        }
    }

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <script type="application/javascript">  、
 
        window.onload = myfun;
        function myfun(){
       
           sessionStorage.setItem('USER_NAME',document.getElementById("user").innerHTML);

           var user=sessionStorage.getItem('USER_NAME');


           // 提示登录
           if(user==""){
             
               alert("需要登录!");
              
               document.getElementById('xtb3').setAttribute('href','#');

           }else
           {
               alert("登录成功!");
           }
        }

    </script>

</head>


<body οnlοad="load();">

<header>
       <span style="display: none" id="user" th:text="${User_Name}"></span>
</header>

</body>
</html>

  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是使用HTML+CSS+JS实现的前端代码以及使用Java+MySQL+MyBatis实现的后端代码。 前端代码:index.html ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>智能排班系统</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>智能排班系统</h1> <div> <label for="employees">请选择员工:</label> <select id="employees"></select> </div> <div> <label for="startDate">请选择开始日期:</label> <input id="startDate" type="date"> </div> <div> <label for="endDate">请选择结束日期:</label> <input id="endDate" type="date"> </div> <div> <button id="submit">提交</button> </div> <div> <h2>排班结果</h2> <table> <thead> <tr> <th>日期</th> <th>员工</th> <th>班次</th> </tr> </thead> <tbody id="shifts"></tbody> </table> </div> <script src="main.js"></script> </body> </html> ``` 前端代码主要包括一个表单和一个用于显示排班结果的表格。在表单,用户可以选择员工、开始日期和结束日期,并点击提交按钮。提交按钮的点击事件会向后端发送一个POST请求,请求体包含选择的员工ID和开始日期、结束日期。当后端返回排班结果时,前端会将结果显示在表格前端代码:style.css ```css h1 { font-size: 36px; text-align: center; margin-bottom: 30px; } div { margin-bottom: 10px; } label { display: inline-block; width: 150px; } select, input, button { font-size: 18px; padding: 5px; } button { background-color: #4CAF50; color: white; border: none; cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } th { background-color: #4CAF50; color: white; } ``` 前端代码的CSS样式主要用于美化页面。 前端代码:main.js ```javascript const employees = [ { id: 1, name: '张三' }, { id: 2, name: '李四' }, { id: 3, name: '王五' } ] const employeesSelect = document.getElementById('employees') employees.forEach(employee => { const option = document.createElement('option') option.value = employee.id option.text = employee.name employeesSelect.add(option) }) const submitButton = document.getElementById('submit') const startDateInput = document.getElementById('startDate') const endDateInput = document.getElementById('endDate') const shiftsTable = document.getElementById('shifts') submitButton.addEventListener('click', async () => { const employeeId = employeesSelect.value const startDate = startDateInput.value const endDate = endDateInput.value const response = await fetch('/schedule', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ employeeId, startDate, endDate }) }) const shifts = await response.json() shiftsTable.innerHTML = '' shifts.forEach(shift => { const row = document.createElement('tr') const dateCell = document.createElement('td') dateCell.innerText = shift.date row.appendChild(dateCell) const employeeCell = document.createElement('td') employeeCell.innerText = shift.employee row.appendChild(employeeCell) const shiftCell = document.createElement('td') shiftCell.innerText = shift.shift row.appendChild(shiftCell) shiftsTable.appendChild(row) }) }) ``` 前端代码JS主要用于处理表单提交事件以及将排班结果显示在表格后端代码:Employee.java ```java public class Employee { private int id; private String name; public Employee() {} public Employee(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` 后端代码的Employee类表示员工的数据模型。 后端代码:Shift.java ```java public class Shift { private String date; private Employee employee; private String shift; public Shift() {} public Shift(String date, Employee employee, String shift) { this.date = date; this.employee = employee; this.shift = shift; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public String getShift() { return shift; } public void setShift(String shift) { this.shift = shift; } } ``` 后端代码的Shift类表示排班的数据模型。 后端代码:ShiftMapper.java ```java public interface ShiftMapper { List<Shift> selectShifts(int employeeId, String startDate, String endDate); } ``` 后端代码的ShiftMapper接口定义了一个方法用于查询排班结果。 后端代码:ShiftMapper.xml ```xml <mapper namespace="com.example.mapper.ShiftMapper"> <resultMap id="shiftMap" type="com.example.model.Shift"> <result property="date" column="date"/> <association property="employee" javaType="com.example.model.Employee"> <result property="id" column="employee_id"/> <result property="name" column="employee_name"/> </association> <result property="shift" column="shift"/> </resultMap> <select id="selectShifts" resultMap="shiftMap"> select s.date, e.id as employee_id, e.name as employee_name, s.shift from shifts s join employees e on s.employee_id = e.id where s.employee_id = #{employeeId} and s.date between #{startDate} and #{endDate} order by s.date </select> </mapper> ``` 后端代码的ShiftMapper.xml文件定义了一个selectShifts查询语句,用于查询指定员工在指定日期范围内的排班结果。 后端代码:ShiftDAO.java ```java public class ShiftDAO { private SqlSessionFactory sessionFactory; public ShiftDAO() { String resource = "mybatis-config.xml"; Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { e.printStackTrace(); } sessionFactory = new SqlSessionFactoryBuilder().build(reader); } public List<Shift> selectShifts(int employeeId, String startDate, String endDate) { try (SqlSession session = sessionFactory.openSession()) { ShiftMapper mapper = session.getMapper(ShiftMapper.class); return mapper.selectShifts(employeeId, startDate, endDate); } } } ``` 后端代码的ShiftDAO类用于访问数据库,并调用ShiftMapper的方法查询排班结果。 后端代码:ScheduleServlet.java ```java public class ScheduleServlet extends HttpServlet { private ShiftDAO shiftDAO = new ShiftDAO(); @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int employeeId = Integer.parseInt(request.getParameter("employeeId")); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); List<Shift> shifts = shiftDAO.selectShifts(employeeId, startDate, endDate); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(new Gson().toJson(shifts)); } } ``` 后端代码的ScheduleServlet类用于处理前端发送的POST请求,并调用ShiftDAO的方法查询排班结果,并将结果以JSON格式返回给前端后端代码:mybatis-config.xml ```xml <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/scheduling"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/example/mapper/ShiftMapper.xml"/> </mappers> </configuration> ``` 后端代码的mybatis-config.xml文件用于配置MyBatis,指定连接MySQL数据库的信息和ShiftMapper.xml文件的位置。 这就是使用HTML+CSS+JS实现的前端代码以及使用Java+MySQL+MyBatis实现的后端代码。由于篇幅限制,这里只给出了代码的关键部分,如果需要完整代码,可以自行拼接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值