Saturday, 14 March 2015

Servlet and JSP

Servlet

Introduction:

·         With java we can develop two types of applications
o   Standalone application
o   Web based application
·         Aa application which contains the main method and can be installed every client machine is called as standalone application
·         Problems with standalone applications
o   Needs to be installed on every client machine
o   Any changes happens on project need to reinstall all the client machines
o   Consumes more resources
·         Application can installed in one machine and which can be accessed anywhere in the  worlds is called as web based application
·         These applications can be installed on server and there are so many servers are available. Tomcat, weblogic, web sphere etc
·         To access these application we need to client and here clients are browsers(IE, FF, crome ..etc)
·         To work with request we need to send methods as part of request. Based on these methods server will respond to client
o   Get
o   Post
o   Head
o   Put
o   Delete
o   Locate
o   Trace
·         Response codes from the server
o   1XX – Information transformation
o   2XX -- success
o   3XX -- redirect
o   4XX – requested resource is not available
o   5XX – requested resource is available but problems in code
·         To create web application we need to create following folders
o   Create folder with project name
o   Create WEB-INF folder
o   Inside WEB-INF create other 2 folders (lib, classes) and web.xml file
·         Web based applications  contains the set of resources (jsp, servlet, html…etc)
·         We can develop two types of application
o   Static application
§  Application will not change data for any request
o   Dynamic application
§  Application will send response based on request
·         To develop web application Sun micro system has released servlet API
·         As part of this API we have two packages
o   Javax.servlet.*
o   Javax.servlet.http.*;
·         Most of important interfaces are
o   Servlet
o   ServletRequest
o   ServletResponse
o   ServletContext
o   ServletConfig
·         Servlet is a java program which can provide the implementation of servlet interface directly or indirectly
·         Servlet is a interface which contains the following abstract methods. If we want to create servlet program we need to implement all methods in our class
o   int(ServletConfig config) : void
o   service(ServletRequest request, ServletResponse response) : void
o   destroy() : void
o   getServletInfo() : String
o   getServletConfig() : ServletConfig

Procedure to create web based application

·         Create dynamic web project
·         Create servlet program
public class FirstServlet implements Servlet
{

    public ServletConfig config;
   
    public void init(ServletConfig config) throws ServletException
    {
        this.config = config;
        System.out.println("init method");
       
    }
   
    public void service(ServletRequest request, ServletResponse response)
    {
        System.out.println("Service method");
    }
   
    public void destroy()
    {
        System.out.println("Destroy method");
    }
   
    public String getServletInfo()
    {
        return "FirstServlet";
    }
   
    public ServletConfig getServletConfig()
    {
        return config;
    }
}

·         Configure servlet in web.xml file
<servlet>
      <servlet-name>first</servlet-name>
      <servlet-class>com.ibm.pdc.ephs.servlet.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
      <servlet-name>first</servlet-name>
      <url-pattern>/fistPage</url-pattern>
</servlet-mapping>
§  Access page from browser
§  Internal process for web application:
o   Server creates the request and response object
o   Server check the context root and check for the servlet is configured for that url pattern.
o   If url is not configured server throws the exception
o   If url is configured sytem checks servlet name
o   Checks for servlet class for the specified name
o   Now server execute the init method if it is not executed yet
o   Then server execute the service method(This method is like main method in web applications)
o   Init method will be executed only once. From second request onwards it will execute service method.

Static servlet:

·         Display welcome message on browser.
o    

Dynamic servlet:

public class DynamicOutputServlet implements Servlet
{
    private ServletConfig config;

    public void init(ServletConfig config)
    {
        System.out.println("Init");
    }

