Reputation: 4988
i have the following code,
public class HttpAdapter extends HttpServlet {
private static final long serialVersionUID = 1L;
static Logger l = Logger.getLogger(HttpAdapter.class.getName());
public HttpAdapter() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
Layout ll = new SimpleLayout();
Appender a = new FileAppender();
a = new FileAppender(ll,"C:\\Users\\Vasanth\\Desktop\\JDlogs\\my.txt");
l.info(request.getRemoteHost());
l.addAppender(a);
String loc = DTO.findMyLocation();
l.info(loc);
l.info(this.getClass()+" >>>>>>>>>>>>>>task complete");
l.info(request.getRemoteHost());
}catch(Exception e){
e.printStackTrace();
}finally{
getServletContext().getRequestDispatcher("/JSP/done.jsp").forward(request, response);
}
}
//F:\\home\\WorkSpace\\Jdfront1\\webapps\\JSP\\
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Here's the unusual thing: whenever I am making a request to this servlet from a browser thru a jsp page that looks like,
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>jdHome</title>
</head>
<body>
<header>hello!!</header>
<section>
<form action="http://192.168.1.101:90/Jdfront1/hello">
<label>Topic :</label><input type="text" name="topic"/><br>
<label>Number of pages :</label><input type="text" name="Nopages"/><br>
<label>URL :</label><input type="text" name="link"/><br>
<label>isRange :</label><input type="text" name="range"/><br>
<input type="submit">
</form>
</section>
when the request is made for the first time it runs all fine and the logs are also coming once only,
but when I make a 2nd request to the same servlet from the jsp, the entire program runs two times. The logs come two times, like if I have a System.out.println("hello")
, it prints 'hello' two times. When I make the 3rd request, it prints 3 times and goes on! Is there something I am missing in the dispatcher that I have used to forward? I have tried everywhere, no problem similar or even close to this is reported anywhere.
Upvotes: 0
Views: 165
Reputation: 139921
Why are you configuring your logger inside the doGet()
method?
As you've pointed out, this method is executed on each request.
However, you probably only want to configure your logger and it's appenders once. A better place for this logic would be inside the Servlet's init method (the best place for this logic would be in an external XML or properties file).
The reason why you are seeing multiple copies of the log line is because by the time you have received the fourth request, you've added four appenders to your logger. The logger framework doesn't know that these appenders are duplicates of each other, and sends the log message to every one.
Upvotes: 6