Thursday, June 21, 2012

show/hide table in jsp struts

 <logic:equal name="searchPatientFormBean" property="showPatientSearchResult" value="true">  
 <table>  
 ..data..  
 </table>  
 </logic:equal>  
where name="searchPatientFormBean" is the form bean name given in the <action>

property="showPatientSearchResult" is the attribute of form bean whose value is set to false intially.

The table will be displayed only if showPatientSearchResult=true

Customized JSF table

Problem:
To create a data table in JSF in which the first row data spans across the columns ie only one column in the first row and the second row had 8 columns and it should alternate like that. This is not possible with h:dataTable tag

Reason:
The h:dataTable tag renderds data column wise

Solution:
To create such a table with column span use jstl along with plain html and jsf components

Sample Code:
 <c:forEach items="#{HospInvProfBean.productList}" var="product" varStatus="status"> /> <tr><td colspan="8" class="genText">  
  <h:outputText value="#{product.productDescription}"/></td> </tr>  
  <tr class="dtlLineCen">  
  <td style="width: 10%;">  
 <span class="genText">Minimum</span></td>  
 <td><h:inputText size="4" value="#{product.oposMin}" converter="javax.faces.Long" converterMessage="Not a number"/></td>  
  <td><h:inputText size="4" value="#{product.aposMin}" converter="javax.faces.Long" converterMessage="Not a number" /></td>  
 <td><h:inputText size="4" value="#{product.bposMin}" required="true" /></td>              
  <td><h:inputText size="4" value="#{product.abposMin}" required="true" /></td>     
  <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.onegMin}" required="true" /></td>              
  <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.anegMin}" required="true" /></td>              
 <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.bnegMin}" required="true" /></td>             
 <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.abnegMin}" required="true" /></td></tr>             
 <tr class="dtlLineAltCen">  
 <td style="width: 10%;"><span class="genText">Optimal</span></td>            <td><h:inputText size="4" value="#{product.oposOpt}" required="true" /></td>  
  <td><h:inputText size="4" value="#{product.aposOpt}" required="true" /></td>  
  <td><h:inputText size="4" value="#{product.bposOpt}" required="true" /></td>  
 <td><h:inputText size="4" value="#{product.abposOpt}" required="true" /></td>  
  <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.onegOpt}" required="true"/></td>  
  <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.anegOpt}" required="true"/></td>  
  <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.bnegOpt}" required="true"/></td>  
  <td><h:inputText size="4" rendered="#{product.aboGroup}" value="#{product.abnegOpt}" required="true"/></td>  
 </c:forEach>  

Custom Converter Spring 2.5 / Spring webflow


1. Dispatcher Servlet configuration

 <bean id="viewResolver"  
           class="org.springframework.web.servlet.view.ResourceBundleViewResolver"  
           p:basename="views" />  
 <bean id="tilesConfigurer"  
           class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"  
           p:definitions="/WEB-INF/tiles-defs.xml" />  
 <flow:flow-builder-services id="flowBuilderServices"  
           view-factory-creator="viewFactoryCreator" conversion-service="conversionService" />  

2. Write Convert Class

java.util.Calendar to String Custom Converter / String to java.util.Calendar Custom Converter

 import java.text.DateFormat;  
 import java.text.ParseException;  
 import java.text.SimpleDateFormat;  
 import java.util.Calendar;  
 import org.springframework.binding.convert.converters.TwoWayConverter;  
 public class CalendarStringTwoWayConverter implements TwoWayConverter {  
      @Override  
      public Class getSourceClass() {  
           return Calendar.class;  
      }  
      @Override  
      public Class getTargetClass() {  
           return String.class;  
      }  
      @Override  
      public Object convertSourceToTargetClass(Object source, Class targetClass)  
                throws Exception {  
           String date = null;  
           DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");  
           if(null!=source){  
                date= dateFormat.format(((Calendar) source).getTime()).toString();  
           }  
           return date;  
      }  
      @Override  
      public Object convertTargetToSourceClass(Object target, Class sourceClass)  
                throws Exception {  
            Calendar cal = Calendar.getInstance();  
         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");  
         try {  
                 cal.setTime(sdf.parse((String) target));  
            } catch (ParseException e) {  
                 e.printStackTrace();  
            }  
           return cal;  
      }  
 }  

