0

I have the following code in my jsp

<table>
    <c:forEach var="link" items="${weblinks}">
        <c:if test="${link.featured}">
            <tr>
                <td>
                    <span>${link.title} (Hits : ${link.numOfHits})
                        </span>

                    <span>
                        <a href="<c:url value='${link.url}'/>">${link.url}  </a></span><br></td>
            </tr>
        </c:if>
    </c:forEach>
</table>

Now i want that when any user click on the link the link opens and the url of link also goes to the servlet. I hava achieved the first functionality but how i'll get the url in servlet so that i can update the number of hits, a website link has recevied, in database?

Please help me. I have google it but don't get the answer. If javascript is used then please explain me java script code also?

Asma Ihsan
  • 131
  • 1
  • 3
  • 10

3 Answers3

1

Update

<a href="<c:url value='${link.url}'>
<c:param name="hits" value="${link.numOfHits}"/></c:url>">${link.url}  </a>

this will add a query string which has parameter number of hits which has the value of number of hits

On the servlet with request.getParameter("hits") you will get the number of hits on the servlet

Refer http://www.roseindia.net/jsp/simple-jsp-example/JSTLConstructingURLs.shtml

Hope this helps

Meherzad
  • 8,433
  • 1
  • 30
  • 40
  • The counter hits must be saved at application scope, not at request scope. – Luiggi Mendoza Feb 13 '13 at 06:05
  • You don't even mention it in your answer, how do you expect OP could just realize it? – Luiggi Mendoza Feb 13 '13 at 06:38
  • I just answer op question of passing the value from jsp to servlet. Also OP has not mentioned anything about the way the hit counter is working whether its page hit or user hit or anything about the counter – Meherzad Feb 13 '13 at 06:46
  • I have tried the above code but in servlet i am not getting the parameter "hits"? What i have to do now? @Meherzad – Asma Ihsan Feb 13 '13 at 09:37
0

I don't know how your links are created, but it looks like you will make a GET request to your servlets. Knowing this, each servlet should manage the counter hit for the page and since this value should be known for every user it will be best to save it in application scope rather than request or session. More of this here and How do servlets work? Instantiation, sessions, shared variables and multithreading.

I'll post a sample of jsp and servlet that handles a counter for a single link. You should be able to use it to handle your links as well.

index.jsp (other elements like <head> and <html> are wortheless for the example)

<body>
    Hit the button to add a value to the application counter
    <br />
    <form action="HitCounterServlet" method="GET">
        <input type="submit" value="Add counter hit" />
    </form>
    <br />
    Total hits: ${applicationScope['counter']}
</body>

HitCounterServlet

@WebServlet(name = "HitCounterServlet", urlPatterns = {"/HitCounterServlet"})
public class HitCounterServlet extends HttpServlet {

    private static final Object counterLock = new Object();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext context = request.getServletContext();
        updateHitCounter(context);
        String originalURL = "index.jsp";
        //in case you want to use forwarding
        //request.getRequestDispatcher(originalURL).forward(request, response);
        //in case you want to use redirect
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/" + originalURL));
    }

    private void updateHitCounter(ServletContext context) {
        //since more than a request can try to update the counter
        //you should protect the update using a synchronized block code
        synchronized(counterLock) {
            Integer counter = (Integer)context.getAttribute("counter");
            if (counter == null) {
                counter = 0;
            }
            counter++;
            context.setAttribute("counter", counter);
        }
    }
}

Try this in different browsers and you will see how the counter maintains the same state across them.


In order to save the counter hit in your database, you should just change the code in the updateHitCounter function for code that will connect to your database and execute the update statement to your database field.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • But the main problem i am facing is that there is no form submission in my code. And how i can get the value of url from jsp to servlet without submission of form? I need that when a user click on the link, the link opens in the users window and at the same time the value of url(that has clicked) is gone to servlet where i'll my self update the numberof hits for link. Have you any idea how i can get this? @Luiggi Mendoza – Asma Ihsan Feb 13 '13 at 09:44
  • @AsmaIhsan can you provide an example of your URLs and how did you managed to go open the link and go to the servlet at the same time? Note that this example of *form submission* is similar to access to `http://localhost//HitCounterServlet` in the URL since it's a GET request. – Luiggi Mendoza Feb 13 '13 at 19:49
-1

You can use cookies to record the number of page hits.

Code:

<%@ page import="java.io.*,java.util.*" %>
<%
   // Get session creation time.
   Date createTime = new Date(session.getCreationTime());
   // Get last access time of this web page.
   Date lastAccessTime = new Date(session.getLastAccessedTime());

   String title = "Welcome Back to my website";
   Integer visitCount = new Integer(0);
   String visitCountKey = new String("visitCount");
   String userIDKey = new String("userID");
   String userID = new String("ABCD");

   // Check if this is new comer on your web page.
   if (session.isNew()){
      title = "Welcome Guest";
      session.setAttribute(userIDKey, userID);
      session.setAttribute(visitCountKey,  visitCount);
   } 
   visitCount = (Integer)session.getAttribute(visitCountKey;
   visitCount = visitCount + 1;
   userID = (String)session.getAttribute(userIDKey);
   session.setAttribute(visitCountKey,  visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border="1" align="center"> 
<tr bgcolor="#949494">
   <th>Session info</th>
   <th>Value</th>
</tr> 
<tr>
   <td>id</td>
   <td><% out.print( session.getId()); %></td>
</tr> 
<tr>
   <td>Creation Time</td>
   <td><% out.print(createTime); %></td>
</tr> 
<tr>
   <td>Time of Last Access</td>
   <td><% out.print(lastAccessTime); %></td>
</tr> 
<tr>
   <td>User ID</td>
   <td><% out.print(userID); %></td>
</tr> 
<tr>
   <td>Number of visits</td>
   <td><% out.print(visitCount); %></td>
</tr> 
</table> 
</body>
</html>

Or you can implement a hit counter which makes use of Application Implicit object and associated methods getAttribute() and setAttribute().

<%
    Integer hitsCount = 
      (Integer)application.getAttribute("hitCounter");
    if( hitsCount ==null || hitsCount == 0 ){
       /* First visit */
       out.println("Welcome to my website!");
       hitsCount = 1;
    }else{
       /* return visit */
       out.println("Welcome back to my website!");
       hitsCount += 1;
    }
    application.setAttribute("hitCounter", hitsCount);
%>
<center>
<p>Total number of visits: <%= hitsCount%></p>

hope this helps..

Lucky
  • 16,787
  • 19
  • 117
  • 151
  • This is a bad example. OP's learning the right way and you're leading him/her to use scriplets. Please read [How to avoid Java Code in JSP-Files?](http://stackoverflow.com/a/3180202/1065197) – Luiggi Mendoza Feb 13 '13 at 06:13
  • ok thnks 4 pointing me that i ll review the code and update it with best solution which the OP is looking for.. – Lucky Feb 13 '13 at 13:10