Search This Blog

Showing posts with label Web Technologies. Show all posts
Showing posts with label Web Technologies. Show all posts
Wednesday, 27 March 2024

Ex-12 (b) Creating and Managing Cookies using Servlet

0 comments

  

Web Application using Cookies for Session Handling


The Client (Cookie.html):

<html>

<head>

<title>Session Handling using Session Objects</title>

</head>

<body>

<h2>User Login</h2>

<form method="post" action="/validatUser">

User Name : <input type="text" name="user" /><br/>

Passowrd: <input type="password" name = "pass" /> <br/>

Click here to Send Request --> 

<input type="submit" value="Validate">

</form>

</body>

</html>


Servlet-1 (Validate.java):

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class Validate extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();

        String uName = request.getParameter("user");
        String pWord = request.getParameter("pass");
        
        if(pass.equal("1234"))
        {
            Cookie ck = new Cookie("userName", uName);
            response.addCookie(ck);
            response.sendRedirect("welcomUser");
        }
        else
        {
            out.println("The Password is not Correct...");
        }
    }
}

Servlet-2 (Welcome.java):

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class Welcome extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Cookies cks[] = request.getCookies();
        String user = cks[0].getValue();
        
        out.println("Hello " + user);
    }

}


Web Descriptor (web.xml):

<web-app>

<servlet>

<servlet-name>validateUser</servlet-name>

<servlet-class>Validate</servlet-class>

</servlet>

<servlet>

<servlet-name>welcomeUser</servlet-name>

<servlet-class>Welcome</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>validateUser</servlet-name>

<url-pattern>/validatUser</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>welcomeUser</servlet-name>

<url-pattern>/welcomUser</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>Cookie.html</welcome-file>

</welcome-file-list>

</web-app>

Continue reading →
Tuesday, 26 March 2024

Ex-12 (a) Session Handling using Session Object

0 comments

 

Servlets using Session Object for Session Handling


The Client (Session.html):

<html>

<head>

<title>Session Handling using Session Objects</title>

</head>

<body>

<h2>User Login</h2>

<form method="post" action="validatUser">

User Name : <input type="text" name="user" /><br/>

Passowrd: <input type="password" name = "pass" /> <br/>

Click here to Send Request --> 

<input type="submit" value="Validate">

</form>

</body>

</html>


Servlet-1 (Validate.java):

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Validate extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();

        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        if(pass.equal("1234"))
        {
            HttpSession session = request.getSession();
            session.setAttribute("uName", name);
            response.sendRedirect("welcomUser");
        }
        else
        {
            out.println("The Password is not Correct...");
        }
    }
}


Servlet-2 (Welcome.java):

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Welcome extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();
        
        String user = (String)session.getAttribute("uName");
        out.println("Hello " + user);
    }
}


Web Descriptor (web.xml):

<web-app>

<servlet>

<servlet-name>validateUser</servlet-name>

<servlet-class>Validate</servlet-class>

</servlet>

<servlet>

<servlet-name>welcomeUser</servlet-name>

<servlet-class>Welcome</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>validateUser</servlet-name>

<url-pattern>/validatUser</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>welcomeUser</servlet-name>

<url-pattern>/welcomUser</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>Session.html</welcome-file>

</welcome-file-list>

</web-app>

Continue reading →
Monday, 11 March 2024

Ex. 9 - Retrieving Data from MySql Database using Java & JSP

0 comments

Web Technologies Lab

(Experiment 9(a) and (b))



a) Accessing MySQL DB from Console Application:

package dbconnect;

import java.sql.*;

public class DBConnect {


    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic her

        String url = "jdbc:mysql://127.0.0.1:3306/";

        String dbName = "test";

        String driver = "com.mysql.jdbc.Driver";

        String dbUser = "root";

        String dbPW = "";

        

        Connection objConn;

        Statement objStmt;

        ResultSet objResSet;

        try

        {

            Class.forName(driver).newInstance();

            

            objConn = DriverManager.getConnection(url + dbName, dbUser, dbPW);

            System.out.println("Connected Successfully");

            

            objStmt = objConn.createStatement();  

            objResSet = objStmt.executeQuery("select * from employee");  

            while(objResSet.next())  

                System.out.println(objResSet.getInt(1)+"  "+objResSet.getString(2)+"  "+objResSet.getString(3));  

            objConn.close();  


        }

