TY_BCS_A_JAVA_SLIP8



SLIP 8:
Write a servlet which counts how many times a user has visited a web page. If the user is visiting the page for the first time, display a welcome message. If the user is revisiting the page, display the number of times visited. (Use cookies)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HitCount extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie c[]=request.getCookies();
if(c==null)
 {
 Cookie cookie = new Cookie("count","1"); response.addCookie(cookie);
out.println("<h3>Welcome Servlet<h3>"+ "Hit Count:<b>1</b>");
}
else
{

int val=Integer.parseInt(c[0].getValue())+1; c[0].setValue(Integer.toString(val)); response.addCookie(c[0]); out.println("Hit Count:<b>"+val+"</b>");

}
 }
}

No comments:

Post a Comment