Tuesday, August 20, 2013

About Locking Mechanism in Threads....

About Locking Mechanism...
-------------------------------

Every object in java.. has.. a lock...At any time only one thread can
acquire a lock...,If one thread acquires lock.. all the threads should
need to wait for the lock.. only after the first thread releases the
lock.. second thread can acquire the lock....


When an object's lock is acquired by a thread.. ?
-------------------------------------------------------------------

When a thread enters synchronized method or block,
thread acquires the object's lock...

If any other thread wants to enter the synchronized method
or block...it needs to wait until the first thread releases it...

Assume Class Student has 3 methods...

a)first(synchronized method)
b)second(synchronized method
c)third

Assume there is a Student Object stu
stu = new Student();

When.. one thread XYZ enters first method.., first thread XYZ  acuqires
lock on stu object,so no other thread can enter... first or second
method... until  XYZ thread completes the first method...

But... the most important thing....,other threads can stilll enter
non synchronized method..........

Let me know if you have any doubts..........
























Friday, August 16, 2013

Complex Custom Tag Example

Hi Everyone..

In the previouse post we have seen simple example.Now we will see little complex example.
Run movieTag.jsp in the uploaded code to execute the custom tag.

I want to develop a custom tag.. to display the set of movies stored in page scope.

My tag should be like this and jsp page should display movies when the following
custo tag is encountered.

 <mytags:iterateMovies>
           
            ${movie}<br>
 </mytags:iterateMovies>

movieTag.jsp

<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="mytags" uri="/WEB-INF/tlds/hello" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
       
        <%
           List movies = new ArrayList();
           movies.add("Three Idiots");
           movies.add("Titanic");
           pageContext.setAttribute("movies", movies);
        %>
        <mytags:iterateMovies>
           
            ${movie}<br>
        </mytags:iterateMovies>
    </body>
</html>



Whatever the content in between Opening tag (<mytags:iterateMovies>) and Ending tag( </mytags:iterateMovies>) is called body or body content(JspFragment)


If you want to display the body content on the jsp page from doTag,
you have to say getJspBody().invoke(null);

getJspBody() method is available in SimpleTagSupport class.

But the body content is ${movie} in the above example, so you have to set movie in page scope.
If you observe the doTag() code...

1)First I have retrieved.. the movies list from page scope.
2)In second stage, I am iterating each movie and setting one movie
   at a time in to page scope with name movie.
3)Whenever.. I say getJspBody().invoke(null), the body content between
   opening tag and closing tag (${movie}) should be displayed to jsp but
   ${movie} is expression language, so the movie set in page scope will
   replace the ${movie} and movie is displayed on jsp page. For every iteration the
  ${movie} will be replaced with movie from list and all the movies get displayed.


 public void doTag() throws JspException, IOException {
        List movies = (List)getJspContext().getAttribute("movies");
        for(int i=0;i<movies.size();i++){
       
          getJspContext().setAttribute("movie", movies.get(i));
          getJspBody().invoke(null);
       
        }
       
       
    }


How getJspBody().invoke(null) works ?

Suppose if your custom tag is

<mytags:testBody>Hello I am BODY </mytags:testBody>

doTag:
----------
If you want to display Hello I am BODY from.. doTag
you call getJspBody().invoke(null)

If you call getJspBody().invoke(null) 4 times from doTag

HelloI am BODY will be printed 4 times on jsp page...




Uploaded the HelloWorldWithAdvancedCustomTag in the following URL.

https://docs.google.com/file/d/0BwZaaDwCofcNMVc2dUk5TGJ1bVk/edit?usp=sharing

Let me know if you have any doubts....








Thursday, August 15, 2013

How to create custom tag ?

When we need to write custom tag?

Generally we should not write scriptlets in jsp to do some logic.Expression tags,Standard actions and
jstl may not be sufficient to meet out specific tags.

Eg:
If I want to retrieve records from a table and show it on the jsp with out Scriptlets..there is no other
way other than implementing your own custom tag.

<mytags:displayFriends/>


Is it difficult to write custom tag ?

It looks difficult but if we understand the process it is not that difficult.

Steps to write custom tags ?

We are going to develop simple custom tag.

<mytags:helloWorld>

Whenever we place <mytags:helloWorld> in jsp we need to display
"Welcome to JSTL, it is very easy" message in jsp.

1)We need to write a class that extends SimpleTagSupport.
   SimpleTagSupport implements SimpleTag interface

   We will develop HelloWorld tag for our example.HelloWorld need
    to extend SimpleTagSupport.
    
