springboot

使用springboot的thymeleaf在前端获取数据,使用model和session前端都获取不到。
InfoController.java

package com.example.h1.controller;

import com.example.h1.domain.User;
import com.example.h1.service.UserService;
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.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class InfoController extends HttpServlet {

    @Autowired
    public UserService userService;
    //查询并返回页面
//    @RequestMapping("/info")
//    public String list(Model model){
//        List list = userService.findAll();
//        model.addAttribute("infor" , list);
//        model.addAttribute("aaa","aaa");
//        return "redirect:/static/infor.html";
//    }

    @RequestMapping("/info")
    public String list(HttpServletRequest request, HttpServletResponse response) {
        List<User> list = userService.findAll();
        //添加session
        request.getSession().setAttribute("infor",list);
        System.out.println(request.getSession().getAttribute("infor"));
        return "redirect:/static/infor.html";
    }

}

这里我输出了一下session在控制台可以看到存入的数据。

img

infor.html

html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实验室设备管理系统title>
head>
<body οnlοad="load();">
<h1>实验室设备管理系统h1>
<div>
  <table>
    <thead>
    <tr>
      <th>编号th>
      <th>账号th>
      <th>密码th>
      <th>姓名th>
      <th>性别th>
      <th>年龄th>
      <th>电话th>
      <th>操作th>
    tr>
    thead>
    <tbody>
    <tr th:each="i:${session.infor}">
      <td th:text="${i.getId()}">td>
      <td th:text="${i.getUsername()}">td>
      <td th:text="${i.getPassword()}">td>
      <td th:text="${i.getName()}">td>
      <td th:text="${i.getSex()}">td>
      <td th:text="${i.getAge()}">td>
      <td th:text="${i.getTel()}">td>
      <td>
        <button>编辑button>
        <button>删除button>
      td>
    tr>
    tbody>
  table>
div>
body>
html>


pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.5version>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>h1artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>h1name>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.4.1version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>

        <dependency>
            <groupId>com.mysqlgroupId>
            <artifactId>mysql-connector-jartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.xmlunitgroupId>
            <artifactId>xmlunit-coreartifactId>
            <version>2.9.0version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtmlgroupId>
            <artifactId>nekohtmlartifactId>
            <version>1.9.22version>
        dependency>

        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.6version>
        dependency>

        <dependency>
            <groupId>com.github.whvcsegroupId>
            <artifactId>easy-captchaartifactId>
            <version>1.6.2version>
        dependency>
    dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.ymlinclude>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.ymlinclude>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                    <include>**/*.htmlinclude>
                    <include>**/*.cssinclude>
                includes>
            resource>
        resources>
    build>

project>


在网上找了好多,感觉可能是因为InfoController里使用return "redirect:/static/infor.html";跳转的原因。
但是在最早创建项目时就遇到了用return "infor";跳转不过去的问题,网页报错:

img

控制台报错:

img

所以才使用return "redirect:/static/infor.html";跳转。
有没有办法让使用return "redirect:/static/infor.html";跳转前端能获取到数据,或者怎么使用return "infor";跳转?
求带佬指导一下,谢谢!

根据您提供的代码和信息,您在InfoController中的list方法中将数据添加到session中,然后重定向到了一个静态页面infor.html。但是您在infor.html中无法通过model或session获取数据。

这是因为Thymeleaf是一个服务器端的模板引擎,它的作用是在服务器端渲染模板,并将渲染后的HTML代码发送给浏览器。因此,Thymeleaf模板中无法直接获取session或request中的数据。

如果您想在infor.html中展示数据,可以考虑使用Ajax来获取数据,或者在后端将数据渲染到模板中并返回给浏览器。具体的实现方法取决于您的具体需求。

您在控制器中使用了重定向(redirect),将请求重定向到另一个URL上,因此请求的属性(包括session属性)不会在重定向后继续存在。如果您想使用model或session在重定向后向另一个URL发送数据,您可以考虑使用FlashAttributes或使用URL参数传递数据。

以下是这些选项的简短概述:

1.FlashAttributes:FlashAttributes是在Spring MVC中进行重定向时临时保存数据的一种机制,以便在请求重定向后从一个控制器方法传递数据到另一个控制器方法。 FlashAttributes可在控制器方法之间传递一次性数据,并且只在重定向后的第一个请求中使用。您可以通过RedirectAttributes对象将Flash属性添加到重定向URL中,例如:


@RequestMapping("/info")
public String list(RedirectAttributes redirectAttributes) {
    List<User> list = userService.findAll();
    redirectAttributes.addFlashAttribute("infor", list);
    return "redirect:/static/infor.html";
}

在您的前端代码中,您可以使用以下方式获取Flash属性:


<tr th:each="i : ${#flash['infor']}">