    public void service(ServletRequest request, ServletResponse response)
    {
        try
        {
            PrintWriter out = response.getWriter();
            out.print(new Date());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    public void destroy()
    {
        System.out.println("Destroy");
    }

    public String getServletInfo()
    {
        return "DynamicOutputServlet";
    }

    public ServletConfig getServletConfig()
    {
        return config;
    }
}
<servlet>
            <servlet-name>DynamicOutputServlet</servlet-name>
            <servlet-class>com.ibm.pdc.ephs.servlet.DynamicOutputServlet</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>EmployeeDetailsDisplayServlet</servlet-name>
            <url-pattern>/EmployeeDetailsDisplayServlet</url-pattern>
      </servlet-mapping>

Content type:

·         Used to specify the type of content need to display on browser
·         By default al browsers will display text/html but sometimes we need to display pdf, xml and some other types in the browser
·         To specify the data type which we are passing is with the help of content type on response object
public class WelcomeMessageOnBrowserServlet implements Servlet
{
    private ServletConfig config;

    public void init(ServletConfig config)
    {
        System.out.println("Init");
    }

    public void service(ServletRequest request, ServletResponse response)
    {
        try
        {
            PrintWriter out = response.getWriter();
            out.print("Welcome to Servlet");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
       
    }

    public void destroy()
    {
        System.out.println("Destroy");
    }

    public String getServletInfo()
    {
        return "WelcomeMessageOnBrowserServlet";
    }

    public ServletConfig getServletConfig()
    {
        return config;
    }

}
public class MyXMLFormatServlet implements Servlet
{
    public ServletConfig config;

    public void init(ServletConfig config) throws ServletException
    {
        this.config = config;
        System.out.println("init method");

    }

    public void service(ServletRequest request, ServletResponse response)
    {
        try
        {
            Employee e = new Employee();
            e.setEmployeeId(1);
            e.setEmployeeFirstName("Chadnra");
           
            PrintWriter out = response.getWriter();
            response.setContentType("text/xml");

            out.print("<employee>");
            out.print("<eno>");
            out.print(e.getEmployeeId());
            out.print("</eno>");
            out.print("<ename>");
            out.print(e.getEmployeeFirstName());
            out.print("</ename>");
            out.print("</employee>");

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    public void destroy()
    {
        System.out.println("Destroy method");
    }

    public String getServletInfo()
    {
        return "FirstServlet";
    }

    public ServletConfig getServletConfig()
    {
        return config;
    }
}
<servlet>
      <servlet-name>MyXMLFormatServlet</servlet-name>
      <servlet- class>com.ibm.pdc.ephs.servlet.MyXMLFormatServlet</servlet-class>
</servlet>
<servlet-mapping>
      <servlet-name>MyXMLFormatServlet</servlet-name>
      <url-pattern>/MyXMLFormatServlet</url-pattern>
</servlet-mapping>
·         We have specify response.setContentType(String) before print writer object.
·         Following are the some of content types
o   application/pdf
o   text/html
o   text/plain
o   video/3gpp
o   video/3gpp2
As of now we have removed hard coding with two techniques and now in servlet we will use the following items
·         Servlet Context object
·         Servlet Config object

Servlet Config object:

·         If we configure data for servlet config object only particular servlet can access that data. Other servlets can’t access this data
·         To store data in servlet config object we need to use the <init-parameter> tag inside a <servlet> tag
·         This tag takes the two child tags
o   <param-name>---> key of the object
o   <param-value>----> value to the key
·         getInitParameter(key) method is used to retrieve data inside a servlet
public class ConfigObjectServlet extends HttpServlet
{
    private static final long serialVersionUID = 1496023463759878091L;

    public void service(HttpServletRequest request, HttpServletResponse response)
    {
        ServletConfig config = getServletConfig();
        String name = config.getInitParameter("userName");
        System.out.println(name);
       
        try
        {
            PrintWriter out =  response.getWriter();
            out.print(name);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
      <servlet>
            <servlet-name>ConfigObjectServlet</servlet-name>
            <servlet-class>com.ibm.pdc.ephs.servlet.jessy.ConfigObjectServlet</servlet-class>
            <init-param>
                  <param-name>userName</param-name>
                  <param-value>Chandra</param-value>
            </init-param>
      </servlet>
      <servlet-mapping>
            <servlet-name>ConfigObjectServlet</servlet-name>
            <url-pattern>/ConfigObjectServlet</url-pattern>
      </servlet-mapping>

Servlet Context:

·         Context object will be created only one for project and data which is configured in this is available throughout the project. That means we can access all over the project
·         We will use <context-parm> to configure data for this object. This object takes two child tags
o   <param-name>---->key
o   <param-value>----->value
·         This tag is configured outside of the servlet tag
·         getInitParameter(key) is used to fetch the data in servlet
public class ContextObjectServlet extends GenericServlet
{

    private static final long serialVersionUID = -7763467575722580650L;

    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
    {
        ServletContext application1 = getServletContext();
        ServletContext application2 = getServletConfig().getServletContext();
       
        PrintWriter out = response.getWriter();
        out.print(application1.getInitParameter("userName"));
        out.print(application2.getInitParameter("userName"));       
    }
}
<context-param>
            <param-name>userName</param-name>
            <param-value>Chandra</param-value>
      </context-param>
      <servlet>
            <servlet-name>ContextObjectServlet</servlet-name>
            <servlet-class>com.ibm.pdc.ephs.servlet.jessy.ContextObjectServlet</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>ContextObjectServlet</servlet-name>
            <url-pattern>/ContextObjectServlet</url-pattern>
      </servlet-mapping>

Load on startup:

·         <load-on-startup> tag is used to load the servlet at the time of project deployment.
·         If we configure <load-on-startup> for servlet server execute the init method at the time of project deployment on server
·         <load-on-startup> tag takes the integer values from 1 to infinity.  1 is highest priority and other values are lower priority
·         If we configure two servlets with 1 and 10 as <load-on-startup> server execute the 1 servlet method is first then other servlet
·         Java file:
public class LoadOnStartUpServlet implements Servlet
{
    private ServletConfig config;

    @Override
    public void destroy()
    {
        System.out.println("destroy");
    }

    @Override
    public ServletConfig getServletConfig()
    {
        return config;
    }

    @Override
    public String getServletInfo()
    {
        return this.toString();
    }

    @Override
    public void init(ServletConfig arg0) throws ServletException
    {
        System.out.println("load on startup Init");
    }

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException
    {
        System.out.println("Service");
    }

}





·         Web.xml
      <servlet>
            <servlet-name>LoadOnStartUpServlet</servlet-name>
            <servlet-class>com.ibm.pdc.ephs.servlet.jessy.LoadOnStartUpServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
            <servlet-name>LoadOnStartUpServlet</servlet-name>
            <url-pattern>/LoadOnStartUpServlet</url-pattern>
      </servlet-mapping>

Welcome file List:

·         Welcome file list is used to initialize the home page when we access page without passing the resource name
·         If we configure welcome file list data application loads the configured pages into browser or console
·         Tag to configure this
<welcome-file-list>
      <welcome-file>WelcomeFileServlet</welcome-file>    
</welcome-file-list>
·         From the above tag If we access the page server loads the WelcomeFileServlet related url into the browser as default
·         We can configure multiple <welcome-file> tags inside a <welcome-file-list>. Based on pages availability it will load the pages. First page is available server loads the page and if not looks for other pages. No page is available system gives the 404 error
·         Java file:
public class WelcomeFileServlet extends HttpServlet
{

    private static final long serialVersionUID = -6687778027919400101L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
       
        out.print("Welcome page to servlets");
    }
}







·         Web.xml:
<welcome-file-list>
            <welcome-file>WelcomeFileServlet</welcome-file>    
      </welcome-file-list>

<servlet>
<servlet-name>WelcomeFileServlet</servlet-name>
<servlet-class>com.ibm.pdc.ephs.servlet.jessy.WelcomeFileServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>WelcomeFileServlet</servlet-name>
<url-pattern>/WelcomeFileServlet</url-pattern>
      </servlet-mapping>

Init methods:

·         Servlet is having init method which takes the ServletConfig object and this object needs to be configured as a local variable in our servlet and If we forget to create the config object application variables will not work properly.
·         To avoid above problem Sun Micro System has release GenericServlet program in this they have added code to use the init method without any arguments
init() {}
·         It’s always recommended to use the second init method instead of first init method.
·         An init method which does not take any arguments are called as second init method
·         Java:
public class SecondInitServlet extends GenericServlet
{

    public void init()
    {
        System.out.println("Second init method");
    }

    public void service(ServletRequest request, ServletResponse response)
    {
        System.out.println("Service method");
    }
}
·         Web.xml:
<servlet>
      <servlet-name>SecondInitServlet</servlet-name>
      <servlet-class>com.chandra.servlet.SecondInitServlet</servlet-class>
</servlet>
<servlet-mapping>
      <servlet-name>SecondInitServlet</servlet-name>
      <url-pattern>/SecondInitServlet</url-pattern>
</servlet-mapping>

Service Methods:

·         Generally we will provide normal service method which takes the ServletRequest and ServletResponse as arguments but this is common method to accept all protocols
·         Sun Micro System released the HttpServlet just to support HTTP protocol. It’s always recommend to use the service method which is available inside the HttpServlet class
·         HttpServlet uses the Generic servlet so we can use second init and second service
·         A service method which can take HttpServletRequest and HttpServletResponse as arguments called as second service method
·         Java File
public class SecondServiceServlet extends HttpServlet
{
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        System.out.println("Second Service");
    }
}

·         Web.xml
      <servlet>
            <servlet-name>SecondServiceServlet</servlet-name>
            <servlet-class>com.chandra.servlet.SecondServiceServlet</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>SecondServiceServlet</servlet-name>
            <url-pattern>/SecondServiceServlet</url-pattern>
      </servlet-mapping>
·         It also not recommended to use this second service method, we always need to use the doGet or doPost method in case of HttpServlets
·         doGet(HttpServletRequest request, HttpServletResponse response)
·         doPost(HttpServletRequest request, HttpServletResponse response)

Login Page:

·         Create html page
<html>
<head>
<title>Login Form</title>
</head>
<body>
      <form action="./login">
            <table>
                  <thead>
                        <tr>
                              <td colspan="2" align="center">Login Form</td>
                        </tr>
                  </thead>
                  <tr>
                        <td>Username:</td>
                        <td><input type="text" name="username" /></td>
                  </tr>
                  <tr>
                        <td>Passwprd:</td>
                        <td><input type="password" name="password" /></td>
                  </tr>
                  <tr>
                        <td colspan="2"><input type="submit" value="Login" /></td>
                  </tr>
            </table>
      </form>
</body>
</html>

·         Create Servlet which reads data
public class LoginServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();

        Configuration cfg = new Configuration();
        cfg.configure("com/chandra/servlet/files/configuration/hibernate.cfg.xml");
        SessionFactory sf = cfg.buildSessionFactory();

        Session hsession = sf.openSession();
        Transaction tx = hsession.beginTransaction();

        Criteria criteria = hsession.createCriteria(LoginDomain.class);
        criteria.add(Restrictions.eq(LoginDomain.USERNAME, username));
        criteria.add(Restrictions.eq(LoginDomain.PASSWORD, password));

        List<LoginDomain> list = criteria.list();

        if (list != null && !list.isEmpty() && list.size() == 1)
        {
            out.print("You are authorised person");
        }
        else
        {
            out.print("Sorry, you are not authorised!");
        }
        tx.commit();
        hsession.close();

    }
}

·         Create Db table
create table UserDetails(id number primary key, username varchar2(20), password varchar2(20));

·         Create hibernate configuration and mapping files
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
      <session-factory>
            <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
            <property name="connection.url">jdbc:oracle:thin:@localhost:1521:ephsw01</property>
            <property name="connection.username">HIBERNATE</property>
            <property name="connection.password">HIBERNATE</property>
            <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
            <mapping resource="com/chandra/servlet/files/mapping/Login.hbm.xml" />
      </session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
      <class name="com.chandra.servlet.domain.LoginDomain" table="USERDETAILS">
            <id name="id" column="ID">
                  <generator class="assigned"></generator>
            </id>
            <property name="username" column="USERNAME" />
            <property name="password" column="PASSWORD" />
      </class>
</hibernate-mapping>
public class LoginDomain implements Serializable
{
    private static final long serialVersionUID = 1549817477120974123L;
    public static final String ID = "id";
    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";

    private Integer id;
    private String username;
    private String password;
//setters and getters
}

·         Configure servlet in web.xml file
<servlet>
      <servlet-name>loginForm</servlet-name>
      <servlet-class>com.chandra.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
      <servlet-name>loginForm</servlet-name>
      <url-pattern>/login</url-pattern>
</servlet-mapping>
mapping
·         Deploy application
·         Access it from browser








JSP:
·         JSP is also like a servlet and no need to struggle much to develop jsp pages
·         JSP file simplifies the development process of a web application like in servlet we need to create servlet and then configuration but in jsp we can just need to create html type of page and need to access page from browser.
·         JSP page needs to end with .jsp extinction
·         We need to place jsp inside project and outside WEB-INF folder
·         The main advantage of JSP is it improves the productivity of a developer
·         JSP takes less amount of time to implement when compare to servlet
·         JSP is also a servlet and which is going to generate by server instead of us
·         Server contains the Servlet, jsp and ejb…etc containers and JSP container is responsible to convert this jsp to servlet
·         By using jsp we can separate the presentation and business logic
·         It’s recommend to use the servlet in case of lot of business logic

Template Test:

·         Any static text is called as template text. This is text used to send output to client
·         When we use the template text, it will directly place text in out.println() method and this code is placed inside the service method
·         Welcome.jsp:
Welcome to JSP.

Scriptlet:

·         Scriptlets are used to write java code inside jsp page
·         Syntax: <% …… %>
·         <% int a = 10; %>
·         a will be created under the service method and it is a behave like a local variable
·         JSP has following implicit variables
o   Request
o   Response
o   pageContext
o   application
o   config
o   session
o   out
o   page
o   exception
·         Request: used to read the request related details here
<%
    out.print(request.getMethod());
    out.print(request.getAuthType());
    out.print(request.getContentType());
    out.print(request.getContextPath());
    out.print(request.getLocalAddr());
    out.print(request.getPathInfo());
    out.print(request.getRequestURI());
    out.print(request.getProtocol());
    out.print(request.getRemoteHost());
    out.print(request.getRemoteUser());
%>

·         Response: used to set data on response object
<%
    response.sendError(500, "Error");
%>

·         PageContext: is a main object by using this we can access all implicit objects
<%
    out.print(pageContext.getOut());
    out.print(pageContext.getRequest());
    out.print(pageContext.getResponse());
    out.print(pageContext.getPage());
    out.print(pageContext.getServletContext());
    out.print(pageContext.getServletConfig());
    out.print(pageContext.getSession());
%>

·         Application: is a context object we can read data of context param values
<%
      application.getInitParameter("name");
      application.getContextPath();
      application.getEffectiveMajorVersion();
      application.getEffectiveMinorVersion();
%>

·         Config: this is related to particular jsp and reads data related to same jsp
<%
    config.getInitParameter("name");
    config.getServletName();
%>

·         Session: session is a object which is created per user
<%
    out.print(session.getCreationTime());
    out.print(session.getId());
    out.print(session.getLastAccessedTime());
    out.print(session.getMaxInactiveInterval());
%>

·         Out: out is JspWriter object and used to send content to browser
<%
    out.print(session.getCreationTime());
    out.print(session.getId());
    out.print(session.getLastAccessedTime());
    out.print(session.getMaxInactiveInterval());
%>

·         Page: is a scoped variable and will be exist until the jsp
<%
    out.print(page.hashCode());
      out.print(page.toString());
%>

·         Exception: is created only on exception pages
<%@ page isErrorPage="true"%>
<%
    out.print(exception.getMessage());
%>

JSP declarations:

·         Used to create the instance variables, instance methods, static variables and static methods
·         Syntax: <%! ….. %>
<%!int a;
    static int b;

    public static void staticMethod(JspWriter out) throws Exception
    {
        out.print("b:" + b);
    }

    public void instnaceMethod(JspWriter out) throws Exception
    {
        out.print("a:" + a);
    }%>

<%
    staticMethod(out);
    instnaceMethod(out);
%>

JSP Expression:

·         JSP Expressions are used to read data of a instance, local, static variables and display the data to user directly without using the out.println() method
·         Syntax: <%= …. %>
<%=out%>
<%=request%>
<%=response%>
<%=pageContext%>
<%=page%>
<%=session%>
<%=application%>
<%=config%>

JSP Directives:

·         JSP directives gives the instructions to JSP compilers
·         These are three types
o   Page
o   Include
o   taglib

Page directive:

·         Page directives gives the information about the page
·         Following are the page directive attributes
o   language: used to specify the supported language and JSP support only java
<%@ page language="java" %>
o   info: used to display the servlet info used in getServletInfo():
<%@ page info="JSP information" %>
<%=getServletInfo() %>
o   contentType: used to specify the context of data need to display on browser
<%@ page contentType="text/html; charset=ISO-8859-1" %>
o   import: used for importing the packages
<%@ page import="java.util.*, java.io.*" %>
o   buffer: used to specify the size of buffer to send data to client. If that is reached jsp will send data to browser and then wait for fill the buffer data. Default size of buffer is 8KB.
o   autoFlush: Used to flush data to browser. By default server flush the data to browser and If it is filled server send the data. We can disable this functionality by setting the false to autoFlush.  If autoFlush is false server throw the buffer overflow error.
<%@ page buffer="10kb"%>
<%@ page autoFlush="true" %>

o   isErrorPage: this is a message to error pages. When any error occurs on other pages jsp forward to this page
<%@ page isErrorPage="true" %>
Some problem happends on page

o   errorPage: This is cause of errors and main page in application
<%@ page errorPage="/PageDirectiveIsErrorPage.jsp"%>
<%=10 / 0%>

Include directive:

·         It behaves like static import
·         Used to load page headers and footers
·         <%@ include file="/LoginForm.html"%>
·         Above page loaded at file time if any changes on LoginForm it will not impact on pages

Taglib directive;

Will be covered as part of JSTL

JSP action tags:

·         JSP action tags are used to perform some actions and which are given by the Sun Micro System
·         Following are the action tags
o   <jsp:include>
<jsp:include page="LoginForm.html" />
<jsp:include page="LoginForm.html" />
o   <jsp:forward>
<jsp:forward page="LoginForm.html" />
<jsp:forward page="LoginForm.html" />
o   <jsp:useBean>
<jsp:useBean id="login" class="com.chandra.servlet.domain.LoginDomain" scope="session"/>
o   <jsp:setProperty>
<jsp:setProperty property="username" name="login" value="Chandra"/>
<jsp:setProperty property="password" name="login" value="Chadnra"/>
o   <jsp:getProperty>
<jsp:getProperty property="username" name="login"/>
<jsp:getProperty property="password" name="login"/>













Multi page form applications:

Http is a state less protocols that means it will not remember data from one request to other request. To resolve this issue we have following techniques
·         Hidden variables
·         Cookies
·         Session

Hidden variables:

We will use html hidden variable technique to send data internally
<form action="./SecondPage.jsp">
      <input type="text" name="username" /> <input type="submit" value="Next">
</form>
Read data from first form and sent it to server in the form of hidden variable.
<%
    String name = request.getParameter("username");
%>
<form action="../HiddenVariableTechnique">
      <input type="hidden" value="<%=name%>" name="username"/>
      <input type="text" name="passord" /> <input type="submit" value="Login">
</form>
public class HiddenVariablesServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        out.print(request.getParameter("username"));
        out.print(request.getParameter("passord"));

    }
}
      <servlet>
            <servlet-name>HiddenVariableTechnique</servlet-name>
            <servlet-class>com.chandra.servlet.HiddenVariablesServlet</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>HiddenVariableTechnique</servlet-name>
            <url-pattern>/HiddenVariableTechnique</url-pattern>
      </servlet-mapping>
Disadvantages: Data transfer from server and client multiple times
Advantages: these are occupy less memory

Cookie:

·         Cookie is a piece of information which can transfer between server and client.
·         When server send cookie to client, client store data in cache memory
·         Every browser send 20 cookies per domain and each one maximum of 4KB
·         Application to send cookie to client
public class SendCookieServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Cookie c = new Cookie("name", "Chandra");
        response.addCookie(c);
    }
}
<servlet>
<servlet-name>SendCookieServlet</servlet-name>
<servlet-class>com.chandra.servlet.SendCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SendCookieServlet</servlet-name>
<url-pattern>/SendCookieServlet</url-pattern>
      </servlet-mapping>
