package vs;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet(urlPatterns = { "/HelloWorld", "/vs", "/hello" })
public class HelloWorld extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = -3570303195316235943L;
	private Integer counter = 0;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public HelloWorld() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html><head><title>HTTPRequest Inhalte ausgeben</title></head><body>");
		// Header
		out.println("<h1>Header</h1><ul>");
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = headerNames.nextElement();
			out.println("<li>" + headerName + ": " + request.getHeader(headerName));
		}
		out.println("</ul>");

		// Parameter
		out.println("<h1>Parameter</h1><ul>");
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			out.println("<li>" + parameterName + ": " + request.getParameter(parameterName));
		}
		out.println("</ul>");

		// Zugriffszähler
		out.println("<h1>Zugriffsz&auml;hler</h1><ul>");
		synchronized (this.counter) {
			if (this.counter != null) {
				this.counter += 1;
			} else {
				this.counter = 1;
			}
			out.println("<p>dies war Aufruf Nr. " + this.counter);
		}

		out.println("</body>");
		out.flush();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
