SSM框架用Ajax增删改查一个页面(简单易懂)
SSM(Spring + Spring MVC + MyBatis)框架是一种常用的Java EE架构,用于快速开发和部署企业级web应用程序。以下是使用SSM框架结合Ajax进行增删改查操作的一个简单示例。
首先,这里是一个简单的Spring MVC控制器:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String getUserList(Model model) {
List<User> userList = userService.findAll();
model.addAttribute("userList", userList);
return "userList";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String addUser(@RequestParam("name") String name, @RequestParam("age") int age) {
User user = new User(name, age);
userService.save(user);
return "success";
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
@ResponseBody
public String deleteUser(@PathVariable("id") int id) {
userService.delete(id);
return "success";
}
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ResponseBody
public String updateUser(@RequestParam("id") int id, @RequestParam("name") String name, @RequestParam("age") int age) {
User user = new User(id, name, age);
userService.update(user);
return "success";
}
}
这里是UserService和UserMapper(MyBatis)的简单实现:
public interface UserMapper {
List<User> findAll();
void save(User user);
void delete(int id);
void update(User user);
}
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findAll() {
return userMapper.findAll();
}
public void save(User user) {
userMapper.save(user);
}
public void delete(int id) {
userMapper.delete(id);
}
public void update(User user) {
userMapper.update(user);
}
}
以下是使用Ajax进行增删改查操作的JavaScript代码示例:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// 添加用户
$("#addUser").click(function(){
var name = $("#name").val();
var age = $("#age").val();
$.post("/user/add", {name: name, age: age}, function(response){
if(response === "success"){
alert("Use
评论已关闭