0% found this document useful (0 votes)
5 views42 pages

CCS375 - WT Cia - 2 QB Answer Key

The document outlines the curriculum for the Web Technologies course (CCS375) at M.A.M. School of Engineering for the academic year 2024-2025. It covers key concepts such as Servlets, JSP, Applets, session tracking, and HTTP request methods, along with lifecycle methods and examples of servlet implementation. Additionally, it discusses the ServletConfig interface and its methods, providing a comprehensive overview of server-side programming in Java.

Uploaded by

ksathishkm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views42 pages

CCS375 - WT Cia - 2 QB Answer Key

The document outlines the curriculum for the Web Technologies course (CCS375) at M.A.M. School of Engineering for the academic year 2024-2025. It covers key concepts such as Servlets, JSP, Applets, session tracking, and HTTP request methods, along with lifecycle methods and examples of servlet implementation. Additionally, it discusses the ServletConfig interface and its methods, providing a comprehensive overview of server-side programming in Java.

Uploaded by

ksathishkm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

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

Department of Computer Science and Engineering


Academic Year 2024-2025 (Odd Semester)
Unit - III
Sub.Code/Sub.Name : CCS375 – Web Technologies Date :
Year/Sem. : III / V

Answer All the Questions


Part A (10x2=20 Marks)
Define Servlets
Servlet technology is used to create web application (resides at server side and generates dynamic web page).
1. Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was popular as a server-side programming language. But there were many
disadvantages of this technology.
What do you mean by Server-side?

'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.

Write about the life cycle methods of a Servlet.

The following are the paths followed by a servlet


4.

llector of the JVM.


List the common mechanisms used for session tracking.

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?

The http request methods are:


GET - Asks to get the resource at the requested URL
POST -Asks the server to accept the body info attached. It is like GET request with extra info sent with the
8. request.
HEAD - Asks for only the header part of whatever a GET would return. Just like GET but with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS - Asks for a list of the HTTP methods to which the thing at the request URL can respond
Distinguish between CGI and servlets.

9.

Define packet switched networks.

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.

Part B (5x16=80 Marks)


Explain the concept of Servlets with an example program
11
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web
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
application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP requests.

// Import required java libraries


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

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}

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

By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and


the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

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.

For now, let us copy HelloWorld.class into <Tomcat-installationdirectory>/webapps/ROOT/WEB-


INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/

<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

 This method is used to handle the GET request on the server-side.


 This method also automatically supports HTTP HEAD (HEAD request is a GET request which
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
returns nobody in response ) request.
 The GET type request is usually used to preprocess a request.
Modifier and Type: protected void
Syntax:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException

2. doPost() Method

 This method is used to handle the POST request on the server-side.


 This method allows the client to send data of unlimited length to the webserver at a time.
 The POST type request is usually used to post-process a request.
Modifier and Type: protected void
Syntax:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException

3. doHead() Method

 This method is overridden to handle the HEAD request.


 In this method, the response contains the only header but does not contain the message body.
 This method is used to improve performance (avoid computing response body).