        catch(Exception e)

        {

            System.out.println("Error in Connection");

        }

    }

}


b) Accessing MySQL DB from Web Application using JSP:

<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<html>
<head>
<title>JDBC Connection JSP example</title>
</head>
<body>
<h1>JDBC Connection JSP example</h1>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/test","root", "");
Statement stmt=con.createStatement();
String qry="select * from emp";
ResultSet rs=stmt.executeQuery(qry);
while(rs.next())
{

out.print(rs.getInt(1)+" "+rs.getString(2)+" ");
}
}
catch(SQLException ex)
{
out.print("SQL Exception caught"+ex.getMessage());
}
%>
</body>
</html>

Continue reading →
Monday, 26 February 2024

Ex. 8 - Servlet Retrieving Data from a MySQL Database

0 comments

Web Technologies Lab

(Experiment 8)





import java.io.IOException;

import java.io.PrintWriter;

import java.sql.*;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 *

 * @author Eben Priya David

 */

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})

public class MyServlet extends HttpServlet {


    /**

     * Processes requests for both HTTP

     * <code>GET</code> and

     * <code>POST</code> methods.

     *

     * @param request servlet request

     * @param response servlet response

     * @throws ServletException if a servlet-specific error occurs

     * @throws IOException if an I/O error occurs

     */

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {

        

        Connection conn = null;

        String url = "jdbc:mysql://127.0.0.1:3306/";

        String dbName = "test";

        Statement stmt = null;

        ResultSet result = null;

        String driver = "com.mysql.jdbc.Driver";

        String dbUser = "root";

        String dbPW = "";

            

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        try {

            /*

             * TODO output your page here. You may use following sample code.

             */

        Class.forName(driver).newInstance();

        conn = DriverManager.getConnection(url + dbName, dbUser, dbPW);      

        stmt = conn.createStatement();

        result = null;

        String empname, empcity, empstate;

        result = stmt.executeQuery("Select * from employee");

        String emp_Name, emp_City, emp_State;

            out.println("<html>");

            out.println("<head>");

            out.println("<title>Servlet MyServlet</title>");            

            out.println("</head>");

            out.println("<body>");

            out.println("<h1>Servlet MyServlet at " + request.getContextPath() + "</h1>");

        

               while (result.next()) 

               {

                     empname = result.getString(2);

                     out.println("<h3>" + empname + "</h3><br/>");

               }

            

            out.println("</body>");

            out.println("</html>");

        } finally {            

            out.close();

        }

    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**

     * Handles the HTTP

     * <code>GET</code> method.

     *

     * @param request servlet request

     * @param response servlet response

     * @throws ServletException if a servlet-specific error occurs

     * @throws IOException if an I/O error occurs

     */

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        try {

            processRequest(request, response);

        } catch (ClassNotFoundException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        } catch (SQLException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        }

    }


    /**

     * Handles the HTTP

     * <code>POST</code> method.

     *

     * @param request servlet request

     * @param response servlet response

     * @throws ServletException if a servlet-specific error occurs

     * @throws IOException if an I/O error occurs

     */

    @Override

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        try {

            processRequest(request, response);

        } catch (ClassNotFoundException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        } catch (SQLException ex) {

            Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

        }

    }


    /**

     * Returns a short description of the servlet.

     *

     * @return a String containing servlet description

     */

    @Override

    public String getServletInfo() {

        return "Short description";

    }// </editor-fold>

}


Continue reading →
Sunday, 26 February 2023

Installing Server Software on Windows and Ubuntu

0 comments

Installing Server Software - Apache and Tomcat 

(Experiment 1)

 Experimented On: 01-01-2024 (III IT 'B')

04-01-2024 (III IT 'A')



Steps involved in Installing Server on Windows:

Step 1: Install JDK version 1.5 and above for having the JRE installed on your system using the link given below: 


After installing JDK, check whether Java has been installed properly by typing the command java and javac on the command prompt.

Step 2: Instll XAMPP software stack which includes the installation for Apache, Tomcat, MySQL, PHP and Perl using the link given below: 


After installing XAMPP successfully in your system, open the browser and type the following commands to check whether the server - Apache and Tomcat are running properly through port number 80 and 8080 respectively:

localhost (127.0.0.1) - can be used to access Apache which is running on port number 80

