我有一个带有HTML表单的JSP页面:
<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>
如何在Servlet中获取这些数据并将其添加到数据库?
创建一个扩展的类,HttpServlet并@WebServlet在其上添加注释,其中包含servlet应该侦听的所需URL。
HttpServlet
@WebServlet
@WebServlet("/yourServletURL") public class YourServlet extends HttpServlet {}
然后只<form action> 指向该URL。我还建议对非幂等请求使用POST方法。您应该确保您所指定的nameHTML表单输入字段的属性(<input>,<select>,<textarea>和<button>)。这代表HTTP请求参数名称。最后,您还需要确保将感兴趣的输入字段包含在所需表单的内部,而不是外部。
<form action>
name
<input>
<select>
<textarea>
<button>
以下是各种HTML表单输入字段的一些示例:
<form action="${pageContext.request.contextPath}/yourServletURL" method="post"> <p>Normal text field. <input type="text" name="name" /></p> <p>Secret text field. <input type="password" name="pass" /></p> <p>Single-selection radiobuttons. <input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p> <p>Single-selection checkbox. <input type="checkbox" name="agree" /> Agree?</p> <p>Multi-selection checkboxes. <input type="checkbox" name="role" value="USER" /> User <input type="checkbox" name="role" value="ADMIN" /> Admin</p> <p>Single-selection dropdown. <select name="countryCode"> <option value="NL">Netherlands</option> <option value="US">United States</option> </select></p> <p>Multi-selection listbox. <select name="animalId" multiple="true" size="2"> <option value="1">Cat</option> <option value="2">Dog</option> </select></p> <p>Text area. <textarea name="message"></textarea></p> <p>Submit button. <input type="submit" name="submit" value="submit" /></p> </form>
doPost()在您的Servlet中创建一个方法,该方法将提交的输入值作为由输入字段name( 不是 id!)键入的请求参数。您可以用于request.getParameter()从单值字段request.getParameterValues()获取提交的值,以及从多值字段获取提交的值。
doPost()
id
request.getParameter()
request.getParameterValues()
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String pass = request.getParameter("pass"); String gender = request.getParameter("gender"); boolean agree = request.getParameter("agree") != null; String[] roles = request.getParameterValues("role"); String countryCode = request.getParameter("countryCode"); String[] animalIds = request.getParameterValues("animalId"); String message = request.getParameter("message"); boolean submitButtonPressed = request.getParameter("submit") != null; // ... }
进行必要的验证,最后以常规的JDBC / DAO方式将其持久保存在数据库中。
User user = new User(name, pass, roles); userDAO.save(user);