2)We need to override doTag method with our logic to display "Welcome to JSTL,it is very easy".

   Example code:
  
   public void doTag() throws JspException, IOException {
      
        getJspContext().getOut().print("Welcome to JSTL,it is very easy");
       
       
    }
   
 
3)We need to create tld file with following contents.Tld should be located in WEB-INF
   folder.I am placing it in WEB-INF/tlds/hello.tld.

  Contents of TLD file:

 <?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>hello</short-name>
  <uri>/WEB-INF/tlds/hello</uri>
  <tag>
      <name>helloWorld</name>
      <tag-class>customtags.HelloWorld</tag-class>
      <body-content>empty</body-content>
  </tag>
</taglib>


What is the purpose of TLD ?

Whenever container encounters <mytags:helloWorld/>,it searches tld file with name helloWorld
and then calls the doTag method in the class declared by <tag-class> element.In above declaration
we have specified customtags.HelloWorld.So doTag method in HelloWorld gets invoked by
container whenever it sees <mytags:helloWorld/>

Write a test jsp to test our custom tag


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="mytags" uri="/WEB-INF/tlds/hello" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <mytags:helloWorld/>
    </body>
</html>
 


We have to use taglib directive in jsp page to specify the prefix and uri.

What is URI in taglib directive ?

The value need to be matched with the <uri> element's value specified in TLD file.
In our TLD file we have given uri as <uri>/WEB-INF/tlds/hello</uri>.So in jsp
page directive give uri value as  uri="/WEB-INF/tlds/hello".


What is prefix ?

prefix is just a dummy name,you can give whatever you want.
If you give prefix as mytags

Then in jsp you need to give <mytags:helloWorld>

If you give prefix as hellotags

Then in jsp you need to give <hellotags:helloWorld>

What is JspContext?

JspContext is set by the container while creating the custom tag object.
It automatically happens and set by the jspContainer.JspContext is superclass
for pageContext.From JspContext you can access JspWriter to output some
content to the browser.

In doTag, we will first getJspContext and from JSPContext object we will get
out(JspWriter object) and we will call print method that displays the content
on the browser.

getJspContext().getOut().print("Welcome to JSTL,it is very easy");

Uploaded the code to following URL

https://docs.google.com/file/d/0BwZaaDwCofcNSkJINkZEVll3WHM/edit?usp=sharing







 






















What is Filter and Example on Filter ?

Definititon of Filters:

Filters are Java components-very similar to servlets - that you can use to intercept and process request before they are sent to the servlet, or to process response after the servlet has completed,but before the
response goes back to the client.

Suppose if you want to do some thing before doGet/doPost is invoked (like auditing related activity(How many requests came to servlet etc)) you can write Filter.We have to map which filters will be called for which request URL pattersns in DD(web.xml)

Filter is an interface just like Servlet.

What happens in Background ?
 
As you know container passes request,response objects to doGet/doPost.If a filter is configured, container
invokes the Filter and passes the request and response objects to Filter and then request get passed to
Servlet(If no other Filters are configured.We can configure more than one filter for a request.Eg:AuditingFilter may just log the request details to HelloWorldServlet,SecurityFilter performs security checks for the same HelloWorldServlet).

Suppose if there are more Filters for Servlet, container invokes Filter1 and then Filter7 and Filter3.
as in the following image.But Servlet even doesn't know that Filters are configured.



Filter methods:

init(Just like Servlet)
destroy(Just like Servlet)
doFilter:
     The doFilter() method is called every time the Container determines that the filter should be
applied to the current request.The doFilter() method takes 3 arguments.
   a)ServletRequest
   b)ServletResponse
   c) FilterChain

 Auditing related/Security related code you like to implement should be in doFilter.

How to declare Filter ?
------------------------------



From the above declaration you can see it is very similar to Servlet mapping.
Whenever a request ends with .do,then BeerRequestFilter gets executed.


When there are 3 filters configured for HelloWorldServlet,container first invokes
Filter1, In Filter1's doFilter method you have to call chain.doFilter(req,resp),then
Filter2 gets executed,Filter2 has to write chain.doFilter then Filter3 gets executed
and as it is the final Filter then request goes to HelloWorldServlet,then response
comes to Filter3 you can do any post processing logic,then Filter2 then Filter1
and response comes to browser

Request->Filter1->Filter2->Filter3->HelloWorldServlet->Response
->Filter3->Filter2->Filter1->Browser.

ImpThing:

Don't forget to add chain.doFilter in every filter.....

Uploaded the zip file with Simple Filter example

https://docs.google.com/file/d/0BwZaaDwCofcNcTdqcTlCQnZwakk/edit?usp=sharing

Please let me know if you can't access the above URL.