【java】model.addAttribute("method", "update");

本文介绍了一个使用@RequestMapping注解处理GET请求的方法,该方法通过路径参数获取角色ID,并调用service层方法获取角色信息,最终返回角色编辑页面。
@RequestMapping(method = RequestMethod.GET, value = "/update/{id}")
public String forUpdate(Model model, @PathVariable("id") Long id) {
SystemRole systemRole = systemRoleService.getById(id);
model.addAttribute("systemRole", systemRole);
model.addAttribute("method", "update");
return "role/role_edit";
}

转载于:https://www.cnblogs.com/CESC4/p/7397031.html

package com.guilin.Student.controller; import com.guilin.Student.pojo.Student; import com.guilin.Student.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class StudentController { @Autowired private StudentService studentService; // 获取所有学生列表 @RequestMapping("/findStudents") public String getStudents(Model model) { List<Student>students=studentService.findStudents(); model.addAttribute("students", students); return "list"; // 对应/WEB-INF/views/student/list.jsp } // 删除学生 @RequestMapping("/delete") public String deleteStudentById(int studentId) { studentService.deleteStudentById(studentId); return "redirect:/findStudents"; } // 显示添加表单 @RequestMapping("/add") public String forwardAddPage() { return "redirect:/add"; } // 处理添加 @RequestMapping("/add") public String addStudent(Student student) { studentService.addStudent(student); return "redirect:/findStudents"; } // 显示编辑表单 @RequestMapping("/findById") public String showEditForm(@PathVariable int studentId, Model model) { model.addAttribute("student", studentService.findStudentById(studentId)); return "updateStudent"; } // 处理更新 @RequestMapping("/update") public String updateStudent(Student student) { studentService.updateStudent(student); return "redirect:/findStudents"; } // 按班级查询 @RequestMapping("/by-class") public String getByClass(@RequestParam String className, Model model) { model.addAttribute("students", studentService.getStudentsByClass(className)); return "student/list"; } }检查代码是否存在错误
06-11
用户注册后可以发布博文 可以 package com.example.blog.controller; import com.example.blog.dto.UserDto; import com.example.blog.model.User; import com.example.blog.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; // 用户注册页面 @GetMapping("/register") public String showRegistrationForm(Model model) { model.addAttribute("user", new UserDto()); return "user/register"; } // 处理用户注册 @PostMapping("/register") public String registerUser(@Valid @ModelAttribute("user") UserDto userDto, BindingResult result, Model model) { if (result.hasErrors()) { return "user/register"; } if (userService.findByUsername(userDto.getUsername()) != null) { model.addAttribute("usernameError", "用户名已存在"); return "user/register"; } if (userService.findByEmail(userDto.getEmail()) != null) { model.addAttribute("emailError", "邮箱已被注册"); return "user/register"; } userService.save(userDto); return "redirect:/user/login?registered"; } // 用户登录页面 @GetMapping("/login") public String showLoginForm() { return "user/login"; } // 用户个人中心 @GetMapping("/profile") public String showProfile(Model model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); User user = userService.findByUsername(username); model.addAttribute("user", user); return "user/profile"; } // 更新用户信息 @PostMapping("/profile/update") public String updateProfile(@ModelAttribute("user") User user) { userService.update(user); return "redirect:/user/profile?updated"; } // 管理员查看所有用户 @GetMapping("/admin/list") public String listUsers(Model model) { model.addAttribute("users", userService.findAll()); return "user/list"; } // 管理员删除用户 @PostMapping("/admin/delete/{id}") public String deleteUser(@PathVariable Long id) { userService.delete(id); return "redirect:/user/admin/list?deleted"; } } 为发布的博文创建标签 用户登录后可以评论博文 管理员可以管理博文 删除博文 最后提交 sql结构+源代码+答辩ppt(一个人讲解项目)
06-19
@Controller("backendFeedbackController") public class FeedbackController extends BaseController { @Autowired private FeedbackService feedbackService; /** * 进入反馈管理页面 */ @RequestMapping("/admin/feedback") public String feedback(@RequestParam(value = "page",defaultValue = "1")Long pageNumber, @RequestParam(value = "size",defaultValue = "6")Long pageSize, Model model){ Page page = PageUtil.initMpPage(pageNumber,pageSize); Feedback condition = new Feedback(); // 如果不是管理员,只查询自己的反馈 if(!loginUserIsAdmin()){ condition.setUserId(getLoginUserId()); } Page<Feedback> feedbackPage = feedbackService.findAll(page,condition); model.addAttribute("pageInfo",feedbackPage); model.addAttribute("pagePrefix","/admin/feedback?"); model.addAttribute("tab","feedback-list"); model.addAttribute("isAdmin",loginUserIsAdmin()); return "admin/feedback-list"; } /** * 回复反馈 */ @RequestMapping(value = "/admin/feedback/reply/submit",method = RequestMethod.POST) @ResponseBody public JsonResult replySubmit(Feedback feedback){ feedbackService.update(feedback); return JsonResult.success("保存成功"); } /** * 删除反馈 */ @RequestMapping("/admin/feedback/delete") @ResponseBody public JsonResult deleteFeedback(@RequestParam("id")Long id){ try{ Feedback feedback = feedbackService.get(id); if(feedback==null){ return JsonResult.error("反馈不存在"); } if(!loginUserIsAdmin() && !Objects.equals(feedback.getUserId(),getLoginUserId())){ return JsonResult.error("没有权限删除,这不是你的反馈"); } feedbackService.delete(id); }catch (Exception e){ return JsonResult.error("删除反馈失败"); } return JsonResult.success("删除反馈成功"); } }
06-11
实验09 SpringBoot 用户管理实战(JPA) 【实验目的及要求】 1. 掌握 Spring Boot 整合JPA 实现数据 CRUD(增删改查); 2. 掌握 MVC 分层架构(Controller→Service→Mapper) 3. 学会前后端数据交互:Thymeleaf 模板 4. 掌握密码加密等基础安全处理 5. 要求所有回答的文本格式:五号,宋体、1.5倍行距,保留段单元格背景。 【实验步骤】 1、 导入jpademo项目框架,添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> <!-- 使用最新的版本号 --> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 2、 实体类 package com.example.demo.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table(name="user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; // 构造函数、getter和setter public User() {} public User(String name, int age) { this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } 3、 Repository package com.example.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import com.example.demo.entity.User; public interface UserRepository extends JpaRepository<User, Long> { List<User> findByName(String name); } 4、 Controller package com.example.demo.controller; import java.util.List; import java.util.Optional; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.example.demo.entity.User; import com.example.demo.repository.UserRepository; @Controller public class UserController { private final UserRepository userRepository; public UserController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping("/users") public String listUsers(Model model) { List<User> users = userRepository.findAll(); model.addAttribute("users", users); return "users"; } @GetMapping("/users/new") public String showCreateForm(Model model) { model.addAttribute("user", new User()); return "create_user"; } @PostMapping("/users") public String createUser(@ModelAttribute User user) { userRepository.save(user); return "redirect:/users"; } @GetMapping("/users/{id}/edit") public String showEditForm(@PathVariable Long id, Model model) { Optional<User> userOptional = userRepository.findById(id); if (userOptional.isPresent()) { model.addAttribute("user", userOptional.get()); return "edit_user"; } else { return "redirect:/users"; } } @PostMapping("/users/{id}") public String updateUser(@PathVariable Long id, @ModelAttribute User user) { user.setId(id); userRepository.save(user); return "redirect:/users"; } @GetMapping("/users/{id}/delete") public String deleteUser(@PathVariable Long id) { userRepository.deleteById(id); return "redirect:/users"; } @GetMapping("/findbyname") public String findbyname(@RequestParam(name = "nameToFind", required = false) String name, Model model) { System.out.println("received query:" + name); List<User> users = userRepository.findByName(name); model.addAttribute("users", users); return "findbyname"; } @GetMapping("/findbyname2/{name}") public String findbyname2(@PathVariable String name, Model model) { System.out.println("received query2:" + name); List<User> users = userRepository.findByName(name); model.addAttribute("users", users); return "findbyname"; } } 5、 前端页面 增加用户: <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Create User</title> </head> <body> <h1>Create New User</h1> <form action="/users" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br> <label for="age">Age:</label> <input type="number" id="age" name="age" required><br> <input type="submit" value="Create User"> </form> </body> </html> 编辑用户: <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Edit User</title> </head> <body> <h1>Edit User</h1> <form action="/users/{id}" th:action="@{'/users/' + ${user.id}}" method="post"> <input type="hidden" name="id" th:value="${user.id}"> <label for="name">Name:</label> <input type="text" id="name" name="name" th:value="${user.name}" required><br> <label for="age">Age:</label> <input type="number" id="age" name="age" th:value="${user.age}" required><br> <input type="submit" value="Update User"> </form> </body> </html> 列出所有用户: <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User List</title> </head> <body> <h1>User List</h1> <table border="1"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Actions</th> </tr> </thead> <tbody> <tr th:each="user : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td> <a th:href="@{/users/{id}/edit(id=${user.id})}">Edit</a> <a th:href="@{/users/{id}/delete(id=${user.id})}" onclick="return confirm('Are you sure you want to delete this user?')">Delete</a> </td> </tr> </tbody> </table> <a href="/users/new">Create New User</a> <form action="/findbyname" method="get"> <label for="nameToFind"> Find By Name:</label> <input type="text" id="nameToFind" name="nameToFind" required><br> <input type="submit" value="FindByname"> </form> </body> </html> 按名字查找: <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>findbyname list</title> </head> <body> <h1>User List</h1> <ul> <li th:each="user:${users}"> Name:<span th:text="${user.name}"></span>,Age:<span th:text="${user.age}"></span> </li> </ul> <form action="/users" method="get"> <input type="submit" value="Back to List User"> </form> </body> </html> 6、 SQL脚本 -- Server version 8.0.41 drop database if exists userdb; create database if not exists userdb; use userdb; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint NOT NULL AUTO_INCREMENT, `age` int NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; insert into user(age,name) values(21,'Bob'); insert into user(age,name) values(22,'James'); insert into user(age,name) values(38,'张三'); insert into user(age,name) values(45,'李四'); insert into user(age,name) values(29,'Eileen'); 7、 测试结果截图输出 (1)列出用户清单,截图: (2)修改用户信息,截图: (3)删除用户,截图: (4)扩展功能:为用户表添加 “性别、邮箱、手机号,角色” 字段,实现新增和编辑功能,采用Lombok自动添加getter和setter方法: 修改的代码: 运行截图:
最新发布
11-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值