localhost:8080 (127.0.0.1:8080) is the command used for accessing Tomcat which is running on port 8080


Step 3: Install Netbeans using the link given below for having the Integrated Development Environment (IDE) for developing Enterprise Web Application using Java.


Steps to Install Apache Tomcat Server on Ubuntu:

To install Apache Tomcat Server on Ubuntu OS, one must follow the step-by-step instructions given below:

Step 1: Update system repositories

Press “CTRL+ALT+T” to open the terminal of your Ubuntu 22.04 and run the below-given command to update system repositories:

$ sudo apt update

Step 2: Installation of Java

Before jumping into the installation of Apache Tomcat Server, it is essential to have “Java” on your system. For this purpose, execute the following command to install “OpenJDK 11”:

$ sudo apt install openjdk-11-jdk

Then, verify the version of the installed Java:

$ java version

Step 3: Check the availability of Apache Tomcat package

After fulfilling the requirements, check the availability of the Apache Tomcat package in the repository:

$ sudo apt-cache search tomcat

The given output signifies that the “tomcat9” package for download.

Step 4: Install Apache Tomcat Server on Ubuntu 22.04

After finding the required Apache Tomcat package, we will install it on Ubuntu 22.04 with the help of the below-given command:

$ sudo apt install tomcat9 tomcat9-admin

Press “y” to permit the installation for a few minutes.

Step 5: Check ports for Apache Tomcat Server

On Ubuntu 22.04, the Apache Tomcat Server automatically starts working after completing the installation. To validate this operation, you can utilize the “ss” command for displaying the network socket related information:

$ ss -ltn

The default port for the Apache Tomcat server is “8080”

Step 6: Open ports for Apache Tomcat Server

In case if the UFW firewall is activated on your system, then it may cause trouble while connecting external devices. So, to permit the incoming from any type of source to port “8080”, write out the following “ufw” command:

$ sudo ufw allow from any to any port 8080 proto tcp

Step 7: Test working of Apache Tomcat Server

To test its working specify your system loopback address with the number of the opened port for Apache Tomcat Server:

http://127.0.0.1:8080

After installation, Tomcat home page can be found on the local filesystem at: /var/lib/tomcat9/webapps/ROOT/index.html


Here are some links for learning more

https://linuxhint.com/install_apache_tomcat_server_ubuntu_2204/

Installing and Running Tomcat Apache Server

Quick Start Guide for Servlet Programming



Continue reading →
Thursday, 23 February 2023

Assignment Questions on Web Technology

0 comments

 ASSIGNMENT 1

(Includes Questions from Unit 1, 2 & 3)

Questions on CSS (Unit 1):

1.  What do web designers mean when they talk about a style?  

A style is simply a set of formatting instructions that can be applied to a piece of text.  

Styles can be cascaded.  This means that formats override any which were defined or included earlier in the document.  

For instance, we may include an external stylesheet which redefines the h1 tag, then write an h1 style in the head section of the page before finally redefining h1 in the body of the page.  The browser will use the last of these definitions when showing the content.

2.  Describe the different ways that styles can be added to a page.

There are three mechanisms by which we can apply styles to a HTML document:
  1. The style can be defined within the basic HTML tag using style attribute.  This method of defining a style within the html tag itself is called inline style.
  2. Styles can be define in the <head> section of an html file and applied to the whole document.  This type of defining styles is called internal style.
  3. Styles can also be defined in external files (with the extension .css) called stylesheets which can then be used in any document by including the stylesheet via a URI.

3.  What are the benefits of using styles compared with placing formatting directly into the element of a web page?

The syntax of the style definition changes when it is done inside an HTML tag.  The definition becomes an attribute, named style, of the tag.  The description of the style is passed as the value of the attribute and so must follow an equal sign.  The definition is placed inside quotation marks.  Defining the style inside the html tag is called inline style.

Defining the style using <style> tag in the header section allows the style to be defined separately from the content of the web page.  Internal styles are defined in the same html file for which the styles are defined.  Compared to the inline styles, internal styles can define styles for a group or class of html elements.

Defining the style in a separate file with the extension .css, separates the styles from the content of the web page to which they are applied.  External stylesheets define styles that can be applied to a collection of web pages belonging to a web site.  Through external style sheets uniformity can be maintained in applying styles to more than one web page. 

