Saturday 6 September 2014

Add ServletRequestAttributeListener using WebListener


import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ReqAttrListener implements ServletRequestAttributeListener {

    @Override
    public void attributeAdded(ServletRequestAttributeEvent e) {
        System.out.println(e.getName() +" Added");
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent e) {
        System.out.println(e.getName() +" Removed");
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent e) {
        System.out.println(e.getName() +" Replaced");
  }
}

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns = {"/SampleApp"})
public class SampleApp extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException{
        try(PrintWriter out = res.getWriter()){
           req.setAttribute("name", "Krishna");
           req.setAttribute("name", "Arjun");
           req.removeAttribute("name");
        }
    }
}

Run ' SampleApp', server console has messages like below.

Info:   name Added
Info:   name Replaced
Info:   name Removed



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment