CCS375 - WT Cia - 2 QB Answer Key
CCS375 - WT Cia - 2 QB Answer Key
SCHOOL OF ENGINEERING
                                                   Accredited by NAAC
                              Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                               Siruganur, Trichy -621 105.        www.mamse.in
     'server side' means everything that happens on the server, instead of on the client. In the past, nearly all
     business logic ran on the server side, and this included rendering dynamic webpages, interacting with
     databases, identity authentication, and push notifications.
2.
     Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
     platform-independent method for building Web-based applications.
     JSP technology is used to create web application just like Servlet technology. It can be thought of as an
     extension to servlet because it provides more functionality than servlet such as expression language, JSTL, etc.
     Define Applets
     Applets are applications designed to be transmitted over the network and executed by Java compatible web
3.   browsers.
machine.
     Session Tracking is a mechanism used by Web container to maintain state (data) of a user. It is also known as
5.   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 to particular user.
                                           M.A.M. SCHOOL OF ENGINEERING
                                                     Accredited by NAAC
                                Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                                 Siruganur, Trichy -621 105.        www.mamse.in
      Write down the methods of servlet interface
6.     Servlet interface provides common behavior to all the servlets.Servlet interface needs to be implemented for
           creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize
           the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.
      Define Servlet Life Cycle
7.
      A servlet life cycle can be defined as the entire process from its creation till the destruction.
      Write down the two commonly used Request methods?
9.
      A "packet switched network" is a digital network that transmits data by dividing it into small units called
10.   "packets," which are then independently routed through various network nodes (like routers) to reach their
      destination, where they are reassembled to form the original data; essentially, it allows multiple users to share
      network bandwidth efficiently by sending data in small, manageable chunks rather than dedicated, continuous
      streams, making it the foundation for most modern internet traffic.
Let us create a file with name HelloWorld.java with the code shown above. Place this file at
C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location must be added to
CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java
as follows −
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as
well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World
program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software
Development Kit (JDK). For this command to work properly, you have to include the location of the Java
                                   M.A.M. SCHOOL OF ENGINEERING
                                              Accredited by NAAC
                         Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                          Siruganur, Trichy -621 105.        www.mamse.in
         SDK that you are using in the PATH environment variable.
         If everything goes fine, above compilation would produce HelloWorld.class file in the same directory.
         Next section would explain how a compiled servlet would be deployed in production.
Servlet Deployment
         If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located
         in WEB-INF/classes/com/myorg/MyServlet.class.
         <servlet>
           <servlet-name>HelloWorld</servlet-name>
           <servlet-class>HelloWorld</servlet-class>
         </servlet>
         <servlet-mapping>
           <servlet-name>HelloWorld</servlet-name>
           <url-pattern>/HelloWorld</url-pattern>
         </servlet-mapping>
         Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There could be
         various entries in this table already available, but never mind.
         You are almost done, now let us start tomcat server using <Tomcat-installationdirectory>\bin\startup.bat
         (on Windows) or <Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
         type http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine, you would
         get the following result
a List down the methods of HttpServlet. Explain each of them with an example.
12
         1. doGet() Method
2. doPost() Method
3. doHead() Method
5. doDelete() Method
6. doOptions() Method
7. doTrace() Method
8. getLastModified() Method
  This method returns the time the HttpServletRequest object was last modified.
  If time is unknown the method will return a negative number.
  This method makes browser and proxy caches work more effectively.
  also reducing the load on server and network resources.
