以SSM框架为基础的JAVA项目编写代码
时间: 2024-03-23 12:40:17 浏览: 67
好的,下面是一个基于SSM框架的Java项目的代码示例,供参考:
1. 实体类代码示例:
```java
public class User {
private int id;
private String username;
private String password;
// 省略 getter 和 setter 方法
}
```
2. DAO层代码示例:
```java
public interface UserDao {
User getUserById(int id);
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
```java
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public User getUserById(int id) {
return sqlSessionTemplate.selectOne("getUserById", id);
}
public void addUser(User user) {
sqlSessionTemplate.insert("addUser", user);
}
public void updateUser(User user) {
sqlSessionTemplate.update("updateUser", user);
}
public void deleteUser(int id) {
sqlSessionTemplate.delete("deleteUser", id);
}
}
```
3. Service层代码示例:
```java
public interface UserService {
User getUserById(int id);
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User getUserById(int id) {
return userDao.getUserById(id);
}
public void addUser(User user) {
userDao.addUser(user);
}
public void updateUser(User user) {
userDao.updateUser(user);
}
public void deleteUser(int id) {
userDao.deleteUser(id);
}
}
```
4. Controller层代码示例:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/get/{id}")
@ResponseBody
public User getUserById(@PathVariable("id") int id) {
return userService.getUserById(id);
}
@RequestMapping("/add")
public String addUser(User user) {
userService.addUser(user);
return "redirect:/user/list";
}
@RequestMapping("/update")
public String updateUser(User user) {
userService.updateUser(user);
return "redirect:/user/list";
}
@RequestMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") int id) {
userService.deleteUser(id);
return "redirect:/user/list";
}
}
```
以上代码示例仅供参考,实际项目中可能需要根据具体需求进行调整和优化。
阅读全文