·         Application to read cookies:
public class ReadCookiesServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        if (cookies != null)
        {
            for (Cookie c : cookies)
            {
                out.print(c.getName() + ":\t\t");
                out.println(c.getValue());
            }
        }
    }
}

<servlet>
<servlet-name>ReadCookiesServlet</servlet-name>
<servlet-class>com.chandra.servlet.ReadCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadCookiesServlet</servlet-name>
<url-pattern>/ReadCookiesServlet</url-pattern>
      </servlet-mapping>
Disadvantages:
1.       If browser do not accept cookies application will not work
2.       Data will be transferred between server and client
3.       We can send small amount of data
4.       Every time client need to close the browser to clear the cookies

Session:

·         When client send the request first time to server, server creates the session.
·         After creation of session server send the JSESSIONID in the form of cookie
·         Per client we will be having only one client
·         Session is object which is object HttpSession(interfaces)
·         We can get session object with request object
o   request.getSession(true)
o   request.getSession(false)
·         If we pass value false, server will not create new session object and will be used in the application. This is used in internal pages of application like login page we will create session and internal pages we will use false value.
·         Application to read data of session
public class SessionServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        HttpSession session = request.getSession(true);
        PrintWriter out = response.getWriter();
        out.println(session.isNew());
        out.println(session.getId());

        HttpSession session1 = request.getSession(false);
        out.println(session1.isNew());
        out.println(session1.getId());
    }
}
      <servlet>
            <servlet-name>SessionServlet</servlet-name>
            <servlet-class>com.chandra.servlet.SessionServlet</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>SessionServlet</servlet-name>
            <url-pattern>/SessionServlet</url-pattern>
      </servlet-mapping>