Modifier and Type: protected long
Syntax:
protected long getLastModified(HttpServletRequest request)
Parameter: request – an HttpServletRequest object that contains the request the client has made of
the servlet.
9. service() Method
This method receives standard HTTP requests from the public service method and dispatches them
to the doXXX methods defined in this class.
Modifier and Type: protected void
Syntax:
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
                                          M.A.M. SCHOOL OF ENGINEERING
                                                  Accredited by NAAC
                             Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                              Siruganur, Trichy -621 105.        www.mamse.in
        This method is used to dispatch client requests to the public service method.
        Modifier and Type: public void
        Syntax:
        public void service(ServletRequest request,ServletResponse response)
        throws ServletException,IOException
        package com.gfg;
        import javax.servlet.*;
        import javax.servlet.http.*;
              <servlet-mapping>
                                     M.A.M. SCHOOL OF ENGINEERING
                                             Accredited by NAAC
                        Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                         Siruganur, Trichy -621 105.        www.mamse.in
         <servlet-name>Test</servlet-name>
         <url-pattern>/test</url-pattern>
       </servlet-mapping>
     </web-app>
    In <servlet-name> we have given a logical name for our TestServlet class. So, if we use the method
    getServletName() it will return the logical name of Servlet and in this case, it will return ―Test‖.
    2. public abstract javax.servlet.ServletContext getServletContext()
    This method will simply return ServletContext Object. Web container creates one ServletContext object for
    every web application.
    3. public abstract java.lang.String getInitParameter(java.lang.String)
    We can store init parameters as a part of web.xml.
   XML
     <web-app>
      <servlet>
         <servlet-name>Test</servlet-name>
         <servlet-class>TestServlet</servlet-class>
         <init-param>
            <param-name>username</param-name>
            <param-value>xyz</param-value>
         </init-param>
     <init-param>
            <param-name>password</param-name>
            <param-value>welcome@123</param-value>
         </init-param>
      </servlet>
       <servlet-mapping>
         <servlet-name>Test</servlet-name>
         <url-pattern>/test</url-pattern>
       </servlet-mapping>
     </web-app>
    The advantage of using init parameters is we do not need to hard code values in source code and if we are
    not hard coding values in source code, to change values we don’t need to touch source code. We just need to
    change values in web.xml and re-deploy the application. These init parameters are specific to a Servlet for
    which you have configured them. By using getInitParameter() we can access the value of init parameters in
    our Servlet.
   Java
     import   javax.servlet.Servlet;
     import   javax.servlet.ServletRequest;
     import   javax.servlet.ServletResponse;
     import   javax.servlet.ServletConfig;
                 System.out.println(username);
                 System.out.println(password);
                }
                public void destroy(){
                }
                public ServletConfig getServletConfig(){
                  return config;
               }
                public String getServletInfo(){
                  return this.getClass().getName();
               }
           }
         An object of ServletContext is created by the web container at time of deploying the project. This object
         can be used to get configuration information from web.xml file. There is only one ServletContext object
         per web application.
         If any information is shared to many servlet, it is better to provide it from the web.xml file using
         the <context-param> element.
         Advantage of ServletContext
         Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the
         servlet. We provide this information from the web.xml file, so if the information is changed, we don't
         need to modify the servlet. Thus it removes maintenance problem.
            1. public String getInitParameter(String name):Returns the parameter value for the specified parameter nam
            2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameter
            3. public void setAttribute(String name,Object object):sets the given object in the application scope.
            4. public Object getAttribute(String name):Returns the attribute for the specified name.
            5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameter
               Enumeration of String objects.
            6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet co
b      Write a servlet program which displays the different image each time the user visits the page and the images
       are links.
                 Using FileInputStream class to read image and ServletOutputStream class for writing this
                 image content as a response. To make the performance faster, we have used BufferedInputStream
                 and BufferedOutputStream class.
                 In this example, we are assuming that you have java.jpg image inside the c:\test directory. You
                 may change the location accordingly.
                     1. index.html
                     2. DisplayImage.java
                     3. web.xml
                 index.html
                 This file creates a link that invokes the servlet. The url-pattern of the servlet is servlet1.
                                  M.A.M. SCHOOL OF ENGINEERING
                                             Accredited by NAAC
                        Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                         Siruganur, Trichy -621 105.        www.mamse.in
         1. <a href="servlet1">click for photo</a>
                 DisplayImage.java
                 This servlet class reads the image from the mentioned directory and writes the content in the
                 response object using ServletOutputStream and BufferedOutputStream classes.
         package com.javatpoint;
         import java.io.*;
         import javax.servlet.*;
         import javax.servlet.http.*;
         public class DisplayImage extends HttpServlet {
             bin.close();
             fin.close();
             bout.close();
             out.close();
             }
         }
     These Objects are the Java objects that the JSP Container makes available to the developers in each page
     and the developer can call them directly without being explicitly declared. JSP Implicit Objects are also
     called pre-defined variables.
     Following table lists out the nine Implicit Objects that JSP supports −
14    S.No.                                             Object & Description
                      request
             1
                      This is the HttpServletRequest object associated with the request.
                      response
             2
                      This is the HttpServletResponse object associated with the response to the client.
                          M.A.M. SCHOOL OF ENGINEERING
                                     Accredited by NAAC
                Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                 Siruganur, Trichy -621 105.        www.mamse.in
             out
     3
             This is the PrintWriter object used to send output to the client.
             session
     4
             This is the HttpSession object associated with the request.
             application
     5
             This is the ServletContext object associated with the application context.
             config
     6
             This is the ServletConfig object associated with the page.
             pageContext
     7
             This encapsulates use of server-specific features like higher performance JspWriters.
             page
     8       This is simply a synonym for this, and is used to call the methods defined by the
             translated servlet class.
             Exception
     9
             The Exception object allows the exception data to be accessed by designated JSP.
The request Object
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client
requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information including form data, cookies,
HTTP methods etc
             out.print(dataType dt)
     1
             Print a data type value
     2       out.println(dataType dt)
                                M.A.M. SCHOOL OF ENGINEERING
                                          Accredited by NAAC
                     Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                      Siruganur, Trichy -621 105.        www.mamse.in
