当用户点击链接时,如何从jsp获取url值到servlet?

时间:2013-02-13 03:33:45

标签: jsp servlets

我在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>

现在我希望当任何用户点击链接时,链接打开,链接的url也会转到servlet。我hava实现了第一个功能但是我如何获得servlet中的url以便我可以在数据库中更新点击次数,网站链接已经收到?

请帮帮我。我有谷歌,但没有得到答案。如果使用javascript那么请解释我的java脚本代码吗?

3 个答案:

答案 0 :(得分:1)

更新

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

这将添加一个查询字符串,其参数编号为hits,其值为hits

在具有request.getParameter("hits")的servlet上,您将获得servlet上的命中数

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

希望这有帮助

答案 1 :(得分:0)

我不知道你的链接是如何创建的,但看起来你会向你的servlet发出GET请求。知道了这一点,每个servlet都应该管理页面的计数器命中,因为每个用户都应该知道这个值,所以最好将它保存在应用程序范围而不是请求或会话中。更多hereHow do servlets work? Instantiation, sessions, shared variables and multithreading

我将发布一个jsp和servlet样本,用于处理单个链接的计数器。您也应该能够使用它来处理您的链接。

index.jsp(其他元素,例如<head><html>仍为此示例)

<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);
        }
    }
}

在不同的浏览器中尝试此操作,您将看到计数器如何在它们之间保持相同的状态。


为了保存数据库中的计数器命中,您应该只更改updateHitCounter函数中的代码,以获取将连接到数据库并将update语句执行到数据库字段的代码。

答案 2 :(得分:-1)

您可以使用Cookie记录网页点击次数。

代码:

<%@ 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>

或者你可以实现一个命中计数器,它使用Application Implicit对象和相关方法getAttribute()和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>

希望这会有所帮助..