EL实现List<Map>的前后台数值传递

本文通过一个具体的Java示例展示了如何使用集合框架中的List和Map来存储数据,并在JSP页面上展示这些数据。该示例包括了在后台创建一个包含多个映射的列表,并将其传递到前端显示。

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

后台的代码:

List<Map<String, String>> list=new ArrayList<Map<String,String>>();  
  for(int i =0 ;i<10;i++){  
  Map<String, String> map=new HashMap<String, String>();  
  map.put("tt", "map"+i);  
  list.add(map);
  }  
session.setAttribute("list",list); 

前台代码:

<c:forEach var="map" items="${sessionScope.list}"> 
	${map.tt}或者${map['tt']} 
</c:forEach>


<template> <el-container style="height: 100vh"> <el-aside width="200px"> <el-menu default-active="1" class="el-menu-vertical-demo"> <el-menu-item index="1">员工管理</el-menu-item> </el-menu> </el-aside> <el-container> <el-header> <h2>员工管理系统</h2> </el-header> <el-main> <!-- 查询条件 --> <el-row :gutter="20" style="margin-bottom: 20px;"> <el-col :span="4"> <el-input v-model="queryParams.name" placeholder="请输入姓名" /> </el-col> <el-col :span="4"> <el-select v-model="queryParams.gender" placeholder="请选择性别"> <el-option label="男" :value="0"></el-option> <el-option label="女" :value="1"></el-option> </el-select> </el-col> <el-col :span="4"> <el-select v-model="queryParams.job" placeholder="请选择职位"> <el-option label="班主任" :value="1"></el-option> <el-option label="讲师" :value="2"></el-option> <el-option label="学工主管" :value="3"></el-option> <el-option label="教研主管" :value="4"></el-option> <el-option label="咨询师" :value="5"></el-option> </el-select> </el-col> <el-col :span="6"> <el-date-picker v-model="queryParams.dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" /> </el-col> <el-col :span="4"> <el-button type="primary" @click="fetchData">搜索</el-button> <el-button type="success" @click="showAddDialog">新增</el-button> <el-button type="danger" @click="batchDelete">批量删除</el-button> </el-col> </el-row> <!-- 数据表格 --> <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55" /> <el-table-column prop="id" label="ID" width="80" /> <el-table-column prop="name" label="姓名" /> <el-table-column prop="gender" label="性别" width="80"> <template #default="scope"> {{ scope.row.gender === 0 ? '男' : '女' }} </template> </el-table-column> <el-table-column prop="job" label="职位" width="120"> <template #default="scope"> {{ jobMap[scope.row.job] || '未知' }} </template> </el-table-column> <el-table-column prop="entrydate" label="入职时间" width="120" /> <el-table-column label="头像" width="100"> <template #default="scope"> <el-image v-if="scope.row.image" :src="scope.row.image" style="width: 50px; height: 50px; border-radius: 50%;" :preview-src-list="[scope.row.image]" /> <span v-else>暂无图片</span> </template> </el-table-column> <el-table-column prop="createTime" label="创建时间" width="150" /> <el-table-column label="操作" width="200"> <template #default="scope"> <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button> <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button> </template> </el-table-column> </el-table> <!-- 分页组件 --> <el-pagination layout="prev, pager, next" :total="total" :page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum" @current-change="fetchData" /> </el-main> </el-container> </el-container> <!-- 新增/编辑对话框 --> <el-dialog v-model="dialogVisible" :title="dialogTitle"> <el-form :model="form" label-width="100px"> <el-form-item label="姓名"> <el-input v-model="form.name" /> </el-form-item> <el-form-item label="用户名"> <el-input v-model="form.username" /> </el-form-item> <el-form-item label="密码"> <el-input v-model="form.password" show-password /> </el-form-item> <el-form-item label="性别"> <el-select v-model="form.gender" placeholder="请选择性别"> <el-option label="男" :value="0"></el-option> <el-option label="女" :value="1"></el-option> </el-select> </el-form-item> <el-form-item label="职位"> <el-select v-model="form.job" placeholder="请选择职位"> <el-option label="班主任" :value="1"></el-option> <el-option label="讲师" :value="2"></el-option> <el-option label="学工主管" :value="3"></el-option> <el-option label="教研主管" :value="4"></el-option> <el-option label="咨询师" :value="5"></el-option> </el-select> </el-form-item> <el-form-item label="头像链接"> <el-input v-model="form.image" /> </el-form-item> <el-form-item label="入职时间"> <el-date-picker v-model="form.entrydate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" /> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> <el-button @click="dialogVisible = false">取消</el-button> </el-form-item> </el-form> </el-dialog> </template> <script setup> import { ref, onMounted } from 'vue'; import axios from 'axios'; // 设置 axios 实例 const apiClient = axios.create({ baseURL: 'http://localhost:8080/emps', timeout: 5000, }); // 表格数据 const tableData = ref([]); const total = ref(0); const selectedRows = ref([]); // 查询参数 const queryParams = ref({ pageNum: 1, pageSize: 5, name: '', gender: null, job: null, dateRange: [] }); // 表单数据 const form = ref({ id: null, username: '', password: '', name: '', gender: null, job: null, image: '', entrydate: '' }); // 对话框控制 const dialogVisible = ref(false); const dialogTitle = ref('新增员工'); const isEdit = ref(false); // 职位映射表 const jobMap = { 1: '班主任', 2: '讲师', 3: '学工主管', 4: '教研主管', 5: '咨询师' }; // 获取数据 const fetchData = async () => { const params = { page: queryParams.value.pageNum, pageSize: queryParams.value.pageSize, name: queryParams.value.name, gender: queryParams.value.gender, job: queryParams.value.job, begin: queryParams.value.dateRange[0] || '', end: queryParams.value.dateRange[1] || '' }; try { const res = await apiClient.get('', { params }); if (res.data.code === 1) { tableData.value = res.data.data.rows; total.value = res.data.data.total; } else { alert('获取数据失败:' + res.data.msg); } } catch (error) { console.error('请求出错:', error); alert('网络请求失败,请检查后端是否运行正常'); } }; // 显示新增对话框 const showAddDialog = () => { dialogTitle.value = '新增员工'; isEdit.value = false; form.value = { id: null, username: '', password: '', name: '', gender: null, job: null, image: '', entrydate: '' }; dialogVisible.value = true; }; // 显示编辑对话框 const handleEdit = (row) => { dialogTitle.value = '编辑员工'; isEdit.value = true; form.value = { ...row }; dialogVisible.value = true; }; // 提交表单 const submitForm = async () => { try { if (isEdit.value) { await apiClient.put('', form.value); } else { await apiClient.post('', form.value); } dialogVisible.value = false; fetchData(); } catch (error) { console.error('保存失败:', error); alert('操作失败,请查看控制台日志'); } }; // 删除员工 const handleDelete = async (id) => { if (!confirm(`确认删除ID为 ${id} 的员工吗?`)) return; try { await apiClient.delete(`/${[id]}`); fetchData(); } catch (error) { console.error('删除失败:', error); alert('删除失败,请查看控制台日志'); } }; // 批量删除 const batchDelete = () => { if (selectedRows.value.length === 0) { alert('请至少选择一条记录'); return; } const ids = selectedRows.value.map(item => item.id); if (!confirm(`确认删除选中的 ${ids.length} 条员工吗?`)) return; try { apiClient.delete(`/${ids}`); fetchData(); } catch (error) { console.error('批量删除失败:', error); alert('删除失败,请查看控制台日志'); } }; // 表格选择监听 const handleSelectionChange = (rows) => { selectedRows.value = rows; }; // 初始化加载数据 onMounted(() => { fetchData(); }); </script> <style scoped> .el-header { background-color: #f5f7fa; display: flex; align-items: center; } </style> 帮我优化一下代码,使代码更简洁,美化一下页面,把头像列放到名字列后面
最新发布
07-15
package com.example.walk.common; public class ApiResponse<T> { private boolean success; private String message; private T data; public ApiResponse(boolean success, String message, T data) { this.success = success; this.message = message; this.data = data; } public static <T> ApiResponse<T> success(T data) { return new ApiResponse<>(true, “Success”, data); } public static <T> ApiResponse<T> error(String message) { return new ApiResponse<>(false, message, null); } public boolean isSuccess() { return success; } public String getMessage() { return message; } public T getData() { return data; } } package com.example.walk.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; /** * Spring Security 配置类 * 用于配置应用程序的安全相关设置 / @Configuration @EnableWebSecurity public class SecurityConfig { /* * 配置密码编码器 * 使用 BCrypt 算法进行密码加密 * BCrypt 是一种基于 Blowfish 加密算法的密码哈希函数 * 它会自动生成随机盐值,并将盐值与密码一起哈希 * * @return PasswordEncoder 实例 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * 配置安全过滤器链 * 定义应用程序的安全规则和访问控制 * * @param http HttpSecurity 对象,用于配置安全规则 * @return SecurityFilterChain 实例 * @throws Exception 如果配置过程中发生错误 */ @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 禁用 CSRF 保护 // CSRF 是一种跨站请求伪造攻击,在 RESTful API 中通常不需要 .csrf(csrf -> csrf.disable()) // 配置请求授权 .authorizeHttpRequests(auth -> auth // 允许所有请求通过,不需要认证 // 这意味着所有的 API 端点都可以直接访问 .anyRequest().permitAll() ); return http.build(); } } package com.example.walk.controller; import com.example.walk.common.ApiResponse; import com.example.walk.entity.Admin; import com.example.walk.service.AdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * 管理员控制器 * 处理所有与管理员相关的HTTP请求 * 提供管理员的注册、登录等功能 */ @RestController @RequestMapping(“/api/admins”) public class AdminController { @Autowired private AdminService adminService; /** * 管理员注册 * 创建新的管理员账号 * * @param admin 管理员信息,包含用户名、密码等 * @return 注册成功的管理员信息 */ @PostMapping(“/register”) public ResponseEntity<ApiResponse<Admin>> register(@RequestBody Admin admin) { try { Admin registeredAdmin = adminService.register(admin); return ResponseEntity.ok(ApiResponse.success(registeredAdmin)); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage())); } } /** * 管理员登录 * 验证管理员身份并返回管理员信息 * * @param credentials 包含用户名和密码的凭证 * @return 登录成功的管理员信息 */ @PostMapping(“/login”) public ResponseEntity<ApiResponse<Admin>> login(@RequestBody Map<String, String> credentials) { return adminService.login(credentials.get(“username”), credentials.get(“password”)) .map(admin -> ResponseEntity.ok(ApiResponse.success(admin))) .orElse(ResponseEntity.badRequest().body(ApiResponse.error(“Invalid credentials”))); } } package com.example.walk.controller; import com.example.walk.entity.Guide; import com.example.walk.service.GuideService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 攻略控制器 * 处理所有与旅游攻略相关的HTTP请求 * 提供攻略的创建、更新、删除、查询等功能 */ @RestController @RequestMapping(“/api/guides”) public class GuideController { @Autowired private GuideService guideService; /** * 创建攻略 * 创建新的旅游攻略 * * @param guide 攻略信息,包含标题、内容、目的地等 * @param authorId 作者ID * @return 创建成功的攻略信息 */ @PostMapping public ResponseEntity<?> createGuide(@RequestBody Guide guide, @RequestParam Long authorId) { try { Guide createdGuide = guideService.createGuide(guide, authorId); return ResponseEntity.ok(createdGuide); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(e.getMessage()); } } /** * 更新攻略 * 修改指定ID的攻略信息 * * @param id 攻略ID * @param guide 更新的攻略信息 * @return 更新后的攻略信息 */ @PutMapping(“/{id}”) public ResponseEntity<?> updateGuide(@PathVariable Long id, @RequestBody Guide guide) { try { Guide updatedGuide = guideService.updateGuide(id, guide); return ResponseEntity.ok(updatedGuide); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(e.getMessage()); } } /** * 删除攻略 * 删除指定ID的攻略 * * @param id 要删除的攻略ID * @return 删除操作的结果 */ @DeleteMapping(“/{id}”) public ResponseEntity<?> deleteGuide(@PathVariable Long id) { try { guideService.deleteGuide(id); return ResponseEntity.ok().build(); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(e.getMessage()); } } /** * 搜索攻略 * 根据关键词搜索攻略 * * @param keyword 搜索关键词 * @return 匹配的攻略列表 */ @GetMapping(“/search”) public List<Guide> searchGuides(@RequestParam String keyword) { return guideService.searchGuides(keyword); } /** * 按目的地查询攻略 * 查询指定目的地的所有攻略 * * @param destination 目的地名称 * @return 该目的地的攻略列表 */ @GetMapping(“/destination”) public List<Guide> findByDestination(@RequestParam String destination) { return guideService.findByDestination(destination); } /** * 获取攻略详情 * 根据ID查询攻略详细信息 * * @param id 攻略ID * @return 攻略详细信息 */ @GetMapping(“/{id}”) public ResponseEntity<?> getGuideById(@PathVariable Long id) { return guideService.getGuideById(id) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } /** * 获取作者的攻略 * 查询指定作者的所有攻略 * * @param authorId 作者ID * @return 该作者的攻略列表 */ @GetMapping(“/author/{authorId}”) public List<Guide> getGuidesByAuthor(@PathVariable Long authorId) { return guideService.getGuidesByAuthor(authorId); } } package com.example.walk.controller; import com.example.walk.common.ApiResponse; import com.example.walk.entity.User; import com.example.walk.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; /** * 用户控制器 * 处理所有与用户相关的HTTP请求 * 提供用户的注册、登录、信息管理等功能 */ @RestController @RequestMapping(“/api/users”) public class UserController { @Autowired private UserService userService; /** * 用户注册 * 创建新用户账号 * * @param user 用户信息,包含用户名、密码等 * @return 注册成功的用户信息 */ @PostMapping(“/register”) public ResponseEntity<ApiResponse<User>> register(@RequestBody User user) { try { User registeredUser = userService.register(user); return ResponseEntity.ok(ApiResponse.success(registeredUser)); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage())); } } /** * 用户登录 * 验证用户身份并返回用户信息 * * @param credentials 包含用户名和密码的凭证 * @return 登录成功的用户信息 */ @PostMapping(“/login”) public ResponseEntity<ApiResponse<User>> login(@RequestBody Map<String, String> credentials) { return userService.login(credentials.get(“username”), credentials.get(“password”)) .map(user -> ResponseEntity.ok(ApiResponse.success(user))) .orElse(ResponseEntity.badRequest().body(ApiResponse.error(“Invalid credentials”))); } /** * 更新用户信息 * 修改指定用户的信息 * * @param id 用户ID * @param user 更新的用户信息 * @return 更新后的用户信息 */ @PutMapping(“/{id}”) public ResponseEntity<ApiResponse<User>> updateUser(@PathVariable Long id, @RequestBody User user) { try { User updatedUser = userService.updateUser(id, user); return ResponseEntity.ok(ApiResponse.success(updatedUser)); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage())); } } /** * 删除用户 * 删除指定ID的用户账号 * * @param id 要删除的用户ID * @return 删除操作的结果 */ @DeleteMapping(“/{id}”) public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable Long id) { try { userService.deleteUser(id); return ResponseEntity.ok(ApiResponse.success(null)); } catch (RuntimeException e) { return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage())); } } /** * 获取所有用户 * 返回系统中所有用户的列表 * * @return 用户列表 */ @GetMapping(“/all”) public List<User> getAllUsers() { return userService.getAllUsers(); } /** * 获取指定用户信息 * 根据用户ID查询用户详细信息 * * @param id 用户ID * @return 用户详细信息 */ @GetMapping(“/{id}”) public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable Long id) { return userService.getUserById(id) .map(user -> ResponseEntity.ok(ApiResponse.success(user))) .orElse(ResponseEntity.ok(ApiResponse.error(“User not found”))); } } package com.example.walk.entity; import jakarta.persistence.*; import lombok.Data; @Data @Entity @Table(name = “admins”) public class Admin { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true, nullable = false) private String username; @Column(nullable = false) private String password; } package com.example.walk.entity; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDateTime; @Data @Entity @Table(name = “guides”) public class Guide { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String title; @Column(columnDefinition = “TEXT”) private String content; @ManyToOne @JoinColumn(name = “author_id”, nullable = false) private User author; @Column(name = “publish_time”) private LocalDateTime publishTime; @Column(nullable = false) private String destination; @PrePersist protected void onCreate() { publishTime = LocalDateTime.now(); } } package com.example.walk.entity; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDateTime; @Data @Entity @Table(name = “users”) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true, nullable = false) private String username; @Column(nullable = false) private String password; @Column(name = “user_status”) private String status; @Column(name = “register_time”) private LocalDateTime registerTime; @PrePersist protected void onCreate() { registerTime = LocalDateTime.now(); } } package com.example.walk.mapper; import com.example.walk.entity.Admin; import org.apache.ibatis.annotations.*; @Mapper public interface AdminMapper { @Insert(“INSERT INTO admins (username, password) VALUES (#{username}, #{password})”) @Options(useGeneratedKeys = true, keyProperty = “id”) int insert(Admin admin); @Select(“SELECT * FROM admins WHERE username = #{username}”) Admin findByUsername(String username); @Select(“SELECT COUNT(*) FROM admins WHERE username = #{username}”) int existsByUsername(String username); } package com.example.walk.mapper; import com.example.walk.entity.Guide; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface GuideMapper { @Insert("INSERT INTO guides (title, content, author_id, publish_time, destination) " + “VALUES (#{title}, #{content}, #{author.id}, #{publishTime}, #{destination})”) @Options(useGeneratedKeys = true, keyProperty = “id”) int insert(Guide guide); @Update("UPDATE guides SET title = #{title}, content = #{content}, " + “destination = #{destination} WHERE id = #{id}”) int update(Guide guide); @Delete(“DELETE FROM guides WHERE id = #{id}”) int deleteById(Long id); @Select(“SELECT * FROM guides WHERE destination LIKE CONCAT(‘%’, #{destination}, ‘%’)”) List<Guide> findByDestination(String destination); @Select("SELECT * FROM guides WHERE title LIKE CONCAT(‘%’, #{keyword}, ‘%’) " + “OR content LIKE CONCAT(‘%’, #{keyword}, ‘%’)”) List<Guide> searchByKeyword(String keyword); @Select(“SELECT * FROM guides WHERE id = #{id}”) Guide findById(Long id); @Select(“SELECT * FROM guides WHERE author_id = #{authorId}”) List<Guide> findByAuthorId(Long authorId); } package com.example.walk.mapper; import com.example.walk.entity.User; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface UserMapper { @Insert("INSERT INTO users (username, password, user_status, register_time) " + “VALUES (#{username}, #{password}, #{status}, #{registerTime})”) @Options(useGeneratedKeys = true, keyProperty = “id”) int insert(User user); @Select(“SELECT * FROM users WHERE username = #{username}”) User findByUsername(String username); @Select(“SELECT COUNT(*) FROM users WHERE username = #{username}”) int existsByUsername(String username); @Update(“UPDATE users SET username = #{username}, password = #{password} WHERE id = #{id}”) int update(User user); @Delete(“DELETE FROM users WHERE id = #{id}”) int deleteById(Long id); @Select(“SELECT * FROM users”) List<User> findAll(); @Select(“SELECT * FROM users WHERE id = #{id}”) User findById(Long id); } package com.example.walk.service; import com.example.walk.entity.Admin; import com.example.walk.mapper.AdminMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class AdminService { @Autowired private AdminMapper adminMapper; @Autowired private PasswordEncoder passwordEncoder; public Admin register(Admin admin) { if (adminMapper.existsByUsername(admin.getUsername()) > 0) { throw new RuntimeException(“Admin username already exists”); } admin.setPassword(passwordEncoder.encode(admin.getPassword())); adminMapper.insert(admin); return admin; } public Optional<Admin> login(String username, String password) { Admin admin = adminMapper.findByUsername(username); if (admin != null && passwordEncoder.matches(password, admin.getPassword())) { return Optional.of(admin); } return Optional.empty(); } } package com.example.walk.service; import com.example.walk.entity.Guide; import com.example.walk.entity.User; import com.example.walk.mapper.GuideMapper; import com.example.walk.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class GuideService { @Autowired private GuideMapper guideMapper; @Autowired private UserMapper userMapper; public Guide createGuide(Guide guide, Long authorId) { User author = userMapper.findById(authorId); if (author == null) { throw new RuntimeException(“Author not found”); } guide.setAuthor(author); guideMapper.insert(guide); return guide; } public Guide updateGuide(Long id, Guide updatedGuide) { Guide guide = guideMapper.findById(id); if (guide == null) { throw new RuntimeException(“Guide not found”); } guide.setTitle(updatedGuide.getTitle()); guide.setContent(updatedGuide.getContent()); guide.setDestination(updatedGuide.getDestination()); guideMapper.update(guide); return guide; } public void deleteGuide(Long id) { guideMapper.deleteById(id); } public List<Guide> searchGuides(String keyword) { return guideMapper.searchByKeyword(keyword); } public List<Guide> findByDestination(String destination) { return guideMapper.findByDestination(destination); } public Optional<Guide> getGuideById(Long id) { return Optional.ofNullable(guideMapper.findById(id)); } public List<Guide> getGuidesByAuthor(Long authorId) { return guideMapper.findByAuthorId(authorId); } } package com.example.walk.service; import com.example.walk.entity.User; import com.example.walk.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserMapper userMapper; @Autowired private PasswordEncoder passwordEncoder; public User register(User user) { if (userMapper.existsByUsername(user.getUsername()) > 0) { throw new RuntimeException(“Username already exists”); } // 给新注册账号密码加密 user.setPassword(passwordEncoder.encode(user.getPassword())); user.setStatus(“ACTIVE”); userMapper.insert(user); return user; } public Optional<User> login(String username, String password) { User user = userMapper.findByUsername(username); // 这部分是用户登陆的时候的密码比对(解密) if (user != null && passwordEncoder.matches(password, user.getPassword())) { return Optional.of(user); } return Optional.empty(); } public User updateUser(Long id, User updatedUser) { User user = userMapper.findById(id); if (user == null) { throw new RuntimeException(“User not found”); } user.setUsername(updatedUser.getUsername()); if (updatedUser.getPassword() != null && !updatedUser.getPassword().isEmpty()) { user.setPassword(passwordEncoder.encode(updatedUser.getPassword())); } userMapper.update(user); return user; } public void deleteUser(Long id) { userMapper.deleteById(id); } public List<User> getAllUsers() { return userMapper.findAll(); } public Optional<User> getUserById(Long id) { return Optional.ofNullable(userMapper.findById(id)); } } package com.example.walk; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WalkApplication { public static void main(String[] args) { SpringApplication.run(WalkApplication.class, args); } } package com.example.walk; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class WalkApplicationTests { @Test void contextLoads() { } } 这是我的后端项目代码,我正在建立一个javaweb的后台管理系统,请根据我提供的后端项目代码提供给我对应的前端项目代码,并实现对接。以下是前端界面要求。信息管理系统实现。 需求:我已经使用vscode以springboot+mybatis完成了后端代码编写,请使用vscode软件以vue+element-ui的形式编写对应的前端代码包含用户、管理员、攻略信息的添加、显示、删除和修改等操作。 功能要求: 用户、管理员、攻略信息添加 输入信息:系统应允许用户和管理员进行登录、注册。登录时需输入账号和密码。注册时输入账号、密码、邮箱、手机号,并自动生成ID号,管理员的ID号范围在1-99,用户id号从三位数开始自动生成,管理员注册需提供管理员密令,在注册管理员时要求用户提供。准许管理员对攻略信息的添加(包括文章ID、标题、内容、作者ID、发布时间、目的地。) 唯一性检查:在用户和管理员进行注册时,系统需检查ID是否已存在于系统中。若已存在,应给出相应提示,禁止重复添加;若不存在,则成功添加信息。 反馈信息:登录、注册成功后,系统应提示用户 “登陆成功”或“注册成功”;登录失败时,提示“账号或密码错误”。注册失败时,提示 “该用户已存在,无法重复注册。” 信息显示: 信息展示:系统应能显示用户和管理员的基本信息,包括账号、密码、手机号、邮箱。用户界面添加一个浏览记录。管理员界面以罗列的形式查看用户以及他们的基本信息和ID号。并且可以查看攻略信息。 空信息处理:若系统中暂无攻略信息,应提示管理员和用户 “暂无攻略信息。” 用户信息删除: 输入账号或者ID:管理员可输入要删除的用户账号或ID号对用户进行强制注销,可以输入攻略ID将攻略删除。用户可以在自己的用户界面进行账号注销。 信息查找:系统需检查输入的账号或ID号是否存在于系统中,若存在,则删除该用户信息,在管理员界面提示 “成功删除该用户信息。”若不存在,提示 “未找到用户信息。”。在用户界面提供注销按钮,点击注销后删除用户信息并提示“注销成功”,然后返回登录、注册界面。 信息修改: 输入账号:用户界面提供一个修改按钮,修改自己的基本信息。管理员界面在每一个用户信息后面设置一个编辑按钮,点击后对用户信息进行修改 信息修改:用户可输入新的账号、密码、邮箱、手机号,若不修改某项信息,可不填写。修改成功后,系统提示 “修改成功。” 系统交互: 操作菜单:系统应提供一个清晰的操作菜单,管理员界面包含 “添加信息”、“显示所有用户信息”、“删除用户信息”、“修改用户信息” 和 “退出” 等选项。用户界面包含“修改信息”等选项 退出提示:当用户选择 “退出” 选项时,系统应提示 “感谢使用walk,再见!” 从项目的建立开始引导我完成前端页面的建立。并且逐步指引我完成整个项目,如前端界面的完整建立和前后端的对接
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值