Saturday, 6 September 2014

Add ServletRequestAttributeListener using Deployment Descriptor

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;

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

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <listener>
        <description>RequestAttributeListener</description>
        <listener-class>ReqAttrListener</listener-class>
    </listener>
</web-app>

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