3. Register Converter

 import org.springframework.binding.convert.service.DefaultConversionService;  
 import org.springframework.stereotype.Component;  
 @Component("conversionService")  
 public class ApplicationConversionService extends DefaultConversionService {  
      @Override  
      protected void addDefaultConverters() {  
           super.addDefaultConverters();  
           addDefaultAliases();  
           addConverter("calenderStringTwoWayConverter", new CalendarStringTwoWayConverter());  
           addConverter("enumStringTwoWayConverter", new EnumStringTwoWayConverter());  
           addConverter("timeStringTwoWayConverter", new TimeStringTwoWayConverter());  
      }  
 }  

Use in flow registry : Bind  properties with converter
 <view-state id="review" view="review" model="reviewModel">  
      <binder>  
           <binding property="state" converter="enumStringTwoWayConverter"/>            
           <binding property="time" converter="timeStringTwoWayConverter"/>             
           <binding property="date" converter="calenderStringTwoWayConverter"/>   
      </binder>  
 </view-state>  

This way of using named converters has been discontinued from Spring 3.0. In Spring3.0 the converters are handled in a different way.

4. Use in JSP

There is nothing special in jsp.

 <form:form name="myform" modelAttribute="reviewModel">  
      <form:input type="text" id="date" path="date" value="${date}"/>  
 </form:form>  

Single selection checkbox javascript


Javascript:

 function singleSelectCheckbox(checkbox) {  
       var cbs = document.getElementsByTagName('input');  
       for(var i=0; i < cbs.length; i++) {  
             if(cbs[i].type == 'checkbox') {  
                   if (cbs[i].id == checkbox.id) {    
             continue;  
                   }  
                   else{  
                        cbs[i].checked = false;   
                        }  
                   }  
            }  
        }  
In html page, give different ids to each checkboxes

Wednesday, May 16, 2012

Spring Webflow Popup example in JSP

Spring version: Spring webflow 2.0.3 , Spring MVC 3.0.5

1. In the parent jsp page add the following java script

 <script type="text/javascript" src="<c:url value="/resources/dojo/dojo.js" />"> </script>  
 <script type="text/javascript" src="<c:url value="/resources/spring/Spring.js" />"> </script>  
 <script type="text/javascript" src="<c:url value="/resources/spring/Spring-Dojo.js" />"> </script>  
 <link type="text/css" rel="stylesheet" href="<c:url value="/resources/dijit/themes/tundra/tundra.css" />" />  
 <script type="text/javascript">  
      Spring.addDecoration(new Spring.AjaxEventDecoration({                           
                                    elementId: 'popupbutton',  
                                    formId: 'myform',  
                                    event: 'onclick',  
                                    popup: true  
            }));            
 </script>  
                                                           Listing: 1

Replace the following attributes with your values :-

elementId : is the Id of the button /link which opens the pop up
formId : is the Id of the form where the pop up button belongs to

Sample Code from page:

 <form:form id="myform">  
 <input type="button" name="_eventId_review" id="popupbutton" value="Open Popup"  
  onclick="openPopupPage()" />  
 </form:form>  
 function openPopupPage() {  
    window.location.href = '${flowExecutionUrl}&_eventId=review';  
 }  
                                                             Listing: 2

Make sure to have org.springframework.js-2.0.3.RELEASE jar. This jar contains the Spring.js, Dojo.js ,Spring-Dojo.js  and the css referenced in the script tag

2. Modify Web.xml