Print a data type value then terminate the line with new line character.
                  out.flush()
          3
                  Flush the stream.
     The session Object
     The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way
     that session objects behave under Java Servlets.
     The session object is used to track client session between client requests.
     The application Object
     The application object is direct wrapper around the ServletContext object for the generated Servlet and
     in reality an instance of a javax.servlet.ServletContext object.
     This object is a representation of the JSP page through its entire lifecycle. This object is created when the
     JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
     By adding an attribute to application, you can ensure that all JSP files that make up your web application
     have access to it.
     The config Object
     The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around
     the ServletConfig object for the generated servlet.
     This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such
     as the paths or file locations etc.
     The following config method is the only one you might ever use, and its usage is trivial −
     config.getServletName();
     This returns the servlet name, which is the string contained in the <servlet-name> element defined in
     the WEB-INF\web.xml file.
     The pageContext Object
     The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext
     object is used to represent the entire JSP page.
     This object is intended as a means to access information about the page while avoiding most of the
     implementation details.
Explain in detail about Servlet Database Connectivity with an example of Student database.
     First of all we have a created database and we create some table fields which you can copy and use
                           M.A.M. SCHOOL OF ENGINEERING
                                      Accredited by NAAC
                 Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                  Siruganur, Trichy -621 105.        www.mamse.in
it:
Description of program:
In this example we have used JDBC connection in servlet.We have to first create the a table in
MySQL database and then connect it through JDBC to show all the records on web page. we have
used for some servlet method "doGet" and "doPost". The doGet() is used to get information from
the client/browser and doPost() is used to send information back to the browser.
ConnectorJDBC.java
package connector;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
out.print("<html>");
out.print("<head>");
out.print("<title>Hello Connect Database</title>");
out.print("</head>");
out.print("<name>");
out.print("<h1>Name from database</h1>");
out.print("<br/>");
out.print("</tr><br/>");
}
out.print("</body>");
out.print("</html>");
// out.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(stmt != null){
stmt.close();
}
if(conn != null){
conn.close();
}
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                          M.A.M. SCHOOL OF ENGINEERING
                                     Accredited by NAAC
                Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                 Siruganur, Trichy -621 105.        www.mamse.in
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>dbconnection</display-name>
<servlet>
<servlet-name>ConnectorJDBC</servlet-name>
<servlet-class>connector.ConnectorJDBC</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ConnectorJDBC</servlet-name>
<url-pattern>/ConnectorJDBC</url-pattern>
</servlet-mapping>
</web-app>
output
                                       M.A.M. SCHOOL OF ENGINEERING
                                                 Accredited by NAAC
                            Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                             Siruganur, Trichy -621 105.        www.mamse.in
     PHP is basically used for developing web based software applications.PHP is probably the most popular scripting
1.
     language on the web. It is used to enhance web pages.PHP is known as a server-sided language. That is because the
     PHP doesn't get executed on the client’s computer, but on the computer the user had requested the page from. The
     results are then handed over to client, and then displayed in the browser.
     List the data types used in PHP.
2.
     The term "Type Casting" refers to conversion of one type of data to another. Since PHP is a weakly typed
     language, the parser coerces certain data types into others while performing certain operations. For example, a
     string having digits is converted to integer if it is one of the operands involved in the addition operation.
     Implicit Type Casting
3.   Here is an example of coercive or implicit type casting −
     <?php
       $a = 10;
       $b = '20';
       $c = $a+$b;
       echo "c = " . $c;
     ?>
                                             M.A.M. SCHOOL OF ENGINEERING
                                                     Accredited by NAAC
                                Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                                 Siruganur, Trichy -621 105.        www.mamse.in
        In this case, $b is a string variable, cast into an integer to enable addition. It will produce the following output −
        c = 30
        Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a
        special search pattern in the form of text string.
4.
        They are basically used in programming world algorithms for matching some loosely defined patterns to
        achieve some relevant tasks. Some times regexes are understood as a mini programming language with a
        pattern notation which allows the users to parse text strings.
        The exact sequence of characters are unpredictable beforehand, so the regex helps in fetching the required
        strings based on a pattern definition.
        List the important characteristics of PHP.
            Open source
            Security
            Flexibility
5.          Objective oriented
            Database Connectivity
            PHP is open source
            Speed
            Easy to learn and use
            Php is a fast development
        Write a simple PHP Script.
        <!DOCTYPE html>
        <html>
        <head>
          <title>Simple PHP Script</title>
        </head>
6.      <body>
           <?php
             echo "Hello, World!";
           ?>
        </body>
        </html>
        How do you declare and initialize an array in PHP
     1. $season=array("summer","winter","spring","autumn");
     1.
     2. $season[0]="summer";
7. 3. $season[1]="winter";
     4. $season[2]="spring";
     5. $season[3]="autumn";
        Example
        File: array1.php
     1. <?php
                                              M.A.M. SCHOOL OF ENGINEERING
                                                        Accredited by NAAC
                                   Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                                    Siruganur, Trichy -621 105.        www.mamse.in
     2. $season=array("summer","winter","spring","autumn");
     3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
     4. ?>
     1.
          List some built in functions in PHP.
          <?php
            // Get current date
            $today = new DateTime('now');