4.  What is a stylesheet class?  Illustrate with an example.

5.  HTML has two commands which are used to apply formatting to elements which are placed within them.  What are they?  Compare and contrast the use of them in a web page.

Questions on JavaScript (Unit 2):

6.  Create a web page which uses prompt() dialog to ask a user for their name, age and shoe size.  Display the information they enter on the page formatted as a small table.

Questions on Servlet (Unit 3):

7.  When a Servlet receives a request from a client, it has access to two objects for managing the request.  What are they?  Explain them with example.

8.  Describe the life cycle of a Servlet.  Also write a simple Servlet that reads three parameters from the form data.


ASSIGNMENT 2

(Include Questions from Unit 3, 4 &  5)

Questions on Servlets (Unit 3)

1.  List the differences between GenericServlet and HttpServlet.

2.  What are the advantages of Servlets over CGI Scripting.

3.  Explain in detail how HTTP Post request can be handled from a servler, using an example.

Questions on JSP (Unit 4)

4 .  Mention the techniques that are available for sharing user data among JSP pages.  Explain any two of them with sample code.

5.  Explain Anatomy of a JSP Page.

6.  What are Java Beans?  How do you make use of them in a JSP Page?

Bean means component. Components mean reusable objects. JavaBean is a reusable component. Java Bean is a normal java class that may declare properties, setter, and getter methods in order to represent a particular user form on the server-side.

Java Bean is useful to combine multiple simple values to an object and to send that object from one resource to another resource or one layer to another layer. For example, to keep form data into a single object we can use java bean. Java Bean is a specially constructed Java class written in Java and coded according to the Java Beans API specification.

Working of JavaBeans in JSP

First, the browser sends the request for the JSP page. Then the JSP page accesses Java Bean and invokes the business logic. After invoking the business logic Java Bean connects to the database and gets/saves the data. At last, the response is sent to the browser which is generated by the JSP.

Why do we need to use JavaBeans in JSP?

Accessing JavaBeans in JSP Application?

<jsp:useBean>

The jsp:useBean tag is utilized to start up an object of JavaBean or it can re-utilize the existing java bean object. The primary motivation behind jsp:useBean tag is to interface with bean objects from a specific JSP page. In this tag, it is consistently suggestible to give either application or meeting degree to the extension characteristic worth. 

At the point when the compartment experiences this label then the holder will get class characteristic worth for example completely qualified name of Bean class then the holder will perceive Bean .class record and perform Bean class stacking and launch. Subsequent to making the Bean object compartment will allot Bean object reference to the variable indicated as an incentive to id property. In the wake of getting Bean object reference holder will store Bean object in an extension indicated as an incentive to scope trait.

Syntax: <jsp:useBean id=”—” class”—” type”—” scope=”—”/>

Questions on PHP (Unit 5)

7.  Discuss about various functions used in PHP with examples.

8.  Define operator.  Explain different operators used in PHP.

9.  Write a PHP Program to find the factorial of a given Number.

Continue reading →
Sunday, 19 February 2023

Tutorial Questions on Web Technology

0 comments

Tutorias on Web Technology

TUTORIAL I
(Dated: 22-01-2024)

1.  List the formatting options that are provided for plain text in HTML?  How can the font size be changed using basic HTML rather than a stylesheet?



2.  Use an image as the background to a web page.  If you don't have any suitable ones in the cache of your browser then do Web search.  Many sites give away copyright free images that anyone can use.  Also try a number of different combinations of image and text formatting.  What combinations are generally successful?

3.  Rather than placing large images on a page, the preferred technique is to use thumb-nails by setting the height and width parameters to something like 100 pixels by 100 pixels.  Each thumbnail image is also a link to a full-sized version of the image.  Create an image gallery using this technique.  

4.  What advantages do tables have over other methods of presenting data?  Add a table to your web page.  Try different formatting options - how does the table look if it doesn't have a border, for instance?  (Solution: Here is a Tutorial on HTML Tables with Samle Code)

5.  Try using a simple frameset to dispaly two pages at the same time.  Split the screen first horizontally, then vertically.  Which do you prefer?

TUTORIAL II
(Dated: 12-02-2024)

1.  List the technologies that are used to create Dynamic web pages.

2.  Describe the Document Object Model (DOM).