·         Invalidate session
o   By default server remove session after 30 min
o   session.invalidate(); remove from java ccode
o   Configuration in web.xml file
<session-config>
    <session-timeout>10</session-timeout>
</session-config>
10 is in the form of minutes
o   session.setMaxInactiveInterval(10);

Scoped Variables:

·         Level of data access of a variable is called scoped variable.
·         In jsp we have 4 scopes
o   Page: setting data in pageContext is called as page scope.
<%
    pageContext.setAttribute("name", "Chandra");
%>
<%=pageContext.getAttribute("name") %>

o   Request
<%
  request.setAttribute("name", "Chandra");
%>
<%=request.getAttribute("name")%>

o   Session
<%
    session.setAttribute("name", "Chandra");
%>
<%=session.getAttribute("name")%>

o   Application
<%
    application.setAttribute("name", "Chandra");
%>
<%=application.getAttribute("name")%>

Request Dispatchers:

·         RequestDispatcher is an object which can take object from client and hand over to any other pages
·         Sun micro system released RequestDispacther interface and it contains two methods
o   forward(request, response)
o   include(request, response)
·         Request dispatcher can get in two ways
o   application.getRequestDispathcher(“absolute path”);
o   request.getRequestDispatcher(“relative path”);
·         absolute path means no need to pass the / to url
·         relative path means we need to pass correct url here
·         Forward: will forward to other page and discard current page output and this can happen only one time.
public class ForwardServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        RequestDispatcher relativePath = request.getRequestDispatcher("login");
        relativePath.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        RequestDispatcher absolutePatch = getServletContext().getRequestDispatcher("/login");
        absolutePatch.forward(request, response);
    }
}
·         Include: we can include any number of pages in one servlet
public class IncludeServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        RequestDispatcher relativePath = request.getRequestDispatcher("login");
        relativePath.include(request, response);
        RequestDispatcher absolutePatch = getServletContext().getRequestDispatcher("/SessionServlet");
        absolutePatch.include(request, response);
    }


}

Named Dispatcher:

·         We can request pages with servlet names
public class NamedDispatcherServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        RequestDispatcher namedDispatcher = getServletContext().getNamedDispatcher("login");
        namedDispatcher.forward(request, response);
    }
}

sendRedirect():

·         Used to access request which is available in another server.
public class SendRedirectServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException    {
        response.sendRedirect("https://www.facebook.com");
    }
}




MVC:

Registration Form:

1.       JSP page to create form
2.       Servlet to read data from jsp
3.       Service layer and dao layer to send data to DB
4.       Success or failure form


JSTL:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false"%>

<%
      pageContext.setAttribute("name", (Object) "pageContext");
      request.setAttribute("name", "request");
      session.setAttribute("name", "session");
      application.setAttribute("name", "application");
%>
${name }
<br />

<h1>Core Tags</h1>
1.C:out
<br />
<c:out value="Welcome to JSTL"></c:out>
<br />
2.C:if
<br />
<c:if test="${name.equals('pageContext')}">
      pageContexgt
</c:if>
<br />
3.
<c:forEach begin="1" end="10" var="a">
${a}
</c:forEach>



No comments:

Post a Comment