用MVC+layui+MySql写一个一张表的增删改查
时间: 2023-05-17 07:04:49 浏览: 107
非常感谢您的提问!以下是一个使用MVC、layui和MySql实现一张表的增删改查的示例代码:
1. 创建数据库表
首先,我们需要在MySql中创建一个名为“users”的表,包含以下字段:
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
age int(11) NOT NULL,
email varchar(255) NOT NULL,
PRIMARY KEY (id)
2. 编写后端代码
接下来,我们可以使用Java和Spring MVC框架编写后端代码。以下是一个简单的UserController类,它包含了处理增删改查请求的方法:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) {
List<User> userList = userService.getAllUsers();
model.addAttribute("userList", userList);
return "user/list";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute("user", new User());
return "user/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute("user") User user) {
userService.addUser(user);
return "redirect:/user/list";
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String edit(@PathVariable("id") int id, Model model) {
User user = userService.getUserById(id);
model.addAttribute("user", user);
return "user/edit";
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String edit(@ModelAttribute("user") User user) {
userService.updateUser(user);
return "redirect:/user/list";
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable("id") int id) {
userService.deleteUser(id);
return "redirect:/user/list";
}
}
3. 编写前端代码
最后,我们可以使用layui框架编写前端代码。以下是一个简单的用户列表页面:
<table class="layui-table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{{#each userList}}
<tr>
<td>{{this.id}}</td>
<td>{{this.name}}</td>
<td>{{this.age}}</td>
<td>{{this.email}}</td>
<td>
<a href="/user/edit/{{this.id}}" class="layui-btn layui-btn-sm">编辑</a>
<a href="/user/delete/{{this.id}}" class="layui-btn layui-btn-sm layui-btn-danger">删除</a>
</td>
</tr>
{{/each}}
</tbody>
</table>
4. 总结
以上就是一个使用MVC、layui和MySql实现一张表的增删改查的示例代码。希望对您有所帮助!
阅读全文