Hello everyone, today we will see how to write and compile our
GreetingServlet class. In the previous part of the series we saw the code template of our servlet class. Did you notice the
doGet() method body ? There are only two comments and nothing else is written in the method body. Before start writing the code we have to take care of a few things like defending the invalid inputs, making up the result based on the valid and invalid inputs etc.
Understanding the inputs
The input to our
doGet() method comes via the request. Yes – The parameter and value pair the client sent to the server while requesting is the input. Here the input the client sent to the server is any random number from the set (0, 1, 2). So two things are clear here – the input is an integer and its range.
Since we are clear about the input. Now think about the
doGet() method. We first write a defensive code to check if the input meet the expectation – a random number from set (0, 1, 2). The server will send a response to the client with a message – “Oops! invalid input.” if the input do not meet the expectations.
Making up the response
There are many methods available in
HttpServletResponse class and to move forward with our development we need to two methods
setContentType() and getWriter(). The
setContentType() method takes
String as argument and it is used to set the content type. Say “text/html” if we are going to put html content in the response. Alright – what is the use of second method ? Here we have to sent a text message with some opening and closing HTML tags. This is simply character data and to send this we need a
PrintWriter object. We accquire the
PrintWriter object from the response object by using
Okay! we got the
PrintWriter object. Now what ? We have to put our message (greetings if inputs are fine, error message if input is invalid). Once we accquire the
PrintWriter object, we use the
write() method to put the text in the response 🙂
If we open something, we have to close the same. The samething we have to do in the case of
PrintWriter object we retrived from response – close it when it is done.
The complet code is given below…
Aah wait! We missed one thing. How do we read the parameter value from the request object ? For this we need the parameter name which is “randomNumber” and a method called
getParameter() which accept the parameter name and return the the value. This method is available in the request object.
Alright lets go through the code!
The code above take care of every possible scenario we discussed above and set the message accordingle 🙂
Alright then. I hope everyone understood the below discussed things. We will see how to compile the
GreetingServlet.java file and use it in the web application in the next and final part of Inot the Web.
Please post your thoughts and comments here 🙂