MainServlet.java Source code

Java tutorial

Introduction

Here is the source code for MainServlet.java

Source

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MainServlet extends HttpServlet {

    int count;

    public void init() throws ServletException {
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader("InitDestroyCounter.initial");
            bufferedReader = new BufferedReader(fileReader);
            String initial = bufferedReader.readLine();
            count = Integer.parseInt(initial);
            return;
        } catch (Exception ignored) {
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException ignored) {
            }
        }
        String initial = getInitParameter("initial");
        try {
            count = Integer.parseInt(initial);
            return;
        } catch (NumberFormatException ignored) {
        }
        count = 0;
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/plain");
        PrintWriter out = res.getWriter();
        count++;
        out.println("Since the beginning, this servlet has been accessed " + count + " times.");
    }

    public void destroy() {
        saveState();
    }

    public void saveState() {
        // Try to save the accumulated count
        FileWriter fileWriter = null;
        PrintWriter printWriter = null;
        try {
            fileWriter = new FileWriter("InitDestroyCounter.initial");
            printWriter = new PrintWriter(fileWriter);
            printWriter.println(count);
            return;
        } catch (IOException e) { // problem during write
            // Log the exception. See Chapter 5.
        } finally {
            // Make sure to close the file
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }
}