javaweb实现增加修改的核心代码包括实体类、Dao和servlet、service的
时间: 2023-12-27 07:04:08 浏览: 270
servlet+jsp+bean+dao
这里是一个简单的示例代码,实现了一个用户管理系统的增删改查功能,包括实体类User、Dao层UserDao、Service层UserService和Servlet层UserServlet。
User实体类:
```java
public class User {
private int id;
private String name;
private int age;
private String gender;
// 省略getter和setter方法
}
```
UserDao层:
```java
public class UserDao {
// 添加用户
public boolean addUser(User user) {
// 数据库操作
}
// 根据id查询用户
public User getUserById(int id) {
// 数据库操作
}
// 更新用户信息
public boolean updateUser(User user) {
// 数据库操作
}
// 删除用户
public boolean deleteUser(int id) {
// 数据库操作
}
}
```
UserService层:
```java
public class UserService {
private UserDao userDao = new UserDao();
// 添加用户
public boolean addUser(User user) {
return userDao.addUser(user);
}
// 根据id查询用户
public User getUserById(int id) {
return userDao.getUserById(id);
}
// 更新用户信息
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
// 删除用户
public boolean deleteUser(int id) {
return userDao.deleteUser(id);
}
}
```
UserServlet层:
```java
public class UserServlet extends HttpServlet {
private UserService userService = new UserService();
// 处理添加用户请求
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String gender = request.getParameter("gender");
User user = new User();
user.setName(name);
user.setAge(age);
user.setGender(gender);
boolean result = userService.addUser(user);
if (result) {
response.sendRedirect("success.jsp");
} else {
response.sendRedirect("error.jsp");
}
}
// 处理更新用户请求
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String gender = request.getParameter("gender");
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
user.setGender(gender);
boolean result = userService.updateUser(user);
if (result) {
response.sendRedirect("success.jsp");
} else {
response.sendRedirect("error.jsp");
}
}
// 处理删除用户请求
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
boolean result = userService.deleteUser(id);
if (result) {
response.sendRedirect("success.jsp");
} else {
response.sendRedirect("error.jsp");
}
}
// 处理查询用户请求
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User user = userService.getUserById(id);
// 将user对象传递给jsp页面进行显示
request.setAttribute("user", user);
request.getRequestDispatcher("user.jsp").forward(request, response);
}
}
```
以上代码仅供参考,实际开发中需要根据具体需求进行修改和完善。
阅读全文