I have a JSP page with an HTML form:
<form action="SERVLET">
<input type="text" name="name"/><br>
<input type="text" name="group"/>
<input type="text" name="pass"/>
<input type="submit" value="submit">
</form>
How to obtain these data in a servlet and add them to database?
Create a class which extends
HttpServletand put@WebServletannotation on it containing the desired URL the servlet should listen on.And just let
<form action>point to this URL. I would also recommend to use POST method for non-idempotent requests. You should make sure that you have specified thenameattribute of the HTML form input fields (<input>,<select>,<textarea>and<button>). This represents the HTTP request parameter name. Finally, you also need to make sure that the input fields of interest are enclosed inside the desired form and thus not outside.Here are some examples of various HTML form input fields:
Create a
doPost()method in your servlet which grabs the submitted input values as request parameters keyed by the input field’sname(notid!). You can userequest.getParameter()to get submitted value from single-value fields andrequest.getParameterValues()to get submitted values from multi-value fields.Do if necessary some validation and finally persist it in the DB the usual JDBC/DAO way.
See also: