CounterServer.java Source code

Java tutorial

Introduction

Here is the source code for CounterServer.java

Source

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

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

public class CounterServer extends HttpServlet {
    static final String COUNTER_KEY = "Counter.txt";

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(true);
        int count = 1;
        Integer i = (Integer) session.getAttribute(COUNTER_KEY);
        if (i != null) {
            count = i.intValue() + 5;
        }
        session.setAttribute(COUNTER_KEY, new Integer(count));
        DataInputStream in = new DataInputStream(req.getInputStream());
        resp.setContentType("application/octet-stream");
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(byteOut);
        out.writeInt(count);
        out.flush();
        byte[] buf = byteOut.toByteArray();
        resp.setContentLength(buf.length);
        ServletOutputStream servletOut = resp.getOutputStream();
        servletOut.write(buf);
        servletOut.close();
    }
}