Modifier and Type: protected void
Syntax:
protected void doHead(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
 This method is overridden to handle the PUT request.
 This method allows the client to store the information on the server(to save the image file on
the server).
 This method is called by the server (via the service method) to handle a PUT request.
Modifier and Type: protected void
Syntax:
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException

5. doDelete() Method

 This method is overridden to handle the DELETE request.


 This method allows a client to remove a document or Web page from the server.
 While using this method, it may be useful to save a copy of the affected URL in temporary
storage to avoid data loss.
Modifier and Type: protected void
Syntax:
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
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
throws ServletException,IOException

6. doOptions() Method

 This method is overridden to handle the OPTIONS request.


 This method is used to determine which HTTP methods the server supports and returns an
appropriate header.
Modifier and Type: protected void
Syntax:
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException

7. doTrace() Method

 This method is overridden to handle the TRACE request.


 This method returns the headers sent with the TRACE request to the client so that they can be
used in debugging.
Modifier and Type: protected void
Syntax:
protected void doTrace(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException

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

10. service() Method

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.*;

// here GFGServlet class inherit HttpServlet


public class GFGServlet extends HttpServlet {

// we are defining the doGet method of HttpServlet


// abstract class
public void doGet(HttpServletRequest rq,
HttpServletResponse rs)
{
// here user write code to handle doGet request
}

// we are defining the doPost method of HttpServlet


// abstract class
public void doPost(HttpServletRequest rq,
HttpServletResponse rs)
{
// here user write code to handle doPost request
}

b Discuss the methods of SevletConfig with an example.

There are 4 Methods in the ServletConfig interface


1. public abstract java.lang.String getServletName()
2. public abstract javax.servlet.ServletContext getServletContext()
3. public abstract java.lang.String getInitParameter(java.lang.String)
4. public abstract java.util.Enumeration<java.lang.String> getInitParameterNames()
1. public abstract java.lang.String getServletName()
While configuring Servlet in web.xml we have to give a logical name to our servlet. Let’s say we have a
Servlet class TestServlet and we want to configure it in web.xml.
 XML
<web-app>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>

<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;

public class TestServlet implements Servlet{


private ServletConfig config;
// web container will call this
// method by passing ServletConfig
public void init(ServletConfig config){
this.config=config;
}

public void service(ServletRequest request, ServletResponse response){


// pass <param-name> to get <param-value>
String username=config.getInitParameter("username"); // xyz
String password=config.getInitParameter("password"); // welcome@123
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

System.out.println(username);
System.out.println(password);
}
public void destroy(){
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return this.getClass().getName();
}
}

4. public abstract java.util.Enumeration<java.lang.String> getInitParameterNames()


This method will return Enumeration having names of all init parameter names.

a Explain the methods of Servletcontext with an example

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.

Usage of ServletContext Interface


There can be a lot of usage of ServletContext object. Some of them are as follows:
13 1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.
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

Commonly used methods of ServletContext interface


There is given some commonly used methods of ServletContext interface.

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

How to get the object of ServletContext interface


1. getServletContext() method of ServletConfig interface returns the object of ServletContext.
2. getServletContext() method of GenericServlet class returns the object of ServletContext.

Syntax of getServletContext() method


1. public ServletContext getServletContext()

Example of getServletContext() method


1. //We can get the ServletContext object from ServletConfig object
2. ServletContext application=getServletConfig().getServletContext();
3.
4. //Another convenient way to get the ServletContext object
5. ServletContext application=getServletContext()

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.

You need to use the content type image/jpeg.

In this example, we are assuming that you have java.jpg image inside the c:\test directory. You
may change the location accordingly.

To create this application, we have created three files:

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 {

public void doGet(HttpServletRequest request,HttpServletResponse response)


throws IOException
{
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("c:\\test\\java.jpg");

BufferedInputStream bin = new BufferedInputStream(fin);


BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}

bin.close();
fin.close();
bout.close();
out.close();
}
}

Explain about JSP object in detail.

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

The response Object


The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server
creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this
object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.

The out Object


The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content
in a response.
The initial JspWriter object is instantiated differently depending on whether the page is buffered or not.
Buffering can be easily turned off by using the buffered = 'false' attribute of the page directive.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However,
JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object,
JspWriter throws IOExceptions.
Following table lists out the important methods that we will use to write boolean char, int, double,
object, String, etc.
S.No. Method & Description

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.

The page Object


This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
The page object is really a direct synonym for the this object.
The exception Object
The exception object is a wrapper containing the exception thrown from the previous page. It is typically
used to generate an appropriate response to the error condition.

Explain in detail about Servlet Database Connectivity with an example of Student database.

Requirements to connect with the MySQL database in Servlet:

MySQL should be installed in your computer.


15
MySQL connector JAR (should be kept into lib folder).

How to connect database in servlet.This are as follows:

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:

CREATE TABLE `userinformation` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`sex` varchar(10) DEFAULT NULL,
`address` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

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.

PrintWriter out = response.getWriter():-PrintWriter is a representations of objects to a text-output


stream. This class implements all of the print methods found in PrintStream. It does not contain
methods for writing raw bytes, for which a program should use unencoded byte streams.

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;

public class ConnectorJDBC extends HttpServlet{


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
doProcess(request,response);
}catch(SQLException e){
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
doProcess(request,response);
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
}catch(SQLException e){
e.printStackTrace();
}
}
private void doProcess(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException , SQLException{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/naulej","root","root");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from userinformation");

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/>");

System.out.println("Get value from table userinformation.");


while(rs.next()){
out.println("<tr>");
out.print("Name : " + rs.getString("name"));
out.print("\t\t\t");

out.print("Sex : " + rs.getString("sex"));

out.print("Address : " + rs.getString("address"));

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

Department of Computer Science and Engineering


Academic Year 2024-2025 (Odd Semester)
Unit - 4
Sub.Code/Sub.Name : CCS375 – Web Technologies Date :
Year/Sem. : III / V

Answer All the Questions


Part A (10x2=20 Marks)
Define PHP.

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.

How type conversion is done in PHP?

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

Write the uses of text manipulation with regular expression in PHP.

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.

Built-in PHP functions commonly used in web development include:


strlen() (to get string length),
strtoupper() (to convert a string to uppercase),
array_push() (to add elements to the end of an array),
date() (to format and display current date/time),
8.
rand() (to generate a random number),
file_get_contents() (to read file content as a string),
count() (to count elements in an array),
explode() (to split a string into an array using a delimiter),
implode() (to combine array elements into a string),
htmlspecialchars() (to convert special HTML characters to entities),
trim() (to remove whitespace from the beginning and end of a string).
Write a PHP script to set the background color to blue on Tuesday in a given date.

<?php
// Get current date
$today = new DateTime('now');

// Check if today is Tuesday


if ($today->format('l') === 'Tuesday') {
$bg_color = 'blue';
} else {
$bg_color = 'white'; // Default background color
}
?>

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>

What is meant by a XML namespace?


An XML namespace is a collection of names that can be used as element or attribute names in an XML
10.
document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between
elements with the same name.
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

Part B (5x16=80 Marks)


List and explain the XML syntax rules in detail.

Following is a complete XML document −


<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

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.

Tags and Elements


An XML file is structured by several XML-elements, also called XML-nodes or XML-tags. The names
of XML-elements are enclosed in triangular brackets < > as shown below −
<element>
Syntax Rules for Tags and Elements
Element Syntax − Each XML-element needs to be closed either with start or with end elements as
shown below −
<element>....</element>
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
or in simple-cases, just this way −
<element/>
Nesting of Elements − An XML-element can contain multiple XML-elements as its children, but the
children elements must not overlap. i.e., an end tag of an element must have the same name as that of the
most recent unmatched start tag.
The Following example shows incorrect nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint
</contact-info>
</company>
The Following example shows correct nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint</company>
<contact-info>
Root Element − An XML document can have only one root element. For example, following is not a
correct XML document, because both the x and y elements occur at the top level without a root element

<x>...</x>
<y>...</y>
The Following example shows a correctly formed XML document −
<root>
<x>...</x>
<y>...</y>
</root>
Case Sensitivity − The names of XML-elements are case-sensitive. That means the name of the start
and the end elements need to be exactly in the same case.
For example, <contact-info> is different from <Contact-Info>

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>

Write down the steps how a XMLdocument can be displayed on a browser.


To display an XML document in a web browser:
1. You must first decide whether or not your XML document needs to reference a document type
declaration (DTD). Browsers don't generally need one to display your document properly.
Choose one of the following approaches:
◦ If you do not want to reference a DTD, you will need to write out a version of your document that
b can be displayed by a browser using the write command:
write -noheader -flatten both -nonasciichar numref filename.xml
Make sure that this version of your document is open and then proceed to the next step.
Proceed to step two.
▪ The DTD and document can be saved in different directories, but they must be on the same web
server. In this case, use the write command to write out your document with the -sysid modifier.
For example:
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 -sysid "http://www.some_site.com/doctypes
/axdocbook/axdocbook.dtd" filename.xml
The system ID can also be a relative URI, for example:
write -sysid "../../doctypes/axdocbook
/axdocbook.dtd" filename.xml
Make sure that this version of your document is open and proceed to the next step.
2. Make sure the stylesheet is located on the same web server as your document. We recommend
that you save the stylesheet in the same directory as the document.
3. Use Arbortext Editor to open the document to which you want to add the stylesheet association.
4. ChooseFormat > Select Stylesheets to open the Select Stylesheet dialog box.
5. Highlight HTML File in the Selected for list and click the Modify button.
6. In the Modify HTML File Stylesheet Selection dialog box, you'll see a list of all of the available
stylesheets for producing HTML output. The stylesheets are either locally available or offered
by Arbortext Publishing Engine (Arbortext Publishing Engine stylesheets have a (pe) notation).
Choose a stylesheet based on the following considerations:
◦ If the stylesheet is located in the document directory, the stylesheet association will be written
with a relative URI that is just the stylesheet's file name.
◦ If the stylesheet is located in the document type directory, select it from the list displayed in
the Modify HTML File Stylesheet Selection dialog box.
▪ The stylesheet association href will still use a relative URI containing the stylesheet file name (for
example, href="mydoctype.xsl").
▪ If the document must have a relative path reference to the stylesheet, you need to save your
document in Arbortext Editor, close it, and open your document in a text editor. Change
the href of your stylesheet association to an accurate relative path, for example:
href="../../doctypes/mydoctype/mydoctype.xsl"

◦ 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"

XSL (XML Style Sheet)


XML concentrates on the structure of the information and not its appearance. The
W3C has published two recommendations for style sheets: CSS (Cascading Style Sheet) and
XSL(XML Style sheet Language).XSL supports transforming the document before display.
XSL would typically be used for advanced styling. XSL originally consisted of three parts:
• XSLT (XSL Transformation) - a language for transforming XML documents
• XPath - a language for navigating in XML documents
• XSL-FO (XSL Formatting Objects) - a language for formatting XML documents
XSL
<P><B>Table of Contents</B></P> <UL>
<xsl:for-each select=‖article/section/title‖>
<LI><A><xsl:value-of select=‖.‖/></A></LI>
</xsl:for-each> </UL>

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

//Sample Database Connection Script


//Setup connection variables, such as database username
//and password

$hostname="localhost";
$username="your_dbusername";
$password="your_dbpassword";
$dbname="your_dbusername";
$usertable="your_tablename";
$yourfield = "your_field";

//Connect to the database


$connection = mysql_connect($hostname, $username, $password); mysql_select_db($dbname, $connection);

//Setup our query


$query = "SELECT * FROM $usertable";

//Run the Query


$result = mysql_query($query);

//If the query returned results, loop through


// each result

if($result)
{ while($row = mysql_fetch_array($result))
{ $name = $row["$yourfield"];
echo "Name: " . $name;
}}

?>

Explain about the control statements in PHP with example.

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
}

a Discuss in detail about the XML DTD

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.

Visit http://www.xmlvalidation.com to validate the XML file.

Valid and well-formed XML document with DTD


Let's take an example of well-formed and valid XML document. It follows all the rules of 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

<!ELEMENT employee (firstname,lastname,email)>


<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT email (#PCDATA)>
b Explain about cookies in PHP with example.

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.

In short, cookie can be created, sent and received at server end.


Note: PHP Cookie must be used before <html> tag.
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 setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it
by $_COOKIE superglobal variable.
Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
1. setcookie("CookieName", "CookieValue");/* defining name and value only*/
2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or 360
0 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example
1. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example


File: cookie1.php
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:

Cookie Value: Sonoo

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.
File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>
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

Department of Computer Science and Engineering


Academic Year 2024-2025 (Odd Semester)
Unit - 5
CCS375 – Web Technologies
Sub.Code/Sub.Name : Date :
Security
Year/Sem. : III / V

Answer All the Questions


Part A (10x2=20 Marks)
Define Ajax

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.

List out the technologies are being used in AJAX.

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

HTML/XHTML and CSS


These technologies are used for displaying content and style. It is mainly used for presentation.

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.

Write down the different ways to pass parameters to the server?

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.

Write down the benefits of UDDI.

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

Part B (5x16=80 Marks)


With a simple example illustrate the steps to create a java web service.

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;

public class HelloWorldClient {

public static void main(String[] args) throws Exception {


URL url = new URL("http://localhost:8080/your-service/HelloWorld?wsdl");
QName qname = new QName("http://your-package/", "HelloWorld");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
String response = hello.sayHello("Alice");
System.out.println(response); // Prints: "Hello, Alice!"
}
}

Describe the major elements of SOAP.

The major elements of SOAP (Simple Object Access Protocol) are:


 SOAP Envelope
b
The root element of all SOAP calls, it encloses the entire message to be sent to an
application. The header and body are child elements of the SOAP Envelope.
 SOAP Body
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

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

The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This
means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera) have a built-in
XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Example
var xhttp = new XMLHttpRequest();
Try it Yourself »
The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
12
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

Access Across Domains


For security reasons, modern browsers do not allow access across domains.
This means that both the web page and the XML file it tries to load, must be located on the same
server.
The examples on W3Schools all open XML files located on the W3Schools domain.
If you want to use the example above on one of your own web pages, the XML files you load
must be located on your own server.

ADVERTISEMENT

XMLHttpRequest Object Methods


Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object


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

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

send() Sends the request to the server


Used for GET requests

send(string) Sends the request to the server.


Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties


Property Description

onreadystatechange Defines a function to be called when the readyState property

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")


13 Show the relationship between SOAP, UDDI, WSIL and WSDL
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

XML-RPC

This is the simplest XML-based protocol for exchanging information between computers.

 XML-RPC is a simple protocol that uses XML messages to perform RPCs.


 Requests are encoded in XML and sent via HTTP POST.
 XML responses are embedded in the body of the HTTP response.
 XML-RPC is platform-independent.
 XML-RPC allows diverse applications to communicate.
 A Java client can speak XML-RPC to a Perl server.
 XML-RPC is the easiest way to get started with web services.

To learn more about XML-RPC, visit our XML-RPC Tutorial.

SOAP

SOAP is an XML-based protocol for exchanging information between computers.

 SOAP is a communication protocol.


 SOAP is for communication between applications.
 SOAP is a format for sending messages.
 SOAP is designed to communicate via Internet.
 SOAP is platform independent.
 SOAP is language independent.
 SOAP is simple and extensible.
 SOAP allows you to get around firewalls.
 SOAP will be developed as a W3C standard.

To learn more about SOAP, visit our SOAP Tutorial.

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.

 WSDL stands for Web Services Description Language.


 WSDL was developed jointly by Microsoft and IBM.
 WSDL is an XML based protocol for information exchange in decentralized and distributed
environments.
 WSDL is the standard format for describing a web service.
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
 WSDL definition describes how to access a web service and what operations it will perform.
 WSDL is a language for describing how to interface with XML-based services.
 WSDL is an integral part of UDDI, an XML-based worldwide business registry.
 WSDL is the language that UDDI uses.
 WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

To learn more about WSDL, visit our WSDL Tutorial.

UDDI

UDDI is an XML-based standard for describing, publishing, and finding web services.

 UDDI stands for Universal Description, Discovery, and Integration.


 UDDI is a specification for a distributed registry of web services.
 UDDI is platform independent, open framework.
 UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.
 UDDI uses WSDL to describe interfaces to web services.
 UDDI is seen with SOAP and WSDL as one of the three foundation standards of web
services.
 UDDI is an open industry initiative enabling businesses to discover each other and define how
they interact over the Internet.

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);
}

2. Implement the SEI with java class


 Java

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

public class HelloWorldImpl implements HelloWorld {


public String sayHello(String name) {
return "Hello " + name + "!";
}
}

a Explain the concept of JSON concept with example.

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.

No, really, what is JSON?

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];

1. First, we have the variable name — superHeroes.


2. Inside that, we want to access the members property, so we use ["members"].
3. members contains an array populated by objects. We want to access the second object inside the
array, so we use [1].
4. Inside this object, we want to access the powers property, so we use ["powers"].
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
5. Inside the powers property is an array containing the selected hero's superpowers. We want the
third one, so we use [2].

Explain about Ajax Client Server Architecture

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.

 XML − It is used to exchange data between web server and client.


 The XMLHttpRequest − It is used to perform asynchronous data exchange between a web
browser and a web server.
 HTML and CSS − It is used to provide markup and style to the webpage text.
 DOM − It is used to interact with and alter the webpage layout and content dynamically.
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

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.

 XML − It is used to exchange data between web server and client.


 The XMLHttpRequest − It is used to perform asynchronous data exchange between a web
browser and a web server.
 HTML and CSS − It is used to provide markup and style to the webpage text.
 DOM − It is used to interact with and alter the webpage layout and content dynamically.

You might also like