Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.75 KB | None | 0 0
  1. // http://ocejwcd.wikidot.com/
  2.  
  3. //3306 A  4792 2 DIAS TA BOM!
  4. //CAPITULO 5  ATTRIBUTES AND LISTENERS: BEING A WEB APP
  5.  
  6. Init parameters
  7.     DD->
  8.         <servlet>
  9.             ....
  10.             <init-param>
  11.                 <param-name>adminEmail</param-name>
  12.                 <param-value>thiago@hotmail.com</param-value>
  13.             </init-param>
  14.         </servlet>
  15.  
  16.     In the servlet
  17.         getServletConfig().getInitParameter("adminEmail");
  18.         //podemos chamar o getServletConfig() de qualquer lugar do nosso servlet, menos do construtor, só
  19.         //podemos depois do init() terminar, ou seja, do service() pra frente
  20.    
  21.  
  22.         Unico servletConfig por servlet
  23.         O container le os init parameters do DD e mandam para o servletconfig. Depois o container passa o servletconfig para o init(ServletConfig);
  24.  
  25.         O init() que devemos sobrescrever nao leva parametro nenhum. O que leva o init(ServletConfig) chama o init() internamente.
  26.         Se sobrescrever o outro, temos que chamar o init() la dentro para nao dar cagada!
  27.         Esses parametros são lidos uma única vez, e só quando o container initializes the servlet.
  28.         O container nunca vai ler os init parameters de novo.
  29.         ENTÃO COMO NÃO LÊ DE NOVO, TEMOS QUE DAR UM REDEPLOY PARA OS DADOS NOVOS COMEÇAREM A VALER.
  30.  
  31.         interface javax.servlet.ServletConfig
  32.             getInitParameter(String);
  33.             Enumeration getInitParameterNames();
  34.             getServletContext();
  35.             getServletName();
  36.  
  37.         DD web.xml
  38.         ...
  39.         <servlet>
  40.             <servlet-name>BeerParamTests</servlet-name>
  41.             <servlet-class>com.example.TestInitParams</servlet>
  42.             ....
  43.             <init-param>
  44.                 <param-name>adminEmail</param-name>
  45.                 <param-value>admin@hotmail.com</param-value>
  46.             </init-param>
  47.             <init-param>
  48.                 <param-name>mainEmail</param-name>
  49.                 <param-value>thiago@hotmail.com</param-value> //TESTAR DOOIS ATRIBUTOS COM O MESMO NOME!
  50.             </init-param>
  51.             <servlet-mapping>
  52.                 <servlet-name>BeerParamTests</servlet-name>
  53.                 <url-pattern>/Tester.do</url-pattern>
  54.             </servlet-mapping>
  55.         </servlet>
  56.  
  57.         public class TestInitParams extends HttpServlet {
  58.             ....
  59.             public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  60.                 response.setContentType("text/html");
  61.                 Enumeration e = getServletConfig().getInitParameterNames();
  62.                 while (e.hasMoreElements()){
  63.                     e.nextElement(); //vai printar os parameters names mainEmail e adminEmail
  64.                 }
  65.                 String adminEmail = getServletConfig().getInitParameter("adminEmail");
  66.             }
  67.         }
  68.  
  69.     How can a JSP get servlet init parameters? Servlet init params são exclusivos para o servlet, se tentar pegar o atributo em outro, da cagada!
  70.     Para esse caso setamos o atributo no Context initParam e nao no servletConfig. Esses parametros sao de toda a webapp.
  71.     Então todo servlet e jsp tem acesso a ele.
  72.     No dd web.xml ficaria assim
  73.     ...
  74.     <servlet>
  75.         ...
  76.     </servlet>
  77.     <context-param>
  78.         <param-name>adminEmail</param-name>
  79.         <param-value>clienteheaderror@hotmail.com</param-value>
  80.     </context-param>
  81.  
  82.     ****IMPORTANTE, O Context PARAM NAO FICA DENTRO DE UM SERVLET, DIFERENTE DO <init-param>
  83.     Para acessar no servlet
  84.     getServletContext().getInitiParameter("adminEmail");
  85.  
  86.     Difference between servlet init parameters and context init parameters.
  87.         Context fica dentro do webapp e fora dos servlet.
  88.         Init fica dentro de um servlet e so vale para aquele servlet.
  89.  
  90.         <init-param> <context-param>
  91.         getServletConfig().getInitParameter("meuParametro") -> initParam  VALE APENAS PARA O SERVLET ESPECIFICO.
  92.         getServletContext().getInitParameter("meuParametro") -> contextParam VALE PARA TODA A APP.
  93.  
  94.     Web app initialization
  95.         Container reads DD and create name/value for each <context-param>
  96.         Container creates a new instance of ServletContext
  97.         Container gives the ServletContext a reference for each name/value
  98.         Every jsp and servlet has access to taht same ServletContext
  99.  
  100.     Um único ServletContext por JVM em caso de aplicações distribuidas.
  101.  
  102.     Think of init parameters as deploy-time constants. You can get them at runtime, but you cant set them. NAO TEMOS METODOS setInitiParameter();
  103.  
  104.     *ContextParameter, application parameter , context init param.
  105.     *Servlet init parameter, init parameter, servlet init param.
  106.  
  107.     interface ServletContext {
  108.         getInitParameter(String);
  109.         getInitParameterNames();
  110.         getAttribute(String);
  111.         getAttributeNames();
  112.         setAttribute(String, Object);
  113.         removeAttribute(String);
  114.  
  115.         getMajorVersion()
  116.         getServletInfo();
  117.  
  118.         getRealPath();
  119.         getResourceAsStream(String);
  120.         getRequestDispatcher(String);
  121.  
  122.         log(String);
  123.     }
  124.  
  125.     Podemos pegar o servletContext() de duas formas também!
  126.         getServletConfig().getServletContext()
  127.         ou
  128.         this.getServletContext();
  129.  
  130.         UNICA VEZ QUE TEMOS QUE BUSCAR O CONTEXT ATRAVES DO CONFIG É QUANDO ESTAMOS EM UM SERVLET QUE NAO EXTENDS HTTPSERVLET OR GENERICSERVLET.
  131.  
  132.     Todos os init param são String!
  133.  
  134.     Como fazer que algo rode antes de um servlet ou jsp em especifico? Usar listener e GG
  135.         We wants to listen for a context initialization event, so that can get the context init parameters and run some
  136.         code before the rest of the app can service a client.
  137.         Como se fosse um main, quero que algo rode antes de qualquer coisa, como fazer?
  138.         Usamos um ServletContextListener
  139.  
  140.         interface ServletContextListener {
  141.             contextInitilized(ServletContextEvent);
  142.             contextDestroyed(ServletContextEvent);
  143.  
  144.             //javax.servlet.ServletContextListener
  145.         }
  146.  
  147.     This listener can:
  148.         Get notified when the context is initialized
  149.         Get the init param from the context
  150.         Use the init param to make a db connection.
  151.         Get notified when the context is destroyed.
  152.  
  153.         import javax.servlet.*;
  154.        
  155.         public class MyServletContextListener implements ServletContextListener {
  156.            
  157.             public void contextInitilized(ServletContextEvent event){
  158.                 ServletContext context = event.getServletContext();
  159.                 ...
  160.                 Dog d = new Dog(); //SE FOSSE APP DISTRIBUIDA, DOG TERIA QUE SER SERIALIZABLE!
  161.                 ....
  162.                 event.setAttribute("dog", d); //É ATRIBUTO, TEM SET E É  OBJETO!!!!
  163.                 //FOI SETADO NO CONTEXT, ENTAO PARA PEGAR TEMOS QUE BUSCAR NO context.getAttribute("dog"); FAZENDO O CAST!, LEMBRAR Q RETORNA OBJECT!
  164.                 //PARAM NAO TEM SET E SÓ PODE SER STRING!
  165.  
  166.             }
  167.  
  168.             public void contextDestroyed(ServletContextEvent event){
  169.                 //code to close the db connection.
  170.             }
  171.  
  172.         }
  173.  
  174.         Para o listener ser "visto" temos que por no nosso DD.
  175.         dentro do web app, fora dos servlet e de qualquer outra coisa, no root mesmo do <web-app>
  176.         <listener>
  177.             <listener-class>com.example.MyServletContextListener</listener-class>
  178.         </listener>
  179.  
  180.  
  181.         Outras listeners interfaces e seus eventos que podem ser "ouvidos"
  182.  
  183.         HttpSessionAttributeListener        HttpSessionBindingEvent-> atributeAdded/Removed/Replaced aqui é quando um atributo normal
  184.         que nao seja um objeto de uma classe.
  185.         ServletRequestListener              ServletRequestEvent-> para saber quando ocorre uma request.
  186.         HttpSessionBindingListener          HttpSessionBindingEvent-> valueBound valueUnbound ! quando é add ou removido da session !
  187.         !objeto de uma classe que sera guardado!!
  188.         ServletContextAttributeListener     ServletContextAttributeEvent-> quando um attributo é add, removed or replaced esse evento ocorre!
  189.         HttpSessionListener                 HttpSessionEvent-> para saber por exemplo quantos users estao no sistema.
  190.         ServletRequestAttributeListener     ServletRequestAttributeEvent-> quando um atributo é add, removido ou replaced em uma request.
  191.         ServletContextListener              ServletContextEvent-> quando o contexto é inicializado ou destruido.
  192.         HttpSessionActivationListener       HttpSessionEvent-> an attribute class, e quero q seja notificado quando estiver pronto
  193.          para migrar para outra JVM
  194.         ;{}
  195.  
  196.         interface ServletContextAttributeListener {  //EVENTO ServletContextAttributeEvent
  197.             void attributeAdded(ServletContextAttributeEvent event);
  198.             void attributeRemoved(ServletContextAttributeEvent event);
  199.             void attributeReplaced(ServletContextAttributeEvent event);
  200.         }
  201.  
  202.         interface HttpSessionListener { //EVENTO HttpSessionEvent
  203.             void sessionCreated(HttpSessionEvent event);
  204.             void sessionDestroyed(HttpSessionEvent event);
  205.         }
  206.  
  207.         interface ServletRequestListener { //EVENTO ServletRequestEvent
  208.             void requestInitialized(ServletRequestEvent event);
  209.             void requestDestroyed(ServletRequestEvent event);
  210.         }
  211.  
  212.         interface ServletRequestAttributeListener { //EVENTO ServletRequestAttributeEvent
  213.             void attributeAdded(ServletRequestAttributeEvent event);
  214.             void attributeRemoved(ServletRequestAttributeEvent event);
  215.             void attributeReplaced(ServletRequestAttributeEvent event);
  216.         }
  217.  
  218.         interface HttpSessionBindingListener { //EVENTO HttpSessionBindingEvent
  219.             void valueBound(HttpSessionBindingEvent event)      //AQUI SAO OBJETOS DE CLASSES QUANDO SAO INSERIDAS OU REMOVIDAS DA SESSION!
  220.             void valueUnbound(HttpSessionBindingEvent event);
  221.         }
  222.  
  223.         interface HttpSessionAttributeListener { //EVENTO HttpSessionBindingEvent *****************
  224.             void attributeAdded(HttpSessionBindingEvent event); //AQUI SAO ATRIBUTOS NORMAIS
  225.             void attributeRemoved(HttpSessionBindingEvent event);
  226.             void attributeReplaced(HttpSessionBindingEvent event);
  227.         }
  228.  
  229.         interface ServletContextListener {//EVENTO ServletContextEvent
  230.             void contextInitilized(ServletContextEvent event);
  231.             void contextDestroyed(ServletContextEvent event);
  232.         }
  233.  
  234.         interface HttpSessionActivationListener {  //EVENTO HttpSessionEvent ******************
  235.             void sessionDidActivate(HttpSessionEvent event);
  236.             void sessionWillPassivate(HttpSessionEvent event);
  237.         }
  238.  
  239.         REPARAR QUE no HttpSessionActivationListener e no HttpSessionAttributeListener OS EVENTOS NAO SEGUEM OS NOMES PADRÃO!!!!!
  240.  
  241.         HttpSessionAttributeListener x HttpSessionBindingListener
  242.         In HttpSessionAttributeListener any type of attribute has ben added, removed or replaced.
  243.         In HttpSessionBindingListener the attribute itself can find out when it has been added to or removed from a session.
  244.  
  245.         public class Dog implements HttpSessionBindingListener {
  246.             private String breed;
  247.             public void valueBound(HttpSessionBindingEvent event){
  248.  
  249.             }
  250.             public void valueUnbound(HttpSessionBindingEvent event){
  251.  
  252.             }
  253.         } //NOW DOG IS A LISTENER! toda vez que dog for para a session ou sair, vamos ser notificados aqui!!! SACOU O BINDINGLISTENER PARA QUE SERVE? PARA A CLASSE EM SI!
  254.         // BINDINGLISTENER ARE NOT REGISTERED IN DD!!!!
  255.  
  256. //3997 PRIMEIRA PARADA
  257.     An attribute is an object set into onte of three other servlet API objects, ServletContext, HttpServletRequest/ServletRequest or HttpSession.
  258.    
  259.     Attributes are not parameters.
  260.                     Attributes                                Parameters
  261.     Types       Application/Context                     Application/Context init parameters
  262.                 Request                                 Request Parameters
  263.                 Session                                 Servlet init Parameters
  264.                 There is no servlet specific attr       No such thing as session parameters.
  265.  
  266.     Set?        setAttribute(String,Object)             CANNOT SET, just in DD.
  267.  
  268.     Return      Object                                  String
  269.  
  270.     Get?        ServletContext.getAttribute(name)       ServletContext.getInitParameter(name)
  271.                 HttpSession.getAttribute(name)          ServletConfig.getInitParameter(name)
  272.                 ServletRequest.getAttribute(name)       ServletRequest.getInitParameter(name)
  273.  
  274.     Os três scopes são?
  275.         Context-> vale para toda a web app. De todo lugar conseguimos pegar ou setar!
  276.         Session -> somente para os que tem acesso a aquela httpSession.
  277.         Request -> somente para aquela request, depois ele "some".
  278.  
  279.  
  280.     Os metodos comuns nas interfaces são:
  281.         Object getAttribute(String name);
  282.         void setAttribute(String name, Object value);
  283.         void removeAttribute(String name);
  284.         Enumeration getAttributeNames();
  285.  
  286.         interface ServletContext {
  287.             getInitParameter(String);
  288.             getInitParameterNames();
  289.            
  290.             Object getAttribute(String name);
  291.             void setAttribute(String name, Object value);
  292.             void removeAttribute(String name);
  293.             Enumeration getAttributeNames();
  294.  
  295.             getMajorVersion();
  296.             getServerInfo();
  297.             getResourceAsStream();
  298.             getRequestDispatcher();
  299.             log(String);
  300.             ...
  301.         }
  302.  
  303.     interface ServletRequest {
  304.         getContentType();
  305.         getInitParameter(String name);
  306.  
  307.         Object getAttribute(String name);
  308.         void setAttribute(String name, Object value);
  309.         void removeAttribute(String name);
  310.         Enumeration getAttributeNames();
  311.         ...
  312.     }
  313.  
  314.     interface HttpServletRequest extends ServletRequest {
  315.         nothing related to attributes here..
  316.  
  317.         getContextPath();
  318.         getCookies();
  319.         getHeader(String);
  320.         getSession();
  321.         gerQueryString();
  322.         ...
  323.     }
  324.  
  325.     interface HttpSession {
  326.  
  327.         Object getAttribute(String name);
  328.         void setAttribute(String name, Object value);
  329.         void removeAttribute(String name);
  330.         Enumeration getAttributeNames();
  331.  
  332.         setMaxInactiveInterval(int);
  333.         getId();
  334.         getLastAccessedTime();
  335.         ...
  336.     }
  337.  
  338.     DarkSide of attributes.
  339.  
  340.     In a servlet
  341.     ....
  342.         getServletContext().setAttribute("foo", "22");
  343.         getServletContext().setAttribute("bar", "42");
  344.  
  345.         out.println(getServletContext().getAttribute("foo"));
  346.         out.println(getServletContext().getAttribute("bar"));
  347.  
  348.         //nothing wrong, print 22 and 42 for the first time run.
  349.         **If we run again
  350.         Printed out 22 and 16.
  351.         O que pode ter dado de errado? Colocamos esse codigo em um app grande, com varios outros servlets, então, algum outro servlet pode ter setado esse valor
  352.         de 16 para o atributo bar! Como ele é de scope context, a aplicação toda o enxerga!
  353.  
  354.         *Context scoped isnt thread-safe!
  355.  
  356.         How do we make context attributes thread-safe?
  357.  
  358.         1-> Synchronizing the doGet()/doPost()... methods is a bad idea.
  359.             Garantimos que ninguem va alterar os atributos ALI, porém, como o servlet é unico... imagina em um site grande....
  360.             Em outro lugar as pessoas pode alterar esses valores, como sao atributos de context.
  361.             Não precisamos de um lock no servlet e sim no context!
  362.             Dentro do servlet usaremos entao synchronized(getServletContext()){ BLA BLA BLA } Assim garantimos, porém, todos terão que implementar assim.
  363.  
  364.         Are session attributes thread-safe?
  365.             A session dura por multiplas request de um mesmo cliente. Nada impede o cliente de abrir duas janelas e fazer varias requests. Essa é a unica forma
  366.             de dar cagada em sessionAttributes. Para proteger disso, podemos synchronized (request.getSession()) {}
  367.  
  368.         SingleThreadModel is designed to protect instance variables (STM interface).
  369.         public class MeuServlet extends HttpServlet implements SingleThreadModel {}
  370.         Isso faz com que o container trabalhe com um request por vez para esse servlet.
  371.         Essa interface não tem methods, apenas garante isso.
  372.         Para isso temos duas abordagens:
  373.             1) The container maintain a single servlet, but queue every request and process one request completely before the next request to proceed.
  374.             2) The container creates a pool of servlet instances and procces each request concurrently, one per servlet instance.
  375.  
  376.             A primeira-> faz uma queue de request para o servlet e vai processando conforme forem ficando prontas
  377.             A segunda-> faz um pool de request e cada uma vai para uma instance do mesmo servlet, para ser processada.
  378.         So, only request attribute and local variables are thread-safe.
  379.         STM garante que apenas uma thread daquele servlet vai existir.
  380.  
  381.  
  382.  
  383.     Request attributes and Request dispatching.
  384.     Request attributes applies only in one request, after it, all dies.
  385.         request.setAttribute("styles", result);
  386.         RequestDispatcher view = request.getRequestDispatcher("result.jsp");
  387.         view.forward(request, response);
  388.         ESSE ATRIBUTO SO VIVE AQUI, OU SEJA SO VAI EXISTIR NESSE SERVLET E NA JSP "RESULT.JSP".
  389.  
  390.     RequestDispatcher have only two methods.
  391.         forward(request,response);
  392.         include(request,response); //veremos no <jsp: include> é o mesmo metodo!
  393.  
  394.         Podemos pegar o Dispatcher do request e do context.
  395.             request.getRequestDispatcher("minhaPagina.jsp"); //se fosse /minhaPagina.jsp ele tentaria root/minhaPagina.jsp.
  396.             getServletContext().getRequestDispatcher("/result.jsp"); //vai tentar rootdaApp/result.jsp
  397.             **QUANDO PEGAMOS DO CONTEXT, TEMOS QUE USAR O / NO NOSSO PATH, SE NAO DA CAGADA!!!!
  398.  
  399.  
  400.     in a servlet code
  401.         ...
  402.         OutputStream os = response.getOutputStream();
  403.         ....
  404.         RequestDispatcher view = request.getRequestDispatcher("result.jsp");
  405.         os.flush();
  406.         view.forward(request, response);
  407.         os.close();
  408.  
  409.         Qual a merda no codigo? Vamos receber uma linda IllegalStateException, ja comitamos a response com o flush() e tentamos passar A request no forward.
  410.         NAO PODEMOS DAR FORWARD NA REQUEST APOS A RESPONSE SER ENVIADA!
  411.             **You cant forward the request if youve already commited a response.
  412.  
  413. //TESTAR CHAMAR O GETSERVLETcONFIG NO INIT();
  414.  
  415.             V   <init-param>
  416.                 <param-name>adminEmail</param-name>
  417.                 <param-value>admin@hotmail.com</param-value>
  418.             </init-param>
  419.             <init-param>
  420.                 <param-name>mainEmail</param-name>
  421.                 <param-value>thiago@hotmail.com</param-value> //TESTAR DOOIS ATRIBUTOS COM O MESMO NOME!
  422.             </init-param>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement