Ok, you can browse complete code at my GitHub account. It is working but I would personally used JPA for persistence.
Let start with controller, which contains doPost
method. It just takes request parameters, constructs some bean and calls DAO to persist it to database. Once done, it sets a bean as request attribute and dispatches call to jsp. It means that once you open this jsp again, this bean will be not gone. Use session to store it across multiple calls.
public class Controller extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String phone = request.getParameter("phone");
// todo check parameters
User user = new User(name, phone);
DAO dao = new DAO();
dao.saveUser(user);
request.setAttribute("USER", user);// consider using session
// TODO handle errors
RequestDispatcher dispatcher = request.getRequestDispatcher("register/index.jsp");
dispatcher.forward(request, response);
}
}
web.xml is easy:
<servlet>
<servlet-name>RegistrationController</servlet-name>
<servlet-class>cz.literak.sandbox.so.register.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationController</servlet-name>
<url-pattern>/RegistrationController</url-pattern>
</servlet-mapping>
DAO uses old plain JDBC to store the object in database table. I would favour using DataSource instead.
static {
try {
Class.forName("org.mariadb.jdbc.Driver");
// Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public User findUser(String phone) {
// todo
return null;
}
// DDL: CREATE TABLE user (name VARCHAR(100), phone VARCHAR(100))
public boolean saveUser(User user) throws ServletException {
try (
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "secret");
PreparedStatement ps = con.prepareStatement("INSERT INTO user VALUES(?,?)"))
{
ps.setString(1, user.getName());
ps.setString(2, user.getPhone());
return ps.execute();
} catch (SQLException e) {
throw new ServletException("DB operation failed", e);
}
}
And finally jsp. It just checks if USER exists and then either displays registration form or welcome message.
<c:choose>
<c:when test="${USER == null}">
<form action="${pageContext.request.contextPath}/RegistrationController" method="post">
<table>
<tr>
<td>User name</td>
<td><input type="text" name="name" ></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</c:when>
<c:otherwise>
Welcome <c:out value="${USER.name}"/>
</c:otherwise>
</c:choose>
I hope that you will not delete this question as it took me substantial amount of time to answer.