I would like to do the servlet program for the below,"create a servlet named com.SessServlet.If you are accessing the servlet in a new browser then
for the first time it should display ‘Welcome, Newcomer’. When you refresh the same page it should display‘Welcome Back. You are visiting the page for <no of times you have refreshed the page>
’."
`package com.SessServlet122;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessServlet extends HttpServlet
{
pub开发者_StackOverflow社区lic void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
int i;
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession();
i=0;
if(hs.isNew())
{
pw.println("Hello:::"+i);
}
else
{ i++;
pw.println("Welcome Back:Ur entry count is::::"+i);
}
pw.close();
}
}`
But this code is not working properly. How to solve this? Thanks in advance.
You should store that counter as a sessionVariable
, that way you will get it work.
You need this line after your pw.close();
call:
hs.setAttribute("counter", i);
Also, the initialization of your counter i
should look like this:
Integer i = (Integer)hs.getAttribute("counter");
if (i == null)
i = 0;
Hint:
- Create a Servlet
- From
service()
method retrieve session and set an attribute in session if its there else set ans display appropriate message - On jsp use JSTL to display the counter, for example : if the attribute set was hitCount then on jsp use
${hitCount}
精彩评论