3.  How is JavaScript included in HTML documents?  Can JavaScript be executed without using a Web Browser?

4.  What are functions in JavaScript?  How are they defined and used for handling events such as - onclick(), onmousemove(), onsubmit() etc.

5.  Write a simple JavaScript that adds some two numbers together or concatenates a couple of strings, and then shows the result of addition or concatenation in an alert() dialog on the page.

<html>
<head>
<script>
function addTwo()
{
const num1 = parseInt(prompt("Enter the First Number"));
const num2 = parseInt(prompt("Enter the Second Number"));
const sum = num1 + num2;
alert("The sum of " + num1 + " and " + num2 + " is " + sum);
}
var strFinal ="";
function concatString()
{
strFinal = strFinal + prompt("Entr the Next String");
alert("Concatenated String is " + strFinal);
}

</script>
</head>
<body>
<form>
<input type="button" value="Addition of Two" onclick="addTwo()"/>
<input type="button" value="Next String to Concatenate" onclick="concatString()"/>
</form>
</body>
<html>

Here is the demo.

TUTORIAL III
(Dated: 04-03-2024)

1.  What are servlets?  Explain the various stages of the life cycle of a servlet.

Servlets are server-side Java programs that are loaded and executed by a Web Server. They can be considered as server-side applets that accept requests from one or more clients (via the Web Server), perform some task, and return the result back to the client as a web page.

Servlet Life Cycle:
A servlet’s life cycle begins when the servlet container loads the servlet into memory – normally, in response to the first request that the servlet receives. Before the servlet can handle the request, the servlet container invokes the servlet’s init method for initializing the servlet variables and resources. Then the servlet’s service() method is called in response to the client’s request.
All requests are handled by the servlet’s service method, which receives the request, processes the request, and sends a response to the client. During the servlet’s life time, method service is called one per request. Each new request typically results in a new thread of execution (created by the servlet container) in which method service gets executed. When the servlet container terminates the servlet, the servlet’s destroy method is called to release servlet resources.

2.  Illustrate with example the process involved in reading the initial parameters of a servlet from servlet descriptor (web.xml).

Step 1: Provide the initialization Parameter in the XML file as follows:
<web-app>
<servlet>
<servlet-name>readParam</servlet-name>
<servlet-class>ReadInitParam</servlet-class>
                <init-param>
<param-name>CollegeName</param-name>
<param-value>MRECW, Maisammaguda, Dulapally, Hyd-100</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>readParam</servlet-name>
<url-pattern>/InitialParamDemo</url-pattern>
</servlet-mapping>
</web-app> 

Step 2:  Create an object of type ServletConfig (by calling getServletConfig method) and call its method getInitParameter():

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ReadInitParam extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter objPW = response.getWriter();
ServletConfig config = getServletConfig();
String strCollege = config.getInitParameter("CollegeName");
objPW.print("Name of the College where I study is : " + strCollege);
objPW.close();
}
}


3.  Explain session tracking using cookies in a servlet.

A Session simply means a particular interval of time.  Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize the particular user.  The figure given below shows the need for session tracking:


Session Tracking Techniques:
There are four techniques used in Session tracking:

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

Session Handling using Cookies:

Cookies are small pieces of information that are sent in response from the web server to the client. Cookies are the simplest technique used for storing client state.

Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.

Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to response object.

There are two types of cookies. They are Session Cookies and Persistent Cookies.

The session cookies do not have any expiration time. It is present in the browser memory. When the web browser is closed then the cookies are destroyed automatically.

The Persistent cookies have an expiration time. It is stored in the hard drive of the user and it is destroyed based on the expiry time.

When a user Start a web and request information from the website. The website server replies and it sends a cookie. This cookie is put on the hard drive. Next time when you return to the same website your computer will send the cookies back.

Here is a presentation on Session Handling using servlets.

 
4.  Write a simple servlet that reads three parameters from form data and process them to display a dynamic web page.

 import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ThreeParams extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading Three Request Parameters";
    out.println(ServletUtilities.headWithTitle(title) +
                "<BODY>\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                "<UL>\n" +
                "  <LI>param1: "
                + request.getParameter("param1") + "\n" +
                "  <LI>param2: "
                + request.getParameter("param2") + "\n" +
                "  <LI>param3: "
                + request.getParameter("param3") + "\n" +
                "</UL>\n" +
                "</BODY></HTML>");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