9.        <!DOCTYPE html>
          <html>
          <head>
            <title>Dynamic Background Color</title>
            <style>
               body {
                  background-color: <?php echo $bg_color; ?>;
               }
            </style>
          </head>
          <body>
            <p>Today's background color is set based on the day of the week.</p>
          </body>
          </html>
11 a
         XML Declaration
         The XML document can optionally have an XML declaration. It is written as follows −
         <?xml version = "1.0" encoding = "UTF-8"?>
         Where version is the XML version and encoding specifies the character encoding used in the document.
         Syntax Rules for XML Declaration
               The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in
                lower-case.
               If document contains XML declaration, then it strictly needs to be the first statement of the XML
                document.
               The XML declaration strictly needs be the first statement in the XML document.
               An HTTP protocol can override the value of encoding that you put in the XML declaration.
    XML Attributes
    An attribute specifies a single property for the element, using a name/value pair. An XML-element can
    have one or more attributes. For example −
    <a href = "http://www.tutorial.com/">Tutorials!</a>
          ◦ You can also specify a URL by entering it in the file name field displayed in the dialog box from
             the Browse button. The stylesheet association will look like the following:
            href="http://myserver:8080/pe/axdocbook.style"
        7. Click the Add association button.
            To remove a stylesheet association, you can highlight a stylesheet with an association and
            click Delete association.
        8. Click OK to apply your choices and close the Modify Stylesheet Selection dialog box.
        9. Click Close in the Select Stylesheets dialog box to return to the document.
        10. You must save your document for the stylesheet association to take effect.
     Explain the following: i) XML namespace ii) XML style sheet. iii) XML attributes iv) XML
     Schema
     XML SCHEMAS
     XML Schema is commonly known as XML Schema Definition (XSD). It is used to
     describe and validate the structure and the content of XML data. XML schema defines the
     elements, attributes and data types. Schema element supports Namespaces. It is similar to a
12
     database schema that describes the data in a database.
     <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
     <?xml version="1.0" encoding="UTF-8"?>
     <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
     <xs:element name="contact">
     <xs:complexType><xs:sequence>
     <xs:element name="name" type="xs:string" />
                              M.A.M. SCHOOL OF ENGINEERING
                                         Accredited by NAAC
                    Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                     Siruganur, Trichy -621 105.        www.mamse.in
     <xs:element name="company" type="xs:string" />
     <xs:element name="phone" type="xs:int" /> </xs:sequence>
     </xs:complexType></xs:element> </xs:schema>
     XML Attributes
     Attributes are part of the XML elements. An element can have multiple unique
     attributes. Attribute gives more information about XML elements. To be more precise, they
     define properties of elements. An XML attribute is always a name-value pair.
     <element-name attribute1 attribute2 >
     ....content….
     < /element-name>
     where attribute1 and attribute2 has the following form: name = "value"
     XML Namespace
     An XML namespace is a collection of names that can be used as element or attribute names in an
     XML document. The namespace qualifies element names uniquely on the Web in order to avoid
     conflicts between elements with the same name.
     <BOOKS>
      <bk:BOOK xmlns:bk="urn:example.microsoft.com:BookInfo"
           xmlns:money="urn:Finance:Money">
       <bk:TITLE>Creepy Crawlies</bk:TITLE>
       <bk:PRICE money:currency="US Dollar">22.95</bk:PRICE>
      </bk:BOOK>
     </BOOKS>
     Describe the data base connections in PHP with suitable example.
     Selecting a reputable web hosting company is only the first step towards building and maintaining a
     successful website. Sometimes you may need to connect your PHP driven website to a database.
13   For most content management systems, this is done through the config.php file. Below is a sample
     PHP script that connects to a database and shows all the fields for a specific table you specify in the
     code.
                                 M.A.M. SCHOOL OF ENGINEERING
                                           Accredited by NAAC
                      Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                       Siruganur, Trichy -621 105.        www.mamse.in
     IMPORTANT: In order for the database connection to work, you will need to create the database,
     add the database user, and be sure that you attach a MySQL user to the database before attempting
     to run the script on the server.If you need to run a database script on your local computer, you will
     need to set up your computer to run Apache, MySQL, and PHP. You can do this by installing
     WAMP (Windows), MAMP (Mac), or XAMPP.
<?php
     $hostname="localhost";
     $username="your_dbusername";
     $password="your_dbpassword";
     $dbname="your_dbusername";
     $usertable="your_tablename";
     $yourfield = "your_field";
     if($result)
        { while($row = mysql_fetch_array($result))
           { $name = $row["$yourfield"];
              echo "Name: " . $name;
       }}
?>
     Control statements in PHP are conditional statements that execute a block of statements if the
     condition is correct. The statement inside the conditional block will not execute until the condition
     is satisfied.
     There are two types of control statements in PHP:
14        Conditional statements are used to execute code based on a condition. For example, you could use an
           if statement to check if a user is logged in, and then execute different code depending on whether they
           are or not.
          Loop statements are used to repeat a block of code a certain number of times. For example, you could
           use a while loop to keep asking a user for their input until they enter a valid value.
     Types
          The If statement
                             M.A.M. SCHOOL OF ENGINEERING
                                       Accredited by NAAC
                  Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                   Siruganur, Trichy -621 105.        www.mamse.in
      The ? Operator
      The switch statement
      Loops
      exit, die and return, exceptions
      Declare