请注意,FlashAttributes并不适用于将大量数据传递给控制器方法,因为数据存储在会话中,可能会导致会话过大的问题。

2.URL参数:您可以通过URL参数将数据传递给重定向后的URL。例如,您可以像下面这样在重定向URL中包含参数:


@RequestMapping("/info")
public String list(Model model) {
    List<User> list = userService.findAll();
    String encodedData = URLEncoder.encode(list.toString(), "UTF-8");
    return "redirect:/static/infor.html?infor=" + encodedData;
}

然后您可以使用JavaScript从URL参数中提取数据,例如:


function getParameterByName(name) {
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(window.location.search);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var data = getParameterByName('infor');
// 现在data是您的数据,您可以将其解析为JavaScript对象

请注意,这只是两种可用的选项之一,具体取决于您的要求和偏好。如果您希望在不使用JavaScript的情况下将数据传递到新页面,则使用Flash属性可能更简单,而如果您需要在重定向后保持原始URL,则使用URL参数可能更好。

如果跳static目录下的文件,不要加static目录,另外嗯是request.getSession放的时候在request域钟 可以换成HttpSession类型对应session去set方法写入值试试
最好放在HttpSession里面打印session域中,着不会出现页面跳转就会丢失值的问题

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 关于该问题,我找了一篇非常好的博客,你可以看看是否有帮助,链接:SpringBoot异常汇总

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

你好,尼前端拿的值是通过转发拿到的,所以重定向转发带的参数就失效了。
可以这样实现重定向代参。

RedirectAttributes model 作为入参
model.addFlashAttribute("msg", username); 重定向前这样做


而直接返回页面,不拼接redirect 这样前端是能获取到值的。
希望能帮到题主。

经过几天的解决,感谢几位好兄弟给出的各种解决方案,最终采用了“不咕鸟会咕咕”提出的解决方法。
InfoContorller.java

@Controller
public class InfoController{

    @Autowired
    public UserService userService;
    //查询并返回页面
    @RequestMapping("/info")
    public String list(Model model){
        List<User> list = userService.findAll();
        model.addAttribute("infor" , list);
        System.out.println(model.getAttribute("infor"));
        return "infor";
    }
}

infor.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实验室设备管理系统</title>
</head>
<body οnlοad="load();">
<h1>实验室设备管理系统</h1>
<div>
  <table>
    <thead>
    <tr>
      <th>编号</th>
      <th>账号</th>
      <th>密码</th>
      <th>姓名</th>
      <th>性别</th>
      <th>年龄</th>
      <th>电话</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="i : ${infor}">
      <td th:text="${i.getId()}"></td>
      <td th:text="${i.getUsername()}"></td>
      <td th:text="${i.getPassword()}"></td>
      <td th:text="${i.getName()}"></td>
      <td th:text="${i.getSex()}"></td>
      <td th:text="${i.getAge()}"></td>
      <td th:text="${i.getTel()}"></td>
      <td>
        <button>编辑</button>
        <button>删除</button>
      </td>
    </tr>
    </tbody>
  </table>
</div>
</body>
</html>


虽然html页面里还会报红。

img

但是运行后的页面已经可以显示想要的数据了。

img

想要消除报红的话,可以参考一下这篇博客。
https://blog.csdn.net/weixin_52173254/article/details/127384678
还有之前提出的使用return "redirect:/static/infor.html";跳转前端能获取到数据,或者怎么使用return "infor";跳转的问题。
用重定向跳转前端获取数据的方法,大家可以上面“qq_46161207”的评论里提出的方法。
我使用return "infor";无法跳转到指定页面的问题,经过寻找也得到了解决。
在controller里使用@RequestMapping注解跳转时,
controller.java


@RequestMapping("/login")//当你在浏览器输入/login,我们会直接跳转到登陆界面
    public String toLogin() {
            return "login";
    }

要在application.yml里写入一些配置,
application.yml

spring:
  # thymeleaf 模板引擎配置
  thymeleaf:     # 不设置缓存
    cache: false
    # thymeleaf模板 解除严格约束(对html5没有结束符的标签解决)
    mode: HTML5
    # thymeleaf修饰的动态页面 自定义根目录(springBoot默认的动态页面存放文件夹就是templates)
    prefix: classpath:/static/
    suffix: .html #默认
    check-template-location: true  #check-tempate-location: 检查模板路径是否存在
    encoding: UTF-8
    content-type: text/html

其中prefix: classpath:/static/,这个配置里 classpath:/ / 两个“/”中间的部分应该是你自己项目里html的存放路径。

img

我之前就是因为两个“/”中间写的部分与html的存放路径不一致,所以导致一直跳转不到指定页面,进而导致前端页面拿不到后端传递的数据。
以上就是我之前遇到的问题的解决方法,希望能为大家遇到问题时提供一个解决方法。