Answer the question
In order to leave comments, you need to log in
How to pass "delete" button click from .jsp file to servlet to delete data from database by id?
there is a UserDaoJdbcImpl class that implements the UsersDao interface with 5 methods: find, findAll ,delete, update.
public class UserDaoJdbcImpl implements UsersDao{
private final String SQL_DELETE =
"DELETE FROM data_user WHERE id = ?";
public void delet(Integer id) {
try {
PreparedStatement statement = connection.prepareStatement(SQL_DELETE);
statement.setLong(1, Long.valueOf("id"));
statement.executeUpdate();
}catch (SQLException e)
{
throw new IllegalStateException(e);
}
}
}
<c:forEach items="${usersFromServer}" var = "user">
<tr>
<td class=w3-round-small>${user.firstName}</td>
<td>${user.lastName}</td>
<td>Пока нету даты</td>
<td><form action = "" method="post">
<input type="hidden" name="id" value="${user.firstName}">
<input type="hidden" name="name" value="${user.lastName}">
<input type="submit" value="Изменить" >
</form>
<form method="post" action="/users">
<button type="submit" name="delete" value="${user.id}">delete</button>
</form></td>
</tr>
</c:forEach>
public class ListServlet extends HttpServlet {
private UsersDao usersDao;
@Override
public void init() throws ServletException{
Properties properties = new Properties();
DriverManagerDataSource dataSource = new DriverManagerDataSource();
try{
properties.load(new FileInputStream(getServletContext().getRealPath("/WEB-INF/classes/test-dao/db.properties")));
String dbUrl = properties.getProperty("db.url");
String dbUsername = properties.getProperty("db.username");
String dbpassword = properties.getProperty("db.password");
String driverClassName = properties.getProperty("db.driverClassName");
dataSource.setUrl(dbUrl);
dataSource.setUsername(dbUsername);
dataSource.setPassword(dbpassword);
dataSource.setDriverClassName(driverClassName);
usersDao = new UserDaoJdbcImpl(dataSource);
}
catch (IOException e){
throw new IllegalStateException(e);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> users = usersDao.findAll();
req.setAttribute("usersFromServer",users);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("views/users.jsp");
requestDispatcher.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String delete = request.getParameter("delete");
if (delete != null) {
usersDao.delet(Integer.valueOf(request.getParameter(delete)));
}
response.sendRedirect(request.getContextPath() + "/users");
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question