5.  Explain the difference between GenericServlet and HTTPServlet class provided for developing servlets in Servlet API.

The Servlet API is a part of the Servlet specification designed by Sun Microsystems. This API is supported by all Servlet containers, such as Tomcat and Weblogic. The API contains classes and interfaces that define a standard contract between the Servlet class and Servlet container (or Servlet engine). These classes and interfaces are packaged in the following two packages of the Servlet API:
  • javax.servlet &
  • javax.servlet.http
These packages contain classes and interfaces that allow the Servlet to access the basic services provided by the Servlet container. The javax.servlet package contains classes and interfaces to support generic, protocol-independent Servlet. These classes are extended by the classes in javax.servlet.http package to add HTTP-specific functionality.
Here are some valuable points about servlets, in general:

Servlet:-

  1. The Servlets runs as a thread in a web-container instead of in a seperate OS process.
  2. Only one object is created first time when first request comes, other request share the same object.
  3. Servlet is platform independent.
  4. Servlet is fast.
The following points differentiate the base classes provided in Servlet API:

GenericServlet:-

  1. General for all protocol.
  2. Implements Servlet Interface.
  3. Use Service method.

HttpServlet:-

  1. Only for HTTP Protocol.
  2. Inherit GenericServlet class.
  3. Use doPost, doGet method instead of service method.

TUTORIAL IV 

(Dated:  27-03-2024)

1.  Define JSP.  Compare JSP with Servltes.

Java Server Pages (JSP) is an extension of Servlet technology that simplifies the delivery of dynamic web content. It provides a set of predefined components for the web application programmers to develop server side scripts that can generate dynamic web pages.


Java provides two packages for JSP programming:
  • javax.servlet.jsp &
  • javax.servlet.jsp.tagext

In many ways, Java Server Pages look like standard HTML and XML documents. In fact, they normally include HTML or XML markup. Such markup is known as fixed-template data or fixed-template text.  Programmers tend to use JSP when most of the content sent to the client is fixed template data and only a small portion of the content is generated dynamically with Java code. On the other hand, Servlets are preferred only when a small portion of the content sent to the client is fixed-template data. 

As with servlets, JSPs normally execute as part of a Web Server, which acts as a container to JSP. When a JSP-enabled server receives the first request for a JSP, the JSP container translates that JSP into a Java servlet that handles the current request and the future requests to the JSP.  

The request and response mechanism and life cycle of a JSP are the same as that of a servlet. JSPs can define methods jspInit and jspDestroy (similar to servlet methods init and destroy), which the JSP container invokes when initializing a JSP, and terminating a JSP respectively.

2.  Discuss the major features of JSP Pages.

JSP often present dynamically generated content as part of an HTML document sent to the client in response to a request. In some cases, the content is static, but is output only if certain conditions are met during a request. JSP programmers can insert Java code and logic in a JSP using script.  To run JSP, we need to have a web server that supports JSP and also the packages jsp and jsp.tagext, which are part of the Java Servlet API.

The following are some of the features of JSP:

1) Extension to Servlet:  JSP technology is the extension to servlet technology and hence we can use all the features of servlet in JSP.  In addition, we can use implicit objects, predefined tags, expression language and Custom tags of JSP, that makes JSP development easy.
2) Easy to maintain:  JSP can be easily coded and managed because it allows a web developer to separate the business logic from presentation  logic. In servlet technology, both the business logic and the presentation logic are put together in a single java file.

3) Fast Development and Deployment: No need to recompile and redeploy after every updation in JSP.  When changes are made in a JSP page, we do not need to recompile and redeploy the code after its modification. On the other hand, modification in the servlet code reqires the recompilation of the code into class file before its execution.

4) Requires Less code than Servlet:  In JSP, we make use of lot of tags such as action tags and custom tags that leads to reduction in code written for JSP.


3.  Explain about the JSPprocessing?

JSP page is translated into servlet by the help of JSP translator.  The JSP translator is a part of webserver that is responsible to translate the JSP page into servlet.  Afterthat Servlet page is compiled by the compiler and gets converted into the class file.


A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each request.  Everything in the page that is not a JSP element is called template text. Template text can be any text: HTML, WML, XML, or even plain text.  