PHP If statement
if(expression1)
{
  Only exceutes when the ic condition is correct.
}
elseif(expression2)
{
  Executed when the if expression1
  is false and the expression 2 is true.
}
else
{
  Executed only when the both if block are false.
}
PHP
Copy
The if statement executes a statement if the expression inside the parenthesis is evaluated to true, or
else the code is skipped to the next block. It may be a single statement followed by a semicolon and
it is a compound statement surrounded by a curly braces. An else statement may appear immediately
after the statement and have a statement of its own. It is executed only when the previous expression
is false or else it is not executed.
A simple if statement:
<?php
        if(date("D") == "Tue")
       {
           print("Hello");
       }
?>
C#
Copy
PHP ? operator
It is represented as a ternary operator and it is used as a conditional operator. It is mainly evaluated
to either false or true. If false the expression next to the ternary operator is executed or else
expression between the ternary operator and colon is executed.
condition expresion ? true : false;
PHP
Copy
It is mainly used to reduce the size of the code or else if can be used to reduce the complexity.
PHP Switch statement
Switch has many expressions and the condition is checked with each expression inside the switch.
There is a default statement in the switch which can be used in the else statement and both have the
same functionality and execute in the same way. A case is a beginning part for execution.
<?php
 $day = date(" l ");
 switch($day)
                         M.A.M. SCHOOL OF ENGINEERING
                                    Accredited by NAAC
               Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                Siruganur, Trichy -621 105.        www.mamse.in
 {
  case "monday":
     print($day);
     break;
 case "tuesday"
    print($day);
    break;
 case "wednesday":
   print($day);
   break;
 case "thursday":
   print($day);
   break;
 case "friday":
   print($day);
   break;
 case "saturday":
   print($day);
   break;
default:
 print($day);
}?>
PHP
Copy
Break is also a control statement used to break the execution of the following statement. In switch it
is able to compare two strings and execute the required statement.
When a case statement is executed for the required condition the remaining case statements are
skipped only when the break statement is used or else all the case statements are executed in the
switch statement.
PHP Loops
Loops are mainly used to repeat the process untill the conditions are met. Until the conditions
are met the loops repeatedly execute. If the the condition is not met, the loop will execute an
infinite number of times.
For loop,
<?php
for($a = 1; $a < = 5; $a++)
{
  print("value of a is $a<br>\n");
}
?>
PHP
Copy
Output
value of a is 1
value of a is 2
value of a is 3
value of a is 4
value of a is 5
The loop is executed 5 times beacuse the condition is not satisfied in the next step so it exits the
                                  M.A.M. SCHOOL OF ENGINEERING
                                              Accredited by NAAC
                         Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                          Siruganur, Trichy -621 105.        www.mamse.in
         loop and stops repeating the execution.
         PHP While Loop
         It is the simplest form of looping statement. It checks the expression, and if true it executse the
         statement or else skips the entire code. It is mainly used when the value is exactly known.
         <?php
          while (TRUE)
          {
            print("While loop is executed");
          }
         ?>
         PHP
         Copy
         The statement inside the while loop is executed when the condition is met else it skips the entire
         loop.
         PHP Do-while loop
         This loop is executed once even if the condition is not met. After executing once it will check for
         conditions and execute the statement until conditions are met.
         <?php
         $a=10;
         do
         {
          print($a<br>\n)
          a=a+a;
         } while (a < 50);
         ?>
         PHP
         Copy
         Output
         10
         20
         40
         PHP For Each statement
         It provides a formalized method for iterating over arrays. An array is a collection of values
         referenced by keys. The for each statement requires an array and a definition of the variable to
         receive each element.
         foreach (array as key = > value)
         {
           statement
         }
         DTD stands for Document Type Definition. It defines the legal building blocks of an XML
         document. It is used to define document structure with a list of legal elements and attributes.
15
         Purpose of DTD
         Its main purpose is to define the structure of an XML document. It contains a list of legal elements
         and define the structure with the help of them.
                               M.A.M. SCHOOL OF ENGINEERING
                                         Accredited by NAAC
                    Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                     Siruganur, Trichy -621 105.        www.mamse.in
    Checking Validation
    Before proceeding with XML DTD, you must check the validation. An XML document is called
    "well-formed" if it contains the correct syntax.
A well-formed and valid XML document is one which have been validated against DTD.
employee.xml
    <?xml version="1.0"?>
    <!DOCTYPE employee SYSTEM "employee.dtd">
    <employee>
      <firstname>vimal</firstname>
      <lastname>jaiswal</lastname>
      <email>[email protected]</email>
    </employee>
    In the above example, the DOCTYPE declaration refers to an external DTD file. The content of the
    file is shown in below paragraph.