In the above jsp code (Listing:1)you can see that we are referring to javascripts (dojo.js , Spring.js etc ) Those requests to the java scripts are handled by Resource Servlet in spring. So add the following servlet entry in web.xml to map the requests to java scripts to the resource servlet.

  <servlet>  
   <servlet-name>Resource Servlet</servlet-name>  
   <servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>  
 </servlet>  
 <servlet-mapping>  
   <servlet-name>Resource Servlet</servlet-name>  
   <url-pattern>/resources/*</url-pattern>  
 </servlet-mapping>  
                                                               Listing: 3

3. Modify flowregistry.xml

Add popup="true" in the view-state of the popup page
 <view-state id="review" view="review" model="reviewModel" popup="true">  
 </view-state>  
Listing: 4

The pop up page is a normal jsp page. There is no special code to be put in the pop up page to open it as a pop up. The above steps I took from my working code.

Note: In IE8 and IE9 , it will not open as a pop-up , if we try to access the page using http://localhost:8080. You have to replace localhost with IP address or computer-name. This is because IE8 and IE9 handles localhost separately.

Hope this helps.

Friday, March 5, 2010

JSF reset form data when conversion fails

Problem:

My JSF form had some input text fields,one command link to another page, one command button for submit and one command button for reset. The text boxes accepts only Long values. I use a backing bean method in the action of reset button to reset the default values (pulled out from data base).

If character is entered in text box and a conversion error occured while sumbitting( save button) then if the user clicks reset or commandLink the same conversion error occurs. Because when we click reset or commandLink to another page, the page is going through the entire jsf life cycle where validtion and conversion happens before action. So we are getting the conversion error even if we try to reset the value.

We need the conversion error only when clicking save button and for reset , commandLink it should not throw any conversion error as these operations have nothing to do with the input data.

Solution:

Use immediate="true" with reset button and commandLink. With immediate attribute we are forcing the action to happen before conversion/validation occurs. Then the commandLink works fine as it is navigating to some other page. The reset button should show the same page with the default values set by the action method. This won't happen as expected. The submitted values will not be cleared even after reset. This is because the view is not getting rendered with immediate attribute. For this to happen we need to render the view explicitly in our code.

setting immediate attribute:


 <h:commandLink id="url_3" value="" immediate="true" action="#{BackingBean.approve}">Approve Page</h:commandLink>  
 <h:inputText size="4" value="#{BackingBean.productPrice}" converter="javax.faces.Long" converterMessage="Not a number"/>  
 <h:commandButton id="save" type="submit" value="Save" action="#{BackingBean.save}"/>  
 <h:commandButton id="reset" immediate="true" value="Reset" action="#{BackingBean.reset}"/>  
sample code to force the view in reset action method:
 public String reset(){  
   setInitialValues();  
   FacesContext context = FacesContext.getCurrentInstance();  
   Application application = context.getApplication();  
   ViewHandler viewHandler = application.getViewHandler();  
   UIViewRoot viewRoot = viewHandler.createView(context,context.getViewRoot().getViewId());  
   context.setViewRoot(viewRoot);  
   return "success" ;  
  }  
More information about immediate attribute:
Immediate attribute
More information about clearing input data:
Clear input component

JSF confirmation message based on action

Problem:

When user clicks a save button, the entered values are validated in a Backing bean method based on a business rule. If the validation fails, a confirmation message or pop up should be displayed to the user whether the user wishes to continue with save.

Solution:

This is little tricky. We call the validation method inside the action method of save button. We have to use a hidden parameter whose value is set to true if the validation fails ie we need to prompt the user. Using a javascript check if the value of hidden parameter is true then show the confirmation message. When user clicks ok in the confirmation message, from the javascript call the action (save) method of a hidden command button. Call the javascript on loading the page


Here is the javascript

 function showConfirmation(){  
  var value=document.getElementById('formId:valid').value;  
  if(value == "true"){  
   if(confirm("There are values that are at 0.Do you want to save the  information ?")){  
   document.getElementById('formId:hiddenButton').click();  
   }else{  
     return false  
    }  
  }  
 }  

jsf page:
 <body onload=showConfirmation()>  
  <h:form id="formId">  
  <h:commandButton id="save" type="submit" value="Save" action="#{BackingBean.save}"/>  
 <h:inputHidden id="valid" value="#{BackingBean.showconfirmation}"/>  
  <h:commandButton id="hiddenButton" value="hidden" action="#{BackingBean.saveWithZero}" style="visibility:hidden;" />  
 </h:form>  
 </body>  

Make sure that you set showconfirmation=false in your backing bean until you need to show the pop up.

JSF confirmation message using javascript

Problem:

When a command button is clicked, display a prompt to the user if user selects 'OK' execute the action other wise stay in the current page.

Solution:

Use javascript confirmation dialog in <commandButton>


<h:commandButton value="Save" action="#{BackingBean.save}" onclick="if (!confirm('Are you sure you want to save?')) return false" >

If we return false from the javascript the action will not be executed.

JSF expanding row of data table

Problem :

To create a table from a list of objects obtained from DB in which each row has a button.On clicking the button the details of the row is displayed as next row.
This is not possible with JSF <h:dataTable>

Solution:

Use JSTL to iterate through the list and use plain html to create the table. 
Use jsf components inside the <td> of the table
Here is the sample code

 <table>  
 <tr class="colHdr">  
   <td >Column 1</td>  
   <td >Column 2</td>  
   <td >Column 3</td>  
   <td >Column 4</td>  
   <td >Column 5</td>  
 </tr>  
 <!-- use jstl1.2 for iterating the list of hardware objects-->  
 <c:forEach items="#{BackingBean.hardwareList}" var="hardware" varStatus="status">  
 <tr>  
   <td colspan="5" class="colStyle">  
     <h:outputText value="#{hardware.hardwareDesc}"/>  
   </td>  
 </tr>  
 <!--use status var to alter the row color -->  
 <tr class="${status.index % 2 == 0 ? 'style1' : 'style2'}">  
   <td> <!--use f:setPropertyActionListener to get which hardware's(row) detail button is clicked -->  
  <h:commandButton value="Hardware Details" action="#{BackingBean.details}">  
     f:setPropertyActionListener target="#{BackingBean.hardware}" value="#{hardware}" />  
  <!-- Backing bean must have getter and setter for hardware type -->  
  </h:commandButton>  
  </td>  
   <td><h:inputText size="4" value="#{hardware.col1}"/></td>  
   <td><h:inputText size="4" value="#{hardware.col2}"/></td>  
   <td><h:inputText size="4" value="#{hardware.col3}"/></td>  
   <td><h:inputText size="4" value="#{hardware.col4}"/></td>  
  <!-- this column is rendered only for hardware whose group is true-->  
   <td><h:inputText size="4" rendered="#{hardware.group}" value="#{hardware.col5}"/></td>  
 </tr>  
 <!-- On clicking the detail button set the showDetails   
 (of the corresponding hardware object obtained through the f:setPropertyActionListener)   
 to true in the backing bean -->  
 <h:panelGroup rendered="#{hardware.showDetails}">  
 <tr>  
 <td colspan="5">  
 <hr />  
 </td>  
 </tr>  
 <tr>  
   <td class="text1">Minimum</td>  
   <td class="text1"><h:outputText value="#{hardware.col1Min}"/></td>  
   <td class="text1"><h:outputText value="#{hardware.col2Min}"/></td>  
   <td class="text1"><h:outputText value="#{hardware.col3Min}"/></td>  
   <td class="text1"><h:outputText value="#{hardware.col4Min}"/></td>  
   <td class="text1"><h:outputText value="#{hardware.col5Min}"/></td>  
 </tr>  
 <tr>  
   <td class="genText">Optimal</td>  
   <td class="expLineAlt"><h:outputText value="#{hardware.col1Opt}"/></td>  
   <td class="expLineAlt"><h:outputText value="#{hardware.col2Opt}"/></td>  
   <td class="expLineAlt"><h:outputText value="#{hardware.col3Opt}"/></td>  
   <td class="expLineAlt"><h:outputText value="#{hardware.col4Opt}"/></td>  
   <td class="expLineAlt"><h:outputText value="#{hardware.col5Opt}"/></td>  
 </tr>  
 </h:panelGroup>  
 </c:forEach>  
 </table>  

Some useful links about customizing data table in JSF
expand-collapse-of-table-rows-in-datatable-jsf
Everything about data table in JSF

Tuesday, February 16, 2010

Jdeveloper 11g in Windows 7

I was trying to install Jdeveloper 11g in my windows 7 machine. I got it installed correctly, but the problem I had was when I started it then it was throwing some exception and it quited. The exception was something like the following:

oracle.adf.rc.config.ConfigurationException: an ADFContext has not been registered for name [oracle.jdeveloper.rescat2.ResourcePalette]. Root Cause=[] [Root exception is java.lang.NullPointerException]

In my case this issue was due to the user profile name in my system. It had spaces. The jdeveloper by default creates its directories in the C:\DocumentSetting\Users\
My profile name was like Vv & Aa. It had spaces before and after the ampersand. So what I did to make it work was to set the JDEV_USER_DIR to another folder.

In the command prompt set the JDEV_USER_DIR to some other folder of your choice.

set JDEV_USER_DIR = F:\myJdevProfile

Then go to the directory where jdeveloper is installed and start it from the command prompt

F:>jdeveloper> jdeveloper.exe

You have to start jdeveloper every time like this after setting the JDEV_USER_DIR
Other wise you can set it permenantly by setting the environment variable.

For windows 7, right click Computer, click properties, click Advanced system settings, click environment variables in the advanced tab. In the system variables, create new variable and give name as JDEV_USER_DIR and value as the directory of your choice. (here it is F:\myJdevProfile)

Here after you can start jdeveloper from the start menu itself by clicking the jdeveloper icon.

Some useful links:

http://forums.oracle.com/forums/thread.jspa?threadID=983953

http://jdeveloperfaq.blogspot.com/2009/12/faq-1-how-to-configue-stand-alone.html

Friday, January 22, 2010

Formating date in java

 Date date = new Date();  
 Format formatter = new SimpleDateFormat("MM/dd/yy");  
 String s= formatter.format(date);  
 System.out.println(s);  

Friday, October 16, 2009

ServletContext and ServletConfig

ServletConfig

  • The servlet gets the init params from the ServletConfig. Each servlet has a ServletConfig object.

  • When the container initializes a servlet, it makes a unique ServletConfig object for it.

  • The servlet init params are read only once and is available only for that particular servlet.

  • The init params are given in the DD within the < servlet> tag.
 <servlet>  
 <init-param>  
 <param-name> name </param-name>  
 <param-value> val </param-value >  
 </init-param>  
 </servlet>  
  • The container first reads the DD and gets the init-params.

  • Then the container creates a new ServletConfig instance for the servlet

  • Container creates a new name/value pair of Strings for each init parameter

  • Container gives the ServletConfig reference to name/value pair

  • Container creates a instance of the servlet class

  • Container calls the init(ServletConfig) method by passing the ServletConfig reference

  • The servlet can access the init params using getServletConfig().getInitParameter("name")

    ServletContext

    The ServletContext is for the webapp. The container makes a ServletContext when a web application is deployed and makes it available to all the servlets and JSPs of that application. Context init params are available to the entire webapp. Any servlet and JSP in the app has access to the context init params. The context params are given in the DD outside the < servlet > tag.

    < web-app .... >
    < context-param >
    < param-name > name < /param-name >
    < param-value > val < /param-value >
    < /context-param >
    < servlet > < /servlet>
    < /we-app >

    The container reads the DD and creates name/value String for each context-param.
    Container creates a instance of ServletContext.
    Container gives the ServletContext reference to each name/value pair of the context params.
    Every JSPs and servlets deployed in that webapp can access this context params through the ServletContext using the method getServletContext().getInitParameter("name")

    Servlet Life Cycle

    A Servlet is controlled by the Container. The servlet has only one state - Initialized.

    1. The web container first loads the Servlet (.class file).

    2. The web container creates an instance of the Servlet by calling the constructor

    3. The web container then calls the init() method of the servlet which initializes the servlet. It is called only once

    4. The web container then calls the service() method of the servlet which in turn calls the respective doGet() or doPost() depending on the type of request. For each request, a separate thread is used.

    5. Finally the container calls the destroy() method which cleans up and make it ready for garbage collection. It is also called only once.



    Servlet classes and life cycle methods:

    javax.servlet.GenericServlet implements javax.servlet.Servlet (interface)
    javax.servelt.http.HttpServlet extends javax.servlet.GenericServlet
    MyServlet extends javax.servelt.http.HttpServlet


    The init() method of the Generic Servlet is called if it is not overriden in the MyServlet. The init() can be used to initalize the database before processing the request.
    The service() method of the HttpServlet is called. We don't need to override it.
    The service() method in HttpServlet calls the overrriden doGet() or doPost() of MyServlet.


    Note:


    • There is only one servlet instance per JVM

    • Each request runs in a separate thread.

    • Servlet is loaded and initialized only once when the container starts up.

    • init() always completes before the first call to service()

    • The constructor of the servlet class just creats an ordinary object. It becomes a servlet when it is initalized after init().

    J2EE Server

    A J2EE server incorporates web container and EJB container. The web container has the web components
    (Servlet + JSP ).
    The EJB container has the business components.

    A web server has only Web container. Apache is the web server and Tomcat is the web container
    There is no stand alone EJB containers now a days.

    J2EE servers are WebService , JBoss which has both web and EJB containers.

    How to configure Tomcat 6 in Eclipse

    Steps for configuring Tomcat 6 in Eclipse


    • Download Eclipse and extract it into a folder. (I have downloaded Eclipse-Galileo [Eclipse IDE for Java EE developers] from http://www.eclipse.org/downloads/ and extracted in into D:\Eclipse )
    • Open eclispe by double clicking eclipse.exe
    • Create a workspace
    • In windows->Preferences->server -> run time environment
    • Click add, select the Tomcat v6, click Next
    • Set the Tomcat installation directory (for me it is D:\apache-tomcat-6.0.20)
    • Set the JRE by clicking Installed JREs -> Add -> Standard VM -> set the JRE home to JDK folder (path in step 3)
    • Click finish
    • Select the newly added JRE and click Ok
    • Select the newly added JRE from the drop down of JRE and click Finish
    • At the top right corner of eclipse there is a button 'Open perspective'. Select Java EE perspective.
    • If you can't see 'Server' tab at the bottom, select Windows->show view -> server
    • In the server tab at the bottom, Right click -> New Server -> Select the Tomcat v6 and click Finish


    • If you want to run the tomcat manually from command prompt then set the environment variable JAVA_HOME to jdk path ie the path in step 3

    web container

    Web Container


    Container is something that extends the functionality of a web server.Web server cannot alone handle the dynamic pages . The container does it.Tomcat is an eg: of a container. While apache is the web server.Servlets are deployed in the Container.

    Container provides -
    communication support - we dont have to worry about creating sockets, listners, streams
    lifecycle management - it controls the life and death of servlets
    multithreading support - automatically creats a new thread when a request comes
    provides security - it has a deployment descriptor DD which is an XML which helps to manage the security with out changing java source code.
    jsp support - translates the jsp to java

    When a request for a dynamic page comes, the web server hands over it to the container and then the container does the following:

    container creates two objects - HttpServletRequest and HttpServletResponse
    finds the correct servlet based on URL, creates/allocates a thread, passes the request and response object to the servlet thread
    calls the service() method
    based on the request type the service() method calls doGet() or doPost() method
    the doXxx() method generates the dynamic pages and put it into the respose object
    thread is completed
    container converts the response to Http response and sends it to the client
    deletes the request and response objects

    URL and Port

    URL

    Uniform Resource Locator - It is the unique address of each resource on the web.
    It is in the format:

    protocol:// server : port/path of the resource/resource name/[optional query string]

    eg: http://www.freshfruits.com/all/fruits/grapes.jsp

    Protocol (http):- tells the server which communication protocol is used
    Server (www.freshfruits.com) :- the unique name of server which maps to a unique IP address.
    IP address is numeric.
    Port (80):- port number is optional. By default the port number for web server is 80
    .
    Path (all/fruits/) :- the location of the resource in the server
    (unix syntax is used to describe the path)
    Resource name (grapes.jsp) :- the requested resource
    Optional query string:- the extra info in the GET request is appended to the end of URL as query string.
    It starts with ? followed by name/value pair separated by &


    TCP Port

    A 16 bit number that identifies a specific softare program on the server hardware. It is a logical
    connection to a software running on a server harware. A server has 65536 ports ranging from 0 - 65535.
    The port numbers from 0-1023 are reserverd for system services.
    It is possible to run different applications on the same port provided the applications are using different
    protocols.
    Some reserved ports:
    21 - FTP
    23 - Telnet
    25 - SMTP
    37 - Time
    80 - HTTP
    110 - POP3
    443- HTTPS
    Apache (the open source web server )directory structure:
    Apache_home -> htdocs -> index.html, root folders for the apps on the server -> sub folders and htm pages

    Http request and Http Response

    HTTP Request and Response

    The HTTP Request contains an HTTP method which tells the server the type of request that is being made. The HTTP adds a header to its request and response.

    GET and POST
    The common HTTP methods are GET and POST.

    The GET method is used to get a resource from the server. For eg: when the user clicks a link. The GET method can send limited quantity (depending on server) of data to the server. The data that is send via GET method is appended to the URL and is exposed to everyone. This data (called parameter) is separated by "?" in the URL. The GET request can be bookmarked. The GET is used for getting things and not making any changes to the server

    The POST method can request a resource from the server and also sends the form data (called payload) to the server.For eg: when the user enters some data and submits the form by clicking the submit button. The parameters are put in the payload. POST request can't be bookmarked. The POST is used for sending data to be processed and this data is used to change something on the server. (an update)


    Sample HTTP GET request:
    -----------------------------------------------------------------
    GET /fruits/grapes.jsp?color=green&type=seedless HTTP/1.1
    Host: www.freshfruits.com
    User-Agent: Mozilla
    Accept: text/html
    Accept-Language:en-us
    Keep-Alive:300
    Connection:keep-alive
    -----------------------------------------------------------------
    Sample HTTP POST request
    ------------------------------------------------------------------
    POST /fruits/grapes.jsp HTTP/1.1
    Host: www.freshfruits.com
    User-Agent: Mozilla
    Accept: text/html
    Accept-Language:en-us
    Keep-Alive:300
    Connection:keep-alive
    color=green&type=seedless --> This is the message body or Payload <--
    ----------------------------------------------------------------------
    The other HTTP methods are HEAD, TRACE, PUT, DELETE. OPTIONS and CONNECT.
    The HTTP Response contains the requested resource in the form of HTML. The response has a header and body. The requested resource is put in the body of the response.The header tells the browser the protocol that is used, whether the request is success or not, the type of the content in the body(MIME type).

    Sample HTTP Response:
    -----------------------------------------------------------
    HTTP/1.1 200 OK
    set-cookie: JSESSIONID=0B4587RT
    content-type:text/html
    content-length:242
    date: wed, 23 Sep 2009 02:45:09 GMT
    Server: Appache
    Connection: close
    < html >
    ...........the requested resource
    ..........
    < /html >
    -------------------------------------------------------------------

    web server and client

    Web Client
    A web client is a browser which lets the user to request resources. The resources can be an image, a text file, a sound file or anything. The web client sends request to the web server.

    Web Server
    A web server receives the request from the client, locates the requested resource and sends the response back to the client. If the requested resources is not available in the server it gives a '404 File not found error'

    How the client and server communicates?

    The web server and client communicates via HTTP (Hyper Text Transfer Protocol). The HTTP protocol runs on the top of TCP/IP.
    The TCP (Transmission Control Protocol) ensures that the file send from one host to another is received completely and correctly.
    The IP (Internet Protocol) routes the packets from one host to another.
    The web client must know HTML (Hyper Text Mark up Language). The HTML tells the browser how to display the contents send by the server.
    In short, the browser ie the web client sends HTTP request and the web server send back an HTTP response which contains HTML.

    Followers