When a JSP page request is processed, the template text and dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.  Below are the steps that are required to process JSP Page –

1. Web browser sends an HTTP request to the web server requesting JSPpage.
2. Web server recognizes that the HTTP request by web browser is for JSP page by checking
the extension of the file (i.e.jsp)
3. Web server forwards HTTP Request to JSPengine.
4. JSP engine loads the JSP page from disk and converts it into aservlet
5. JSP engine then compiles the servlet into an executable class and forward original request
to a servletengine.
6. Servlet engine loads and executes the Servletclass.
7. Servlet produces an output in HTMLformat
8. Output produced by servlet engine is then passes to the web server inside an HTTP
response.
9. Web server sends the HTTP response to Web browser in the form of static HTMLcontent.
10. Web browser loads the static page into the browser and thus user can view the dynamically
generatedpage.

4.  Write about the Components of JSP and Explain.

JSP components include scriptlets, comments, expressions, declarations and escape sequence characters. Scriptlets are blocks of code delimited by <% and %>. They contain Java statements that the container places in method –jspService at translation time.




JSPs supports three comment styles: JSP comments, HTML comments and comments from the scripting language like JavaScript. JSP comments are delimited by <%-- and --%>. HTML comments are delimited with <!-- and -->. Scripting language comments are Java comments and are delimited by / and /. JSP comments and scripting-language comments are ignored and do not appear in the response to a client.  

A JSP expression, delimited by <%= and %> contains Java code that is evaluated when a client requests the JSP containing the expression. The container converts the result of a JSP expression to a String object, and then outputs the string as part of the response to the client.

Declarations (delimited by <%! and %>) enable a JSP programmer to define variables and methods. The variables become instance variables of the Servlet class and the methods become members. Declarations of variables and methods in a JSP use Java syntax. Hence, declaring a variable without using a semicolon is a syntax error.

Escape sequences are sequence of characters used in JSP to make use of the special characters like <% and %> as part of the output. The escape sequences are as follows:
<\% %\> \’ \” \\

5.  How do you establish a connection and retrieve data from a database in JSP?  Illustrate with example.

JDBC helps the programmers in performing the following activities:

1.  It helps a web developer to connect to a data source, like a database.

2.  It helps us in sending queries and updating statements to the database, and

3.  Retrieving and processing the results received from the database in terms of answering your query.

The following are the major steps involved in developing a JSP page that can connect to and retrieve data from a database:

Step1: Load and Register the Driver

First, you need to load the driver or register it before using it in the program. Registration is to be done once in your program. The forName() method of the Class class is used to register the driver class.

Syntaxpublic static void forName(String className)throws ClassNotFoundException 

You can register the Driver by following two ways:

  1. Class.forName(): Here we load the driver’s class file into memory at the runtime. No need of using new or creation of objects.
  2. DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time.
Step2: Establish a Database Connection

In order to establish communication with the database, you must first open a JDBC connection to the database. After loading the driver, establish connections using the DriverManager.getConnection() method. Following are three methods of DriverManager.getConnection():

  1. getConnection(String url)
  2. getConnection(String url, Properties prop)
  3. getConnection(String url, String user, String password)

Syntax: public static Connection getConnection(String url,String name,String password) throws SQLException

Step3: Create the Statement

Once a connection is established you can interact with the database. The createStatement() method of the Connection interface is used to create a statement. The object of the statement is responsible to execute queries with the database.

Syntax: public Statement createStatement()throws SQLException  

Step4: Execute the Query

Now it’s time to process the result by executing the query. The executeQuery() method of Statement interface is used to execute queries to the database.  This method returns the object of ResultSet that can be used to get all the records of a table. The executeUpdate(sql query) method of the Statement interface is used to execute queries of updating/inserting.

Syntax: public ResultSet executeQuery(String sql)throws SQLException

Step5: Close the Connection

So finally, we have sent the data to the specified location. By closing the connection object statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection.


TUTORIAL V
(DOC: 15-04-2024)

1.  List and Explain the Control Structures used PHP.

2.  How data are stored in Arrays in PHP.  Illustrate with an Example.

3.  Explain in detail the steps involved in connect a PHP Page with MySQL for data processing.

4.  Explain with example how files are used for storing and retrieving plain texts in PHP. 

5.  Develop a Web Page using PHP to read form hdata from a Web Client.
Continue reading →