Handling user inputs using Servlets - Part 3

How to create servlet?

In previous two post we have learnt how to create forms and what are important things that needs to taken care of for proper form submission. From this post on wards we will be learning how to handle submitted form at server side in a servlet. I hope you have some knowledge of a servlet and if not then below is a short tutorial on "How to create Servlets".

In order to create a Servlet we need to create a Java Class first.

public class SignUpServlet{

}


This is a simle POJO (Plain Old Java Object), in order to convert this simple class to Servlet we need to extend this class from HttpServlet which is available in javax.servlet.http package.

import javax.servlet.http.HttpServlet;

public class SignUpServlet extends HttpServlet{

}


Now in order to make this servlet accessible through URL, we need to specify the path for this servlet which we can do using @WebServlet annotation which is available in javax.servlet.annotation package.

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;

@WebServlet("/sign_up.do")
public class SignUpServlet extends HttpServlet{

}


As we discussed in previous posts there are two methods through which we can submit our forms those are "GET" and "POST". In order to handle form at server side we need to define method for corresponding methods HHTP method which we have used in our forms. In brlow example I am showing implementation for both methods.

We have methods defined in our parent class(HttpServlet) for servlet, for hadling GET and POST requests, below are two methods :

doGet(HttpServletRequest request, HttpServletResponse response)
doPost(HttpServletRequest request, HttpServletResponse response)


We need to override one of these two for handling forms at server end.

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/sign_up.do")
public class SignUpServlet extends HttpServlet{


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}


This is how we create servlets. Above servlet code will be used in next post and will see how we can access form data at server end.

Continue to Part 4
Share:

No comments:

Post a Comment

Popular Posts

Recent Posts

Followers

Total Pageviews