Saturday, October 13, 2012

ServletContextListener



public interface ServletContextListener extends java.util.EventListener

Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

Methods
void
contextDestroyed(ServletContextEvent sce)
          Notification that the servlet context is about to be shut down.
 void
contextInitialized(ServletContextEvent sce)
          Notification that the web application initialization process is starting.


Web.xml


  servlet_demo
  
    index.html
    
  
  
  
   com.jsl.servlet.StoreUsers
  
  
  
   viewUsers
   com.jsl.servlet.ViewUserList
  
  
   viewUsers
   /viewUsers
  

StoreUsers.java

package com.jsl.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class StoreUsers implements ServletContextListener {
 List list=new ArrayList();
 @Override
 public void contextDestroyed(ServletContextEvent event) {
  System.out.println("Context Detsroy method invoked");
  list=null;
 }

 @Override
 public void contextInitialized(ServletContextEvent event) {
  System.out.println("Context  initilized method invoked");
  
  
  list.add("Krish");
  list.add("Balu");
  list.add("Mani");
  ServletContext context=event.getServletContext();
  context.setAttribute("users", list);
  
 }

}

ViewUserList.java

package com.jsl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ViewUserList extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
   
   ServletContext context=getServletContext();
   
   resp.setContentType("text/html");
   PrintWriter out=resp.getWriter();
   
                  out.print("<html><head><title>Users list</title></head>");
                  out.print("<body>");
                  out.print("<h3> users list is </h3>");
                  out.print("<hr>");
                  List
                   users=(List) context.getAttribute("users");
                  for(String user:users){
                        out.print("<h5>"+user+"</h5>");
                  }
                  out.print("</body>");
                  out.print("</html>");
  }
}

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>


Insert title here


  Users List

</html>

http://localhost:8083/servlet_demo/



http://localhost:8083/servlet_demo/viewUsers




Same example in servlet 3.0


web.xml


 
 servlet_demo
  
   
    index.html
   
  

StoreUsers.java

package com.jsl.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
 

public class StoreUsers implements ServletContextListener {
 List list=new ArrayList();
 @Override
 public void contextDestroyed(ServletContextEvent event) {
  System.out.println("Context Detsroy method invoked");
  list=null;
 }

 @Override
 public void contextInitialized(ServletContextEvent event) {
  System.out.println("Context  initilized method invoked");
  
  
  list.add("Krish");
  list.add("Balu");
  list.add("Mani");
  ServletContext context=event.getServletContext();
  context.setAttribute("users", list);
  
 }

}

ViewUserList.java

package com.jsl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/viewUsers")

public class ViewUserList extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
   
   ServletContext context=getServletContext();
   
   resp.setContentType("text/html");
    PrintWriter out=resp.getWriter();
   
                  out.print("<html><head><title>Users list</title></head>");
                  out.print("<body>");
                  out.print("<h3> users list is </h3>");
                  out.print("<hr>");
                  List
                   users=(List) context.getAttribute("users");
                  for(String user:users){
                        out.print("<h5>"+user+"</h5>");
                  }
                  out.print("</body>");
                  out.print("</html>");
   
  }
}


ServletContextAttributeListener


public interface ServletContextAttributeListener extends java.util.EventListener

Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
package com.jsl.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/users")
public class UserServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
    ServletContext context=getServletContext();
    context.setAttribute("user1", "Krish");
    context.setAttribute("user2", "Krish");
    context.setAttribute("user3", "Balu");
    context.removeAttribute("user2");
    context.setAttribute("user3", "Balakrishna");
   }
}

package com.jsl.servlet;
import java.util.Date;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class UserListner implements ServletContextAttributeListener{
 @Override
 public void attributeAdded(ServletContextAttributeEvent event) {
   System.out.println("The attribute is added "+event.getName()+" "+new Date());
  
 }

 @Override
 public void attributeRemoved(ServletContextAttributeEvent event) {
  System.out.println("The attribute is removed "+event.getName()+" "+new Date());
  
 }

 @Override
 public void attributeReplaced(ServletContextAttributeEvent event) {
  System.out.println("The attribute is replaced "+event.getName()+" "+new Date());
  
 }



}
http://localhost:8083/servlet_demo/users

The servlet console display the notifications


Servlet Config and Context


ServletConfig:

A servlet configuration object used by a servlet container to pass information to a servlet during initialization. 

Methods of ServletConfig:

java.lang.String getInitParameter(java.lang.String name)
          
Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.

java.util.Enumeration getInitParameterNames()
     
Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.

ServletContext  getServletContext()

          Returns a reference to the ServletContext in which the caller is executing.
 
java.lang.String getServletName()

          Returns the name of this servlet instance.


To get the ServletConfig Object

        ServletConfig config = getServletConfig();




web.xml


Servlet_demo

index.html



  simpleServlet
  com.jsl.servlets.SimpleServlet
  
   driver
   oracle.jdbc.driver.OracleDriver
  


  simpleServlet
  /simple


SimpleServlet.java

packagecom.jsl.servlets;

importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletConfig;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
publicclassSimpleServletextendsHttpServlet {
 privatestaticfinallongserialVersionUID = 1L;
 protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
   ServletConfigconfig=getServletConfig();
   response.setContentType("text/html");
   PrintWriter out=response.getWriter();
   out.print("<html><head><title>View Dept Details</head>");
   out.print("<body>");
   String driver=config.getInitParameter("driver");
   out.print("

The Driver name is using servlet 3.0 :

"+driver); out.print("</body>"); out.print("</html>"); } protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { } }




             Servlet 3.0 the init parameters can be set by using the annotaions. we no need to configure in the web.xml



packagecom.jsl.servlets;

importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletConfig;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebInitParam;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
@WebServlet(
 urlPatterns={"/simple"},
 initParams={
   @WebInitParam(name="driver",value="jdbc.oracle.driver.OracleDrvier")
 }
)
publicclassSimpleServletextendsHttpServlet {
 privatestaticfinallongserialVersionUID = 1L;
 protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
   ServletConfigconfig=getServletConfig();
   response.setContentType("text/html");
   PrintWriter out=response.getWriter();
   out.print("<html><head><title>View Dept Details</head>");
   out.print("<body>");
   String driver=config.getInitParameter("driver");
   out.print("

The Driver name is using servlet 3.0 :

"+driver); out.print("</body>"); out.print("</html>"); } protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { } }


Servlet Context

public interface ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. 


The context parameters can be set in the web.xml

    <web-app> 
        <context-param>
               <param-name>driver</param-name>
               <param-value>oracle.jdbc.driver.OracleDriver</param-value>
          </context-param>
    </web-app>



To read this context-param

    ServletContext context=getServletContext();
    String dirver=context.getInitParam("driver");


Diffrence Between the ServletConfig and ServletContext 

ServletConfig
ServletContext
A servlet configuration object used by a servlet container to pass information to a servlet during initialization. 
A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
For each servlet there will one ServletConfig object
The entire web application will have one ServletContext Object
The parameters specified in web.xml inside the <servlet> tag
The paramemters are specified in web.xml inside <web-app>
These parameters can be read by using config.getInitParameter(“name”);
These parameters can be read by using context.getInitParameter(“name”);

Wednesday, October 10, 2012

Servlet RequestDispatcher

1.     RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
2.    The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
3.   This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

Method Summary

void forward(ServletRequest request, ServletResponse response)

      Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response.
      
      For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest    object has its path elements and parameters adjusted to match the path of the target resource.

      Forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

      The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be sub classes of the ServletRequestWrapper  or   ServletResponseWrapper classes that wrap them.



packagecom.jsl.servlet;
packagecom.jsl.servlet;
importjava.io.IOException;
importjavax.servlet.*;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    response.sendRedirect("index.html");
    
    request.getRequestDispatcher("/welcome").forward(request,response);
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
 }
}


      In this example the response has been committed, We are trying to forward to another servlet, It throws the IllegalStateException

Login.html

<!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
 
   
   
   
   
  
  
    
User Login E-Mail
* Password *
</html>

LoginServlet.java

packagecom.jsl.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.*;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.*;
@WebServlet("/login")
publicclassLoginServletextendsHttpServlet {

privatestaticfinallongserialVersionUID = 1L;
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
  RequestDispatcherrd=null;
  String email=request.getParameter("email");
  String password=request.getParameter("password");
  PrintWriter out=response.getWriter();
  response.setContentType("text/html");
  out.print("");
  out.print("<html><head>Login Page</head>");
  out.print("<body>");   
  if(email.equals(" ") &&password.equals(" ")){
   out.print("Please verify user name and password");
   rd=request.getRequestDispatcher("login.html");
   rd.include(request, response);
  }else{
   if(email.equals("admin@jsltech.com") &&password.equals("admin")){
    rd=request.getRequestDispatcher("welcome");
    rd.forward(request, response);
   }else{
   out.print("Please verify user name and password");
    rd=request.getRequestDispatcher("login.html");
    rd.include(request, response);
    }
   }
   
  out.print("</body>");
  out.print("</html>");
   
   
 }
protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
   doGet(request, response);
 }

}

Welcome.java

packagecom.jsl.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

@WebServlet("/welcome")
publicclass Welcome extendsHttpServlet {
 privatestaticfinallongserialVersionUID = 1L;
 protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
  PrintWriter out=response.getWriter();
  response.setContentType("text/html");
  out.print("");
  out.print("<html><head>Login Page</head>");
  out.print("<body>"); 
   out.print("

Welcome to JSL Tech

"); out.print("Login Page"); out.print("</body>"); out.print("</html>"); } }

When click on

http://localhost:8080/Servlet_Example/login.html







      If user name or password wrong, then along with the error message the login page will be included


      If user name and password correct then action will go to the welcome servlet and display the output…



void include(ServletRequest request, ServletResponse response)

             Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.

      The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

      The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be subclasses of theServletRequestWrapper or ServletResponseWrapper classes that wrap them.

      What is the difference between the include() and forward() methods?

include()
forward()
        The RequestDispatcherinclude() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.  
   The RequestDispatcherforward() method is used to show a different resource in place of the servlet that was originally called.
      If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored.
          The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
              The include() method is often used   to include common "boilerplate" text or template markup that may be included by many servlets.
              The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.


Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...