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,再见!”
从项目的建立开始引导我完成前端页面的建立。并且逐步指引我完成整个项目,如前端界面的完整建立和前后端的对接