In: Computer Science
Explain how it is that we build the “processRequest()” method in a Servlet class, when the Servlet interface requires us to write 3 methods(init(), service() and destroy()). Why don’t we have to build these 3 methods?
The "processReuest()" can be built without specifically writing the given 3 methods. The process for creation is mentioned below:
1. Add the following method declaration for processRequest(req, res). Add open and close parentheses ({, }) and position the cursor in between the parenthesis.
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
2. Declare a variable employeeList of the List type that contains Employee objects. Declare the variable gson to process Gson object.
List<Employee> employeeList = null;
3. Instantiate the employeeList object by invoking getEmployees method of EmployeeBean.
employeeList = employeeBean.getEmployees();
4. Check if the employeeList is not NULL
if (employeeList != null) {
5. Set the content type to “application/json”
response.setContentType("application/json");
6. Invoke the method toJson(…) and convert the employeeList to JSON.
Copygson.toJson(employeeList,
new TypeToken<ArrayList<Employee>>() {}.getType(),
response.getWriter());
7. End of if condition. Close the parenthesis (})
8. Add an else condition to cover the error scenario when the employeeList is empty.
Copyelse {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}