employee.dtd
    PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the
    user.
    Cookie is created at server side and saved to client browser. Each time when client sends request to the
    server, cookie is embedded with request. Such way, cookie can be received at the server side.
      PHP $_COOKIE
   PHP $_COOKIE superglobal variable is used to get cookie.
   Example
1. $value=$_COOKIE["CookieName"];//returns cookie value
AJAX tutorial covers concepts and examples of AJAX technology for beginners and professionals.
     AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies
     like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.
1.
     AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.
     AJAX allows you to send only important information to the server not the entire page. So only valuable data from
     the client side is routed to the server side. It makes your application interactive and faster.
     As describe earlier, ajax is not a technology but group of inter-related technologies. AJAX technologies
     includes:
          HTML/XHTML and CSS
          DOM
          XML or JSON
          XMLHttpRequest
          JavaScript
2.   DOM
     It is used for dynamic display and interaction with data.
     XML or JSON
     For carrying data to and from server. JSON (Javascript Object Notation) is like XML but short and faster
     than XML.
     XMLHttpRequest
     For asynchronous communication between client and server. For more visit next page.
     JavaScript
     It is used to bring above technologies together.
     Independently, it is used mainly for client-side validation.
                                            M.A.M. SCHOOL OF ENGINEERING
                                                        Accredited by NAAC
                                   Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                                    Siruganur, Trichy -621 105.        www.mamse.in
How can you find out that an AJAX request has been completed?
         AJAX stands for Asynchronous JavaScript and XML. It is a set of web development techniques to create
         interactive web applications. AJAX allows a web page to communicate with a server without reloading the
3.
         page.
         Ready states are an important part of working with AJAX requests. The ready state of a request indicates the
         request’s status to the server and allows the client to track the progress of the request.
4.       There are two ways to pass parameters via a GET method. First is to user get parameters, such
         as url/?para=var or so. But I can also hard write this parameter in URL as long as my backend parser knows it,
         like url/<parameter>/.
         Define Web service?
         Web services are a type of internet software that use standardized messaging protocols and
         are made available from an application service provider's web server for a client or other
5.
         web-based programs to use. These services are sometimes referred to as web application
         services. They provide powerful, flexible interoperability, enabling machine-to-machine
         interactions across a network even with machines and software stacks not designed to work
         together natively.
         State the uses of WSDL.
         WSDL (Web Services Description Language) is primarily used to describe the functionality and
6.       interface of a web service, allowing different applications developed in various programming languages to easily
         communicate and interact with each other by providing a standardized, machine-readable definition of the
         service's operations, data types, and communication protocols, thus enabling interoperability across diverse
         systems.
         List out the four transmission types of WSDL?
         The four transmission types of Web Services Description Language (WSDL) are:
        One-way: The endpoint receives a message but does not return a response
7.
        Request-response: The endpoint receives a message and sends a correlated message
        Solicit-response: The endpoint sends a message and receives a correlated message
        Notification: The endpoint sends a message but does not wait for a response
         Define UDDI.
                 UDDI, or Universal Description, Discovery, and Integration, is a standard that allows
8.               users to discover and publish information about web services:
            What it does
                 UDDI is a platform-independent, XML-based framework that helps users find and describe
                                              M.A.M. SCHOOL OF ENGINEERING
                                                        Accredited by NAAC
                                   Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                                    Siruganur, Trichy -621 105.        www.mamse.in
                  web services and their providers. It also serves as a registry for businesses that offer web-based
                  services to list themselves and find partners.
             How it works
                  UDDI uses Web Service Definition Language (WSDL) to describe web service interfaces. It
                  also uses a SOAP-based protocol to define how clients communicate with UDDI registries.
      UDDI (Universal Description, Discovery and Integration) offers several key benefits in web
9.
      technologies, primarily by providing a standardized way to discover and access web services
      across different platforms, leading to increased interoperability, faster development times,
      and improved business agility
      What are the core elements of UDDI?
                  The core elements of Universal Description, Discovery, and Integration (UDDI) are
                  the four data structures that make up its data model:
             businessEntity
                  Represents a web service provider, including company name, contact details, and other
                  business information
10.
             businessService
                  Describes a service's business function
             bindingTemplate
                  Includes technical details about the service, such as a reference to its API
             tModel
                 Includes other attributes and metadata, such as taxonomy, transports, and digital signatures
                  To create a simple Java web service, you can use the JAX-WS (Java API for XML
                  Web Services) framework. Here's a basic example demonstrating how to create a
                  service that provides a "sayHello" functionality:
11        a       1. Set up your project:
                 IDE: Choose your preferred Java IDE (like Eclipse, IntelliJ IDEA).
                 Project structure: Create a new Java web project and add necessary dependencies for JAX-WS.
                  2. Create your service class:
                                       M.A.M. SCHOOL OF ENGINEERING
                                                 Accredited by NAAC
                            Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                             Siruganur, Trichy -621 105.        www.mamse.in
        Java
        import javax.jws.WebMethod;
        import javax.jws.WebService;
        @WebService
        public class HelloWorld {
            @WebMethod
            public String sayHello(String name) {
              return "Hello, " + name + "!";
            }
        }
        Explanation:
       @WebService:     This annotation marks the class as a web service.
       @WebMethod:   This annotation indicates that the sayHello method should be exposed as a web
        service operation.
        3. Deploy the service:
       Build a WAR file: Package your web service class into a WAR (Web Application Archive) file.
       Deploy on a server: Deploy the WAR file to a compatible application server like Tomcat,
        Glassfish, etc.
        Client-side usage (example using a Java client):
        Java
        import javax.xml.namespace.QName;
        import java.net.URL;
        import javax.xml.ws.Service;
             A mandatory element that contains the XML data being exchanged in the SOAP
             message. The body must be contained within the envelope and must follow any
             headers.
        SOAP Header
             An optional element that makes SOAP extensible via SOAP Modules.
        HTTP binding
           Defines the relationship between parts of the SOAP request message and various HTTP
           headers. All SOAP requests use the HTTP POST method and specify at least three
           HTTP headers: Content-Type, Content-Length, and a custom header SOAPAction.
Explain about the object that helps AJAX reload parts of a web page without reloading the whole page
ADVERTISEMENT
XML-RPC
This is the simplest XML-based protocol for exchanging information between computers.
SOAP
Explore our latest online courses and learn new skills at your own pace. Enroll and become a
certified expert to boost your career.
WSDL
WSDL is an XML-based language for describing web services and how to access them.
UDDI
UDDI is an XML-based standard for describing, publishing, and finding web services.
Explain the creation of a java web service Client in detail with examples
     The services that are accessible across various networks are Java Web Services. Since JavaEE 6, it has
     two APIs defined by Java for creating web services applications.
      JAX-WS for SOAP web services
      JAX-RS for RESTful web services.
     It is not necessary to add any jars in order to work with either of these APIs because they both use heavy
     annotations and are included in the standard JDK.
     JAX-WS
     The Jakarta EE API, known as JAX-WS, is used to develop and create web services, especially for
     SOAP service users. The development and deployment of web services clients and endpoints are made
     simpler by using annotations.
     Two ways to write JAX-WS application code are:
      RPC Style
14
      Document Style
     NOTE: JAX-RPC API was superseded by JAX-WS 2.0.
     JAX-RS
     JAX-RS is a framework for building RESTful web applications. Currently, there are two
     implementations for building JAX-RS :
      Jersey
      RESTeasy
     Implementation of Java Web Services
     1. Implementing SOAP Web Services with JAX-WS
     There are certain steps to implement SOAP Web Services with JAX-WS
     1. First, you need to define Service endpoint interfaces (SEI) which specify the methods to expose as
          web service.
     2. Next, you need to implement SEI with a Java class.
     3. Then you need to Annotate the SEI and its implementation class with JAX-WX annotations to
                              M.A.M. SCHOOL OF ENGINEERING
                                         Accredited by NAAC
                    Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                     Siruganur, Trichy -621 105.        www.mamse.in
        specify the web service details.
    4. Package web service classes to the WAR file and deploy it to a web server.
    2. Implementing RESTful Web Services with JAX-RS
    There are certain steps to implement RESTful Web Services with JAX-RS
    1. First you need to define the resources that represents the web services and its methods.
    2. Then you need to annotate the resource class and its methods with JAX-RS annotations to specify
        the web service package.
    3. At last we need to package the web service classes to the WAR file and deploy it to a web server.
    Examples of Java Web Services
    This is an example of how we can use JAX-WS to create a Java Web Service (JWS) using the data from
    the search results.
    1. The SEI (Service Endpoint Interface), which shows the procedures of web services
   Java
     import javax.jws.WebMethod;
     import javax.jws.WebService;
     @WebService
     public interface HelloWorld {
       @WebMethod
       String sayHello(String name);
     }
import javax.jws.WebService;
     @WebService(endpointInterface = "com.example.HelloWorld")
     public class HelloWorldImpl implements HelloWorld {
       public String sayHello(String name) {
          return "Hello " + name + "!";
       }
     }
    3. Annotate the SEI and it’s implementation class with JAX-WX annotations to specify the web
    services.
   Java
     import javax.jws.WebMethod;
     import javax.jws.WebService;
     @WebService
     public interface HelloWorld {
       @WebMethod
       String sayHello(String name);
     }
import javax.jws.WebService;
     @WebService(endpointInterface = "com.example.HelloWorld")
                                       M.A.M. SCHOOL OF ENGINEERING
                                                  Accredited by NAAC
                             Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                              Siruganur, Trichy -621 105.        www.mamse.in
         JavaScript Object Notation (JSON) is a standard text-based format for representing structured
         data based on JavaScript object syntax. It is commonly used for transmitting data in web
         applications (e.g., sending some data from the server to the client, so it can be displayed on a web
         page, or vice versa). You'll come across it quite often, so in this article, we give you all you need
         to work with JSON using JavaScript, including parsing JSON so you can access data within it,
         and creating JSON.
                            A basic understanding of HTML and CSS, familiarity with JavaScript basics (see Fir
         Prerequisites:
                            steps and Building blocks) and OOJS basics (see Introduction to objects).
Objective: To understand how to work with data stored in JSON, and create your own JSON strings.
         JSON is a text-based data format following JavaScript object syntax, which was popularized
         by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be
         used independently from JavaScript, and many programming environments feature the ability to
         read (parse) and generate JSON.
15
         JSON exists as a string — useful when you want to transmit data across a network. It needs to be
         converted to a native JavaScript object when you want to access the data. This is not a big issue
         — JavaScript provides a global JSON object that has methods available for converting between
         the two.
         Note: Converting a string to a native object is called deserialization, while converting a native
         object to a string so it can be transmitted across the network is called serialization.
         A JSON string can be stored in its own file, which is basically just a text file with an extension
         of .json, and a MIME type of application/json.
JSON structure
         As described above, JSON is a string whose format very much resembles JavaScript object literal
         format. You can include the same basic data types inside JSON as you can in a standard
         JavaScript object — strings, numbers, arrays, booleans, and other object literals. This allows you
         to construct a data hierarchy, like so:
         JSONCopy to Clipboard
         {
             "squadName": "Super hero squad",
                                  M.A.M. SCHOOL OF ENGINEERING
                                           Accredited by NAAC
                      Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
                                       Siruganur, Trichy -621 105.        www.mamse.in
    "homeTown": "Metro City",
    "formed": 2016,
    "secretBase": "Super tower",
    "active": true,
    "members": [
      {
        "name": "Molecule Man",
        "age": 29,
        "secretIdentity": "Dan Jukes",
        "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
      },
      {
        "name": "Madame Uppercut",
        "age": 39,
        "secretIdentity": "Jane Wilson",
        "powers": [
          "Million tonne punch",
          "Damage resistance",
          "Superhuman reflexes"
        ]
      },
      {
        "name": "Eternal Flame",
        "age": 1000000,
        "secretIdentity": "Unknown",
        "powers": [
          "Immortality",
          "Heat Immunity",
          "Inferno",
          "Teleportation",
          "Interdimensional travel"
        ]
      }
    ]
}
If we loaded this string into a JavaScript program and parsed it into a variable
called superHeroes for example, we could then access the data inside it using the same dot/bracket
notation we looked at in the JavaScript object basics article.
JSCopy to Clipboard
superHeroes.homeTown;
superHeroes["active"];
To access data further down the hierarchy, you have to chain the required property names and
array indexes together. For example, to access the third superpower of the second hero listed in
the members list, you'd do this:
JSCopy to Clipboard
superHeroes["members"][1]["powers"][2];
     The AJAX model allows web developers to create web applications that are able to dynamically
    interact with the user. It will also be able to quickly make a background call to web servers to retrieve
    the required application data. Then update the small portion of the web page without refreshing the
    whole web page.
    AJAX applications are much more faster and responsive as compared to traditional web applications.
    It creates a great balance between the client and the server by allowing them to communicate in the
    background while the user is working in the foreground.
    In the AJAX applications, the exchange of data between a web browser and the server is
    asynchronous means AJAX applications submit requests to the web server without pausing the
    execution of the application and can also process the requested data whenever it is returned. For
    example, Facebook uses the AJAX model so whenever we like any post the count of the like button
    increase instead of refreshing the whole page.
Working of AJAX
    Traditional web applications are created by adding loosely web pages through links in a predefined
    order. Where the user can move from one page to another page to interact with the different portions
    of the applications. Also, HTTP requests are used to submit the web server in response to the user
b   action. After receiving the request the web server fulfills the request by returning a new webpage
    which, then displays on the web browser. This process includes lots of pages refreshing and waiting.
AJAX Technologies
    The technologies that are used by AJAX are already implemented in all the Morden browsers. So the
    client does not require any extra module to run the AJAX application.The technologies used by AJAX
    are −Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or
    we can say that it is used to create AJAX applications.
AJAX change this whole working model by sharing the minimum amount of data between the web
browser and server asynchronously. It speedup up the working of the web applications. It provides a
desktop-like feel by passing the data on the web pages or by allowing the data to be displayed inside
the existing web application. It will replace loosely integrated web pages with tightly integrated web
pages. AJAX application uses the resources very well. It creates an additional layer known as AJAX
engine in between the web application and web server due to which we can make background server
calls using JavaScript and retrieve the required data, can update the requested portion of a web page
without casing full reload of the page. It reduces the page refresh timing and provides a fast and
responsive experience to the user. Asynchronous processes reduce the workload of the web server by
dividing the work with the client computer. Due to the reduced workload web servers become more
responsive and fast.
AJAX Technologies
The technologies that are used by AJAX are already implemented in all the Morden browsers. So the
client does not require any extra module to run the AJAX application.The technologies used by AJAX
are −Javascript − It is an important part of AJAX. It allows you to create client-side functionality. Or
we can say that it is used to create AJAX applications.