Vue + Spring Boot 获取 Session 值并循环输出内容
在 Vue 中无法直接访问 session 中的值,因为 Vue 是运行在客户端浏览器中的 JavaScript 框架,而 session 存储在服务器端。\n\n要获取 session 中的值,可以通过接口来实现。在 Spring Boot 中,可以使用 @Controller 注解来处理前端的请求,并通过 @SessionAttribute 注解来获取 session 中的值。\n\n以下是一个简单的示例代码:\n\n在后端(Spring Boot)中的 Controller 类中:\n\njava\n\@Controller\npublic class MyController {\n \@GetMapping("/getSessionValue")\n \@ResponseBody\n public String getSessionValue(\@SessionAttribute("mySessionValue") String mySessionValue) {\n return mySessionValue;\n }\n}\n\n\n在前端(Vue)中的代码:\n\nvue\n<template>\n <div>\n <ul>\n <li v-for="item in sessionValues" :key="item.id">{{ item.value }}</li>\n </ul>\n </div>\n</template>\n\n<script>\n export default {\n data() {\n return {\n sessionValues: []\n };\n },\n mounted() {\n this.getSessionValue();\n },\n methods: {\n getSessionValue() {\n axios.get('/getSessionValue')\n .then(response => {\n this.sessionValues = response.data;\n })\n .catch(error => {\n console.log(error);\n });\n }\n }\n };\n</script>\n\n\n在上述代码中,后端的 Controller 类中的 getSessionValue 方法使用 @SessionAttribute 注解来获取 session 中名为 "mySessionValue" 的值,并返回给前端。前端的 Vue 组件中,通过调用 getSessionValue 方法来获取后端返回的 session 值,并将其赋值给 sessionValues 变量,然后在模板中使用 v-for 指令循环输出 sessionValues 中的值。\n\n请注意,上述代码仅为示例,实际项目中需要根据具体业务进行相应的调整。
原文地址: https://www.cveoy.top/t/topic/pqpW 著作权归作者所有。请勿转载和采集!