source file name: CookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/CookieServlet"})
public class CookieServlet extends HttpServlet
{
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<h1>Servlet Cookie program");
Cookie[] ck=request.getCookies();
int count=0;
if(ck!=null)
{
for(int i=0;i<ck.length;i++)
{
Cookie c=ck[i];
if(c.getName().equals("count"))
{
try
{
Integer num=new Integer(c.getValue());
count=num.intValue();
}
catch(NumberFormatException ex)
{}
}
}
}
count++;
response.addCookie(new Cookie("count",String.valueOf(count)));
out.println("<br> visitor number: "+count);
out.flush();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
0 Comments
Post a Comment