How to transfer data from JSP to servlet when submitting HTML form

前端 未结 4 1115
陌清茗
陌清茗 2020-11-21 23:14

I have a JSP page with an HTML form:


4条回答
  •  失恋的感觉
    2020-11-22 00:09

    Create a class which extends HttpServlet and put @WebServlet annotation on it containing the desired URL the servlet should listen on.

    @WebServlet("/yourServletURL")
    public class YourServlet extends HttpServlet {}
    

    And just let point to this URL. I would also recommend to use POST method for non-idempotent requests. You should make sure that you have specified the name attribute of the HTML form input fields (,

    Submit button.

    Create a doPost() method in your servlet which grabs the submitted input values as request parameters keyed by the input field's name (not id!). You can use request.getParameter() to get submitted value from single-value fields and request.getParameterValues() to get submitted values from multi-value fields.

    @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;
        // ...
    }
    

    Do if necessary some validation and finally persist it in the DB the usual JDBC/DAO way.

    User user = new User(name, pass, roles);
    userDAO.save(user);
    

    See also:

    • HTML beginner tutorial
    • Our Servlets wiki page
    • doGet and doPost in Servlets
    • How do I call a specific Java method on click/submit event of specific button in JSP?
    • How perform validation and display error message in same form in JSP?
    • How can I retain HTML form field values in JSP after submitting form to Servlet?
    • How to upload files to server using JSP/Servlet?
    • Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
    • Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

提交回复
热议问题