Create a Simple Web Application Project From Eclipse Ide.
package com.app;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LinkTrack
*/
@WebServlet("/track")
public class LinkTrack extends HttpServlet {
private static Hashtable<String, Integer> links = new Hashtable<String, Integer>();
private static final long serialVersionUID = 1L;
String timestamp;
/**
* Default constructor.
*/
public LinkTrack() {
timestamp = new Date().toString();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String link = request.getParameter("link");
if(link == null || link.equals("")) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
request.getSession();
out.println("<html>");
out.println("<head>");
out.println("<title>Link Tracker Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Link Traced Since : "+ timestamp+"</p>");
if(links.size()!=0) {
Enumeration<String> keys = links.keys();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
int count = (Integer)links.get(key).intValue();
out.println("Key : "+key + " And Count : "+count);
}
}
else {
out.println("No Link Traced Yet</br>");
}
out.println("</body>");
out.println("</html>");
}else {
synchronized (link) {
Integer count = links.get(link);
if(count == null) {
links.put(link, new Integer(1));
}
else {
links.put(link, new Integer(1+count.intValue()));
}
}
response.sendRedirect(link);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
0 Comments