0% found this document useful (0 votes)
7 views

wt-unit-5-serverlet-mongodb-ruby

The document provides an overview of web servers, specifically focusing on IIS, Apache, XAMPP, and LAMP, detailing their architectures, functionalities, and advantages. It explains how web servers respond to client requests, the different approaches to server architecture, and the components of XAMPP and LAMP stacks. Additionally, it discusses the Tomcat server, its advantages and disadvantages, and compares Apache and Tomcat servers.

Uploaded by

hanusmurukutla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

wt-unit-5-serverlet-mongodb-ruby

The document provides an overview of web servers, specifically focusing on IIS, Apache, XAMPP, and LAMP, detailing their architectures, functionalities, and advantages. It explains how web servers respond to client requests, the different approaches to server architecture, and the components of XAMPP and LAMP stacks. Additionally, it discusses the Tomcat server, its advantages and disadvantages, and compares Apache and Tomcat servers.

Uploaded by

hanusmurukutla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

lOMoARcPSD|15581981

WT Unit-5 - Serverlet mongodb Ruby

cloud computing (Jawaharlal Nehru Technological University, Hyderabad)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Hanumantharao Murukutla ([email protected])
lOMoARcPSD|15581981

UNIT-5
Web Servers- IIS (XAMPP, LAMP) :
➢ Web Server Responds to client requests by providing resources like HTML
files, images etc...
➢ Stores and transmits web documents (files). It uses the HTTP protocol to
connect to other computers and distribute information. Example: IIS, Apache.
➢ Web server is a computer where the web content is stored. Basically web server
is used to host the web sites but there exists other web servers also such as
gaming, storage, FTP, email etc
➢ Web site is collection of web pages whileweb server is a software that respond
to the request for web resources.

Web Server Working


Web server respond to the client request in either of the following two ways:
• Sending the file to the client associated with the requested URL.
• Generating response by invoking a script and communicating with database

Architecture
Web Server Architecture follows the following two approaches:
1. Concurrent Approach
2. Single-Process-Event-Driven Approach.

Concurrent Approach
Concurrent approach allows the web server to handle multiple client requests at the
same time. It can be achieved by following methods:

WEB TECHNOLOGIES UNIT-5[R-19] Page 1

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

• Multi-process
• Multi-threaded
• Hybrid method.

Multi-processing
In this a single process (parent process) initiates several single-threaded child
processes and distribute incoming requests to these child processes. Each of the child
processes are responsible for handling single request.
It is the responsibility of parent process to monitor the load and decide if processes
should be killed or forked.

Multi-threaded
Unlike Multi-process, it creates multiple single-threaded process.

Hybrid
It is combination of above two approaches. In this approach multiple process are
created and each process initiates multiple threads. Each of the threads handles one
connection. Using multiple threads in single process results in less load on system
resources.

IIS ( Internet Information Services)


• Set up a web or FTP site on your corporate intranet
• Create large sites for internet or develop component based programs
• Designed to deliver high speed and secure information publishing
• A VB application lives on a web server and responds to requests from the browser.
• Uses HTML as interface
• Uses compiled VB code to process the request and to respond to the browser.
• It appears as a series of HTML pages user
• It is made up of a special type of objects called webclass which intern contains series
of resources called webitems developer
• Acts as central functional unit of application, processing data from the browser and
sending information to the user.
• HTML pages and other data that the webclass can send to the browser in response
to the request.
• Processing is performed on server.
Apache
In February of 1995, the most popular server software on the Web was the public
domain HTTP daemon developed by Rob McCool
Architecture of Apache web server
3 Most popular flexible and HTTP1.1 compliant web server.
3 An open source, like BSD license1
3 Modular Architecture helps user - easily add functionality to their specific
environment.

WEB TECHNOLOGIES UNIT-5[R-19] Page 2

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

3 provides full source code and comes with an unrestrictive license


3 Portable : runs on all platforms.
3 Robustness and security
Note: oracle, IBM, RedHat have adopted Apache based solutions for their products.
• Apache Features configurable error messages, DBMS based authentication
databases.
• Apache supports password authentication and digital certificate authentication.
• Apache has built in search engine and an HTML authorizing tool and also supports
FTP.

XAMPP:
XAMPP is the most popular PHP development environment
XAMPP is a completely free, easy to install Apache distribution containing MariaDB,
PHP, and Perl.
XAMPP is a cross-platform web server that is free and open-source. XAMPP is a short
form for Cross-Platform, Apache, MySQL, PHP, and Perl. XAMPP is a popular cross-
platform web server that allows programmers to write and test their code on a local
webserver.
Need for a XAMPP
• XAMPP is simply a local host or server.
• This local server runs on your personal computer, whether it’s a desktop or a
laptop.
• It is used to test clients or websites before publishing them to a remote web
server.
• On a local computer, the XAMPP server software provides a suitable
environment for testing MYSQL, PHP, Apache, and Perl projects. Because
most real-world web server deployments share the same components as
XAMPP, moving from a local test server to a live server is straightforward.
Advantages:
• In comparison to other web servers such as WAMP, it is simple to set up.
• It is Multi Cross-Platform, which implies it works on both Windows and Linux.
• With a single command, you may start and stop the entire web server and
database stack.
• Both a full and a standard version of XAMPP are available.
• It has a control panel that you can see contains start and stop buttons for
specific mechanisms, such as Apache, which is running through its Control
Panel.
Disadvantage:
• In comparison to the WAMP server, configuration and setting are more
difficult.

Components of XAMPP:
The components that are included in the XAMPP are given below:

WEB TECHNOLOGIES UNIT-5[R-19] Page 3

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

• Cross-Platform: Different operating systems are installed in separate


configurations on different local systems. The cross-platform component has
been included to improve the functionality and reach of this Apache
distribution package. It works with a variety of platforms, including Windows,
Linus, and MAC OS packages.
• Apache: Apache is a cross-platform HTTP web server. It is used to transport
web material all over the world. If someone requests files, photos, or documents
using their browser, HTTP servers will serve such assets to clients.
• PHP: The full form of PHP is Hypertext Preprocessor. PHP is a backend
programming language that is most commonly used in web development.
Users can use PHP to build dynamic websites and applications. It supports a
variety of database management systems and may be installed on any
platform. It was written in the C programming language.
• Perl: Perl is often referred to as the <generic= programming language. This Perl
language is dynamic and interpretable. This language is used for web
development, GUI development, system administration, and other things.
HTML, XML, and other markup languages are all supported by Perl.
• XAMPP Control Panel: The XAMPP Control Panel is a panel that assists in
the operation and regulation of other XAMPP components.
• Webalizer: It is a web analytics software solution that keeps track of user logs
and reports on usage.
• Tomcat: It is a JAVA-based servlet that provides JAVA functionality.

LAMP :
LAMP is known for its free and open-source approach to back end development. It
contains Linux OS, Apache web server, MySQL database, and PHP. Besides PHP,
developers can also use Python and Perl as an alternative.
LAMP’s Architecture
Let’s examine how each component contributes to the entire capabilities of the stack:

Linux
Linux is the operating system and sits as the first layer of the LAMP stack. It is the
backbone, as all other components run on top of it. Also, the programming language
and database management used in developing an application must coincide with
what platform to use. In this case, PHP and MySQL work efficiently with Linux. On
the other hand, SQL, ASP.NET, and ASP are better suited to Windows.
Linux has an extensive worldwide user base that extends across different industries.
Although developers can work with the rest of the stack components on different
operating systems, Linux still dominates because of its flexibility and easy
configuration options compared to other operating systems.

WEB TECHNOLOGIES UNIT-5[R-19] Page 4

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

Apache
Apache web server is the most widely used server in the world. It serves more than
half of the websites on the Internet. Appache offers extensive support with its well-
developed community. It works using the HTTP to process requests and transmit
information over the Internet.
Developers choose Apache for its mature and feature-rich ecosystem. Although there
are other entrants such as NGINX, the choice depends on the application’s
requirements.

MySQL
The third layer of the LAMP stack is the MySQL database. It is an open-
source relational database management system that stores application data. With
MySQL, it stores all the information in a format that is easily queried using the SQL
language.
SQL language works well with a structured business domain. Also, MySQL is robust
and proven suitable for running large and complex websites. It supports SQL and
relational tables. By doing so, it enables developers to build dynamic enterprise-level
databases.
You might consider MySQL if you:

• often change the content of your website or web app


• have a lot of user-contributed content
• rely on user’s feedback
• have contents that need to be stored and easily retrieved
If you want to optimize your application, you can view SQL queries from your code
with Prefix.

PHP
The last layer of the LAMP stack is the programming language. PHP (Hypertext
Preprocessor) is a programming language that sits on this layer and has the role of
combining all the elements of the LAMP stack. It allows web applications to run
efficiently.
The PHP language works with Apache to build dynamic web pages. Developers can’t
use HTML alone to execute dynamic processes. It needs a programming language
such as PHP to pull data out of a database. PHP executed this functionality by simply
integrating PHP code into the parts of a page that needs to be dynamic.
Note: PHP programming language is an efficient language. However, using the
LAMP stack, developers can swap out PHP in favor of Perl or the increasingly favorite
Python language.
For example, if the request is for a PHP file, then Apache passes the request to PHP.
Next, it loads the file and executes the code. Meanwhile, PHP communicates with
MySQL to fetch any data referenced in the code.

WEB TECHNOLOGIES UNIT-5[R-19] Page 5

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

After that, PHP uses the code in the file and the data from the database. The browsers
need this to create the HTML that browsers require to display web pages. The LAMP
stack can handle both static web pages and dynamic pages. Dynamic means the
contents keep on changing depending on the date, time, user identity, etc.
After running the file code, PHP passes the resulting data back to the Apache web
server, then sends it to the browser. During this process, it stores new data in MySQL.

Tomcat server:
It is an open-source Java servlet container. The primary objective of using it is to
implement the various Java Enterprise Specs, including the Websites API, Java-
Server Pages, and Java Servlet. The Tomcat or the Apache Tomcat was developed
under the open-source environment in 1998. A various developer has contributed to
the development of the components of the Tomcats since its beginning.

Advantages of Tomcat Server:


1- Open Source Application
One of the important apache tomcat features is that it is an open-source application.
It is released with the general public license. It means anyone can use the core file
for developing personal or commercial applications using the software. It is
available for free download and installation on your computer license.
2- Lightweight
When it comes to the development of the enterprise-level application, you need the
support of a lightweight application that runs smoothly. The Tomcat application
stands still in the lightweight application giving it more flexibility in the
development of the application.
It gives you fast data processing power that enables the deployment of the content
easily. Compare to the competitor, Tomcat is way ahead of technology.
3- Flexible
Tomcat server application comes with built-in customization options. The extension
of the core application provides the Tomcat more advantage in the development of
the application. tomcat is used for Lightweight nature offers more flexibility.
Users can take the advantage of the features to run the application differently to
fulfill their requirements. Tweak the application the way you want and it will
perform the best to generate the results.
4- Stability
Tomcat software has gone through several essential upgrades. It is now one of the
stable platforms on the web that runs the application smoothly. People have
considered the application as an incredibly stable version of the Tomcat that runs
independently on apache installation.
Even if one of the features failed to run the application due to an error, the rest of
the server runs well without any trouble. This makes your application live all the
time.

WEB TECHNOLOGIES UNIT-5[R-19] Page 6

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

5- Extra Level of Security


Tomcat application provides an extra level of security to the user. Many corporates
would like to put their data behind the firewall protection which is generally
accessible from the apache installation.
6- Well Documented
The Tomcat application is well documented which provides comprehensive
information to the developer who wants to learn the Tomcat application
development. Various web-based tutorial services are offering the free course for
Tomcat. Information including installation guide, startup settings, server
configuration, platform support is some of the information easily available on the
web.

Disadvantages of Tomcat Server:


• Tomcat might not be as fast as Apache when it comes to static analysis
• The memory leak is one of the weak spots of Tomcat
• You might encounter some complications in SSL installation with Tomcat
• Tomcat’s user interface is primary and not as high quality as it should be

Difference Between Apache and Tomcat Server


There are some differences between these two. Read the table below to precisely
compare Apache web server vs tomcat application server.

Apache Web Server Apache Tomcat Server

It is a HTTP server. It is eligible to host It is a web container that allows users


one or more HTTP based web-servers to run Servlet and JAVA Server Pages

It can handle both static and dynamic It can handle both static and dynamic
pages. Static pages are created using pages. Static pages are created using
HTML. Dynamic ones are generated HTML. Dynamic ones are generated
using PHP, Ruby or other languages using Servlet and JSP

It can be utilized to host applications It can be utilized to host JAVA based


based on in any programming language code

It is only coded in C programming


It can be coded in pure JAVA
language

Introduction to Servlet:

WEB TECHNOLOGIES UNIT-5[R-19] Page 7

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

The Java Servlet, now also known as the Jakarta Servlet, is a Java Server Software
component, designed and deployed to enhance the Server services by upgrading
their capabilities to respond to any requests through a Web API.
Java Servlet Features
The Java Servlets carry over the features of Java Programming Language. The key
features offered by the Java Servlets are as follows.
• Portable
• Efficient
• Scalable
• Robust
1. Portable
As discussed above, the servlets feature the same Portable nature as the Java
Programming Language. The Servlet program designed in one Operating System's
Platform can be run in a different Operating System Platform with ease.
2. Efficient
The Java Servlet, by its nature, provides an instantaneous response to the client's
request. Also, it can be portable and perform in every environmental condition
regardless of the operating system platform.
3. Scalable
We consider Java Servlets to be highly scalable. Servlets use completely lightweight
threads for the processes and can simultaneously handle multiple client requests by
generating various threads.
4. Robust
The Java Servlets are best known for their robust operating procedures. The
servlets extend the features of Java, which include.
1. Java Security Manager
2. Java Garbage Collector
3. Exception Handling.
Implementation of these advanced features makes Java Servlets resilient to any
security threats to a decent extent. Also, the garbage collector takes care of memory
management and eliminates the issues related to memory management in real-
time, leaving Servlets to be Robust.

Java Servlet Architecture:

WEB TECHNOLOGIES UNIT-5[R-19] Page 8

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

We can also consider the software architecture of a servlet as the life cycle of the
Java Servlet. To write a Servlet, the user needs first to implement the Servlet
Interface, directly or indirectly, using the following import command.
import javax.servlet.*;
Once the Servlet interface is imported, and we inherit the HTTP Class, we begin
with the Java Servlet's life cycle.
In the life cycle of a servlet, we have mainly three stages, which are mentioned
below.
• init()
• service()
• destroy()

Java Servlet Life-Cycle


The Java Servlet Life cycle includes three stages right from its start to the end until
the Garbage Collector clears it. These three stages are described below.
1. init()
2. service()
3. destroy()
1. init()
The init() is the germinating stage of any Java Servlet. When a URL specific to a
particular servlet is triggered, the init() method is invoked.
Another scenario when the init() method gets invoked is when the servers are fired
up. With every server starting up, the corresponding servlets also get started, and
so does the init() method.
One important specialty of the init() method is the init() method only gets invoked
once in the entire life cycle of the Servlet, and the init() method will not respond to
any of the user's commands.
The init() method Syntax:
public void init() throws ServletException {
//init() method initializing
}
2. service()

WEB TECHNOLOGIES UNIT-5[R-19] Page 9

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

The service() method is the heart of the life cycle of a Java Servlet. Right after the
Servlet's initialization, it encounters the service requests from the client end.
The client may request various services like:
• GET
• PUT
• UPDATE
• DELETE
The service() method takes responsibility to check the type of request received from
the client and respond accordingly by generating a new thread or a set of threads
per the requirement and implementing the operation through the following
methods.
• doGet() for GET
• doPut() for PUT
• doUpdate() for UPDATE
• doDelete() for DELETE
The service() method Syntax:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
3. destroy()
Like the init() method, the destroy() method is also called only once in the Java
Servlet's entire life cycle.
When the destroy() method is called, the Servlet performs the cleanup activities
like,
• Halting the current or background threads
• Making a recovery list of any related data like cookies to Disk.
After that, the Servlet is badged, ready for the Garbage collector to have it cleared.
The destroy() method Syntax:
public void destroy() {
//destroy() method finalizing
}

Methods of servlet
Servlet consists of five methods:
1) Init ()
The init () method is called only once throughout the life of a servlets and this init ()
method the servlet has been placed into service. The servlet cannot be put into the
service if,
A) The init () method does not return within a fix time set by the web server.
B) It throws a ServletException.

Syntax: 3 public void init (ServletConfig config) throws ServletException.

WEB TECHNOLOGIES UNIT-5[R-19] Page 10

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

Parameters- The init () method takes a ServletConfig object containing


initialization parameters and servlet’s configuration and throws a ServletException
if an exception has occurred.
2) Service ()
Once the servlet starts receiving request, the service () method is called by the
servlet container to respond. The servlet services the client request with the help of
two objects,javax.servlet.ServletRequest and javax.servlet.ServletResponse are
passed by the Servlet container.
Syntax: 3 public void service (ServletRequest req, ServletResponse res) throws
ServletException.
Parameters: 3 The service () method takes the ServletRequest object that contains
the client’s request and the object ServletResponse contains the servlet’s response.
3) getServletConfig ()
This method contains parameters for initialization and startup of the servlet and
returns a ServletConfig object.
Syntax: 3 public ServletConfig getServletConfig ()
4) getServletInfo ()
The getServletInfo () method is returned by version, author etc.
Syntax: 3 public String getServletInfo ()
5) destroy ()
This method is used to close the servlet.
Syntax: 3 public void destroy ()

Java Server Pages


JavaServer Pages (JSP) is a Web page development technology that supports
dynamic content. This allows programmers to use specific JSP tags to insert Java
code into HTML pages.
A part of JavaServer Pages is a type of Java servlet designed to perform the
function of a Java web application user interface. JSPs are written as text files by
Web developers that incorporate Html or XHTML script, XML components, and
embedded JSP actions and commands.
Advantages of JSP
Standard HTML does not contain dynamic data, whereas JSP does.
JSP’s benefits are fairly straightforward. First of all, the dynamic component is
implemented in Java, not Visual Basic or any platform-specific language, so it is
smoother and simpler to use. Lastly, it is platform-independent.
If we compare JSP and SSI, Server Side Includes is intended only for basic
inclusions, not for actual systems that use form data, build links to databases, and
etc.
Writing and modifying standard HTML is more practical than creating lots
of HTML-generating println statements to generate HTML.
JavaScript can generate HTML dynamically on the client but can hardly interact
with the webserver to perform complex tasks like database access and image
processing etc.

WEB TECHNOLOGIES UNIT-5[R-19] Page 11

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

JSP’s elements
The JSP elements are listed below:
Scriptlet
A script may consist of any number of JAVA language statements, declarations of a
variable or procedure, or statements that are true in the page script’s language.
The following is the scriptlet syntax −
<% code fragment %>
The XML version of the above syntax can be written as follows :
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
The text, HTML tags, or JSP components that you write need to be beyond the
document. The following is the first and simple illustration of JSP:
<html>
<head><title>Hello Kitty</title></head>
<body>
Hello Kitty! <br/>
<%
out.println("Your IP address is " + request.getRemoteAddr()); %>
</body>
</html>
Let us retain the code above in the hello.jsp JSP file and place this file in the folder
C:\apache-tomcat7.0.2\webapps\ROOT.
JSP Declarations

Declaring one or more methods or variables done by Declaration that can be used
later in the JSP file in the Java code. Before you use it in the JSP code, you must
declare the variable or process.

The syntax for JSP declarations is below:

<%! declaration; [ declaration; ]+ ... %>


The XML version of the above syntax can be written as follows:

<jsp:declaration>
code fragment
</jsp:declaration>

JSP Expression
In the scripting language, JSP expression components provide an expression that is
evaluated, converted into a string, and inserted where the expression appears in a
JSP file. Because an expression’s meaning is translated to a string, you can use an
expression in a JSP file inside a line of text, whether or not it’s tagged with HTML.

WEB TECHNOLOGIES UNIT-5[R-19] Page 12

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

An expression element can include any expression that is legitimate under the Java
Language Specification, but you will be unable to use a semicolon to terminate an
expression.

The JSP Expression syntax follows :

<%= expression %>


The XML version of the above syntax can be written as follows:

<jsp:expression>
expression
</jsp:expression>
example showing a JSP Expression:

<html>
<head><title>A Commen Test</title></head>

<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>

JSP 3 Implicit Objects


We are going to address the Tacit Objects in JSP in this section. These objects are
the Java objects made accessible to the developers on each page by the JSP
Container, which can be named directly by the developer without being expressly
declared. Often, pre-defined variables are called JSP Implicit Objects.

The request Object


The request object is an example of an object called
javax.servlet.http.HttpServletRequest. The JSP engine generates a new object to
represent the request whenever a client asks for a page.

The request object offers techniques for extracting information about the HTTP
header, including form records, cookies, HTTP methods, etc.

In a corresponding section − JSP 3 Client Request, we will cover a full range of


methods associated with the request object.

Example of Implicit request object:


In the example here, we collect user input on the index.html page and view the
same details on the userinfo.jsp page using the implicit request object.

index.html

WEB TECHNOLOGIES UNIT-5[R-19] Page 13

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

<html>
<head>
<title>Enter UserName and Password</title>
</head>
<body>
<form action="userinfo.jsp">
Enter User Name: <input type="text" name="uname" /> <br><br>
Enter Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Submit Details"/>
</form>
</body>
</html>
userinfo.jsp

<%@ page import = " java.util.* " %>


<html>
<body>
<%
String username=request.getParameter("uname");
String password=request.getParameter("pass");
out.print("Name: "+username+" Password: "+password);
%>
</body>
</html>
You’ll get something like this after running the code:

This is the output page for userinfo.jsp. We also obtained the ID and password that
the user entered on the login tab.

The response Object


A response object is an instance of an object called
javax.servlet.http.HttpServletResponse. And when the request object is generated
by the server, it often generates an object to display the client’s answer.

The interfaces that cope with generating new HTTP headers are also specified by
the response object. The JSP developer can introduce additional cookies or date
stamps, HTTP status codes, etc., from this object.

Example of Implicit response object:


We will get ID and password from the login page in the following example and then
we pair them with the right hardcoded ID or password. The sign-in page redirects to

WEB TECHNOLOGIES UNIT-5[R-19] Page 14

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

the progress page if the credentials are correct, otherwise, it reroutes to the failed
JSP page.

index.html
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="checkdetails.jsp">
UserId: <input type="text" name="id" /> <br><br>
Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Sign In!!"/>
</form>
</body>
</html>

checkdetails.jsp
<html>
<head><title>Check Credentials</title>
</head>
<body>
<%
String uid=request.getParameter("id");
String password=request.getParameter("pass");
session.setAttribute("session-uid", uid);
if(uid.equals("Chaitanya") && password.equals("aaaa"))
{
response.sendRedirect("success.jsp");
}
else
{
response.sendRedirect("failed.jsp");
}
%>
</body>
</html>
success.jsp

<html>
<head><title>Success Page</title>
</head>
<body>
<%

WEB TECHNOLOGIES UNIT-5[R-19] Page 15

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

String data=(String)session.getAttribute("session-uid");
out.println("Welcome "+ data+"!!");
%>
</body>
</html>

If the credentials entered by the user are incorrect, the access will be diverted to
this tab.

failed.jsp
<html>
<head><title>Sign-in Failed Page</title>
</head>
<body>
<%
String data2=(String)session.getAttribute("session-uid");
out.println("Hi "+ data2+". Id/Password are wrong. Please try Again.");
%>
</body>
</html>

Database connectivity 3 Servlets:


There are different approaches to communicating with databases through servlet
components. We need to perform the servlet to database communication due to the
following main reasons:-

• To save the inputs coming from the end-user through forms to database
software. Example:- Email Id registration.
• To save the result generated by servlet Component in database software.
Example:- Bill generation
• To get inputs from the database software to the Servlet component.
Example:- Balance inquiry, account statement generation

There are 4 approaches for Database Connectivity in Servlet.


Approach-1:- Writing logics in multiple methods.

❖ Create JDBC Connection in the init()


❖ Use the JDBC Connection in the service(-,-)/doXxx(-,-)
❖ Close JDBC Connection in the destroy method.

Approach-2:- Write all the logics in service(-,-) or doXxx(-,-) method.

❖ Create JDBC Connection in service(-,-)/doXxx(-,-) method.

WEB TECHNOLOGIES UNIT-5[R-19] Page 16

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

❖ Use JDBC Connection in service(-,-)/doXxx(-,-) method.


❖ Close JDBC Connection in service(-,-)/doXxx(-,-) method.

Advantage:- Since JDBC Connection is a local variable, it is thread-safe by default.


Hence there is no need to work with the synchronization concept.

Approach-3:- Use server-managed JDBC connection from the connection pool.

❖ Get JDBC Connection object from JDBC Connection pool being from service(-
,-)/doXxx(-,-)
❖ Use JDBC Connection object in service(-,-)/doXxx(-,-)
❖ Return JDBC connection back to JDBC connection pool being from service(-,-
)/doXxx(-,-)
Advantage:- Here JDBC connection is local to service(-,-)/doXxx(-,-) method. So, it
becomes thread-safe.

Approach4:- Use DAO class for the persistence operation.


The Java class/component that separates persistence logic from other logics of the
application and makes that logic as flexible logic to modify and reusable logic is
called DAO (Data access object).
In this approach, we can use either approach-2 or approach-3 to get the JDBC
connection. The main task in this approach,

❖ Write JDBC code (persistence logic) in DAO class either by using direct
connection object or server-managed pooled connection object.
❖ Create a DAO class object in Servlet Component and use its persistence logic
in Servlet Component.
Conclusion
Java is popular for developing medium and large web applications so approach-4 is
recommended to use. But before going to approach4, we must know approach-2 and
approach-3 then only you can develop logic for approach4.

Example
Develop a web application that should have following features.
1. User can register and then login to the application.
2. The users information should be maintained in database.
3. Use standard logging framework log4j.
4. The application should support session management, no JSPs should be
visible without session. Users can logout anytime from the application.
5. We should not show application and server details to user incase of any
exception in application or other common errors like 404.
CREATE TABLE `Users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '', `email` varchar(20) NOT NULL
DEFAULT '', `country` varchar(20) DEFAULT 'USA', `password` varchar(20) NOT

WEB TECHNOLOGIES UNIT-5[R-19] Page 17

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB


AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

login.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Login with email and password</h3>
<form action="Login" method="post">
<strong>User Email</strong>:<input type="text" name="email"><br>
<strong>Password</strong>:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
<br>
If you are new user, please <a href="register.html">register</a>.
</body>
</html>

register.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Register Page</title>
</head>
<body>
<h3>Provide all the fields for registration.</h3>
<form action="Register" method="post">
<strong>Email ID</strong>:<input type="text" name="email"><br>
<strong>Password</strong>:<input type="password" name="password"><br>
<strong>Name</strong>:<input type="text" name="name"><br>
<strong>Country</strong>:<input type="text" name="country"><br>
<input type="submit" value="Register">
</form> <br>
If you are registered user, please <a href="login.html">login</a>.
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>

WEB TECHNOLOGIES UNIT-5[R-19] Page 18

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns="https://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>ServletDBLog4jExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>dbUser</param-name>
<param-value>James </param-value>
</context-param>
<context-param>
<param-name>dbPassword</param-name>
<param-value> James 22</param-value>
</context-param>
<context-param>
<param-name>dbURL</param-name>
<param-value>jdbc:mysql://localhost:3306/UserDB</param-value>
</context-param>
<context-param>
<param-name>log4j-config</param-name>
<param-value>WEB-INF/log4j.xml</param-value>
</context-param>

<error-page>
<error-code>404</error-code>
<location>/AppErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/AppErrorHandler</location>
</error-page>

<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.journaldev.servlet.filters.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

WEB TECHNOLOGIES UNIT-5[R-19] Page 19

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

</web-app>

log4j.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="https://jakarta.apache.org/log4j/"
debug="false">
<appender name="dbexample"
class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${catalina.home}/logs/dbexample.log"/>
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="20MB" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-4r [%t] %-5p %c
%x - %m%n" />
</layout>
</appender>

<logger name="com.journaldev" additivity="false">


<level value="DEBUG" />
<appender-ref ref="dbexample"/>
</logger>

<root>
<level value="debug" />
<appender-ref ref="dbexample" />
</root>

</log4j:configuration>

Connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnectionManager
{
private Connection connection;
public DBConnectionManager(String dbURL, String user, String pwd)
throws ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(dbURL, user, pwd);

WEB TECHNOLOGIES UNIT-5[R-19] Page 20

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

}
public Connection getConnection()
{
return this.connection;
}
}

DBConnectionManager.java is the utility class for MySql database connection and


it has a method that returns the connection object.

Database connectivity in jsp :


First create simple registration form, then All the data will be stored in the
database. We use method getParameter() that return the value of a request
parameter passed as string of request. We have used database connection in this
form. We can insert, update, delete any data in this form. This application can be
used by any jsp web project.
syntax of getParameter:-
<%= request.getParameter("massage")%>
Registration.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>

<%
String id = "";
String user_id = request.getParameter("user_name");
String pwd = request.getParameter("pwd");
String name = request.getParameter("name");
String email = request.getParameter("email");
if (!(user_id == null || user_id.isEmpty()))
{
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "naulej";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);

WEB TECHNOLOGIES UNIT-5[R-19] Page 21

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
try {
connection = DriverManager.getConnection(
connectionUrl + dbName, userId, password);
statement = connection.createStatement();

String sql = "INSERT INTO userinfo (user_id,pwd,name,email) VALUES('"+


user_id + "','" + pwd + "','" + name + "','" + email + "')";
int flage = statement.executeUpdate(sql);

} catch (Exception e) {
e.printStackTrace();
}
}
%>
<html>
<head>
<head>
<title>jsp</title>
</head>
<form method="post" action="Registration.jsp">
<table>
<tr>
<td>id</td><td><input type="text" id="id" size="35" /></td>
</tr>
<tr>
<td>user_id</td>
<td><input type=text name="user_name" size="35" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd" size="35" /></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" name="name" size="35" /></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email" size="35" /></td>

WEB TECHNOLOGIES UNIT-5[R-19] Page 22

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

</tr>
<tr>
<td></td>
<td><input type="submit" name="insert" value="Save"></td>
</tr>
</table>
</form>
</html>
Form

Database connectivity in php:


In PHP it is easy by using the mysqli_connect() function, All the communication between
PHP and the MySQL database server takes place through this connection. Here're the basic
syntaxes for connecting to MySQL using MySQLi and PDO extensions:
Syntax: MySQLi, Procedural way
$link = mysqli_connect("hostname", "username", "password", "database");
Syntax: MySQLi, Object Oriented way
$mysqli = new mysqli("hostname", "username", "password", "database");
Syntax: PHP Data Objects (PDO) way
$pdo = new PDO("mysql:host=hostname;dbname=database", "username",
"password");
The hostname parameter in the above syntax specify the host name (e.g. localhost),
or IP address of the MySQL server, whereas
the username and password parameters specifies the credentials to access MySQL

WEB TECHNOLOGIES UNIT-5[R-19] Page 23

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

server, and the database parameter, if provided will specify the default MySQL
database to be used when performing queries.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Print host information


echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
Note: The default username for MySQL database server is root and there is no
password. However to prevent your databases from intrusion and unauthorized
access you should set password for MySQL accounts.

Closing the MySQL Database Server Connection


The connection to the MySQL database server will be closed automatically as soon
as the execution of the script ends. However, if you want to close it earlier you can
do this by simply calling the PHP mysqli_close() function.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Print host information


echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);

// Close connection
mysqli_close($link);
?>

Introduction to Mongo DB and JQuery:


MongoDB is a NoSQL database which stores the data in form of key-value pairs. It

WEB TECHNOLOGIES UNIT-5[R-19] Page 24

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

is an Open Source, Document Database which provides high performance and


scalability along with data modelling and data management of huge sets of data in
an enterprise application.
A Document is nothing but a data structure with name-value pairs like in JSON. It
is very easy to map any custom Object of any programming language with a
MongoDB Document. For example : Student object has attributes name, rollno and
subjects, where subjects is a List.
Key Features of MongoDB:
1. MongoDB provides high performance. Input/Output operations are lesser
than relational databases due to support of embedded documents(data
models) and Select queries are also faster as Indexes in MongoDB supports
faster queries.
2. MongoDB has a rich Query Language, supporting all the major CRUD
operations. The Query Language also provides good Text Search and
Aggregation features.
3. Auto Replication feature of MongoDB leads to High Availability. It provides
an automatic failover mechanism, as data is restored through backup(replica)
copy if server fails.
4. Sharding is a major feature of MongoDB. Horizontal Scalability is possible
due to sharding.
5. MongoDB supports multiple Storage Engines. When we save data in form of
documents(NoSQL) or tables(RDBMS) who saves the data?

MongoDB vs SQL Databases


SQL Database NoSQL Database (MongoDB)
Relational database Non-relational database
Supports SQL query language Supports JSON query language
Table based Collection based and key-value pair
Row based Document based
Column based Field based
Support foreign key No support for foreign key
Support for triggers No Support for triggers
Contains schema which is predefined Contains dynamic schema
Not fit for hierarchical data storage Best fit for hierarchical data storage
Vertically scalable - increasing RAM Horizontally scalable - add more servers
Emphasizes on ACID properties
Emphasizes on CAP theorem (Consistency,
(Atomicity, Consistency, Isolation and
Availability and Partition tolerance)
Durability)
MongoDB Documents also align with the structure of objects in modern
programming languages, as they are a form of JSON. This makes it easy for
developers to map the data used in the application to its associated document in the
database.
Advantages of MongoDB

WEB TECHNOLOGIES UNIT-5[R-19] Page 25

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

1. it is very easy to install and setup the MongoDB.


2. The very basic feature of MongoDB is that it is a schema-less database. No
schema migrations anymore. Since MongoDB is schema-free, your code
defines your schema.
3. The ability to derive a document-based data model is one of the most
attractive advantages of MongoDB. Because, the way it stores the data in the
form of BSON (Binary JSON), ruby hashes etc, helps to store the data in a
very rich way while being capable of holding arrays and other documents.
4. The document query language supported by MongoDB plays a vital role in
supporting dynamic queries.
5. Very easy to scale.
6. Due to the structuring (BSON format - key value pair) way of the data in
MongoDB, no complex joins are needed.
7. Performance tuning is absolutely easy compared to any relational databases.
8. No need of mapping the application objects to the data objects.

JQuery:
What is jQuery?
jQuery is a DOM manipulation library that essentially helps us do many JavaScript
tasks much faster and more simply.
It comes with a number of useful methods for:
• Selecting/Manipulating/Creating Elements
• Adding Event Listeners
• Animating Elements
• Adding Effects
• Making HTTP Requests (AJAX)
Why Use jQuery?
• It’s easy to learn and use
• Makes DOM manipulation a breeze
• Has cross-browser support
• Working with AJAX is easy
• Lots of knowledge out there if you need help
Why Should I Not Use jQuery?
• It doesn’t do anything you can’t do on your own
• It’s an unnecessary dependency
• Reduces performance
• It’s old and everyone has moved to React/Angular/Vue

WEB TECHNOLOGIES UNIT-5[R-19] Page 26

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

If you don’t already know jQuery, is it worth learning today?


In my opinion, jQuery shouldn’t really be used on new projects, for those we should
be looking at modern frameworks such as React, Angular or Vue. However that
doesn’t mean jQuery should be completely forgotten about just yet.
Some projects may be using libraries such as Bootstrap, which for the time being
has a dependency on jQuery. As do some ready-made templates. Some developer
teams are comfortable working with jQuery and that’s fine too.
In these cases, jQuery remains relevant. Also, if you’re looking to secure your first
developer job, many companies still use jQuery.
Using jQuery
So assuming you want to learn some jQuery, let’s get started!
Create a demo project
We’ll begin by creating a demo project. Add a style.css in a css/directory,
a scripts.js in a js/ directory, and a main index.html in the root directory of the
project.
jquery-demo/
├── css/
| └── style.css
├── js/
| └── scripts.js
└── index.html
Setting up jQuery
jQuery is simply a JavaScript file that you’ll link to in your HTML. There are two
ways to include it in your project:
• Download a local copy
• Link to the file via Content Delivery Network (CDN)
If you choose to download a local copy, link to it with the following:
WEB TECHNOLOGIES UNIT-5[R-19] Page 27

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

<script type="text/javascript" src="js/jquery-3.3.1.js"</script>


Note: the version number will likely change but that’s fine!
If you choose the CDN option, use this code instead:
<script src="https://code.jquery.com/jquery-3.3.1.js"</script>
Let's open our index.html, and copy in the following code:
Note: We will be working with these elements <h1>, <ul>, <img>, <div>, later on in
this article 4 so copy it all in now to save time!
<!doctype html>
<html lang="en">

<head>
<title>jQuery Demo</title>
<link rel="stylesheet" href="css/style.css">
</head>

<body>
<h1 id="demo"></h1>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
<img src="https://upload.wikimedia.org/wikipedia/commons/d/d3/Logo_jQuery.svg"
width="300px">
<div>
<button id="submit">Click me</button>
<input type="text">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="js/scripts.js" />
</body>
</html>
And make sure you place the script tags just before the</body> tag,
ensuring scripts.js is placed after your jQuery script 4 or it won’t work!
Now open up scripts.js and add the following:
$(document).ready(function() {
// All your jQuery will go here!
});
We do this as in order to manipulate a page with jQuery, we need to ensure the
document is <ready= first. All the code we write will need to be wrapped in this code
(it’s best practice).
Let's see it in action with a quick demo! Add the following line to your scripts.js
$(document).ready(function() {
$("#demo").html("This text is brought to you by jQuery!");

WEB TECHNOLOGIES UNIT-5[R-19] Page 28

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

});

Web development frameworks:


Introduction to Ruby:
Ruby is an object-oriented programming language developed by Yukihiro
Matsumoto. Ruby is a dynamic programming language with a complex but at
the same time expressive grammar. Ruby also has a core class library with a
rich and powerful API.
Ruby is inspired by other low level and object oriented programming languages
like Lisp, Smalltalk, and Perl and uses syntax that is easy for C and Java
programmers to learn.
Ruby, a dynamic and open source programming language with a focus on
simplicity and productivity, has an elegant syntax that is natural to read and
easy to write.
Although it's easy to program in Ruby, it is not a simple language.
Features of Ruby
1. Object Oriented : Every values in Ruby is an object, even the most
primitive things like strings, numbers and even true and false. So, Ruby
is a pure Object Oriented Language. Every object has a class and every
class has one superclass.
2. Dynamic : Ruby is a very dynamic programming language. Ruby
programs aren't compiled like C or Java programs. All things in a
program are built by the code when it is run. A program can also modify
its own definitions while running.
3. Singleton Classes : Every object in Ruby has two classes: a regular
class and a singleton class. An object's singleton class is nameless class
whose only instances is that object. Singleton classes are created
automatically and make Ruby simple and elegant.
4. Metaprogramming : Everything in Ruby are objects. You can use them to
learn about them or even modify them, while your program is running.
This technique is called metaprogramming.
5. Flexibility : Methods can be added to existing classes without sub
classing, operators can be overloaded, and even the behaviour of the
standard library can be redefined at runtime.
Literals
A literal is any notation that lets you represent a fixed value in source code.
For instance, all of the following are literals in Ruby:
'Hello, world!' // string literal
375 // integer literal
3.141528 // float literal
true // boolean literal
{ 'a' => 1, 'b' => 2 } // hash literal
[ 1, 2, 3 ] // array literal

WEB TECHNOLOGIES UNIT-5[R-19] Page 29

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

:sym // symbol literal


nil // nil literal
Strings
A string is a list of characters in a specific sequence. In programming, we often
have to work with text data like names, messages, and descriptions. Ruby uses
strings to represent such data. You write string literals with either single
quotes or double quotes
Ex:
a = 'ten'
=> "ten"
Symbols
Ruby symbols are created by placing a colon (:) before a word.
:name
:a_symbol
Basically, a symbol is used when you want to reference something like a string
but don't ever intend to print it to the screen or change it. It is often referred to
as an immutable (i.e. unchangeable) string. While not 100% technically correct,
it is a useful mnemonic device for now.
Numbers
Numbers are represented many ways in Ruby. The most basic form of a
number is called an integer. It is represented by the whole number only, with
no decimal point. A more complex form of a number is called a float. A float is a
number that contains a decimal.
# Example of integer literals
1, 2, 3, 50
# Example of float literals
1.2345, 2345.4267, 98.2234
nil
In programming, we need a way to express "nothing", and in Ruby, we do this
through something called nil. A variable with a value of nil could be described
as having 'nothing' or being 'completely empty', or even just simply 'not any
specific type'. A situation where this may occur is where output is expected but
none is returned, such as:
puts "Hello, World!"
Hello, World!
=> nil
The puts method prints out a string and returns nothing, so we see nil being
returned after the string is displayed.
You can explicitly refer to the nil value by using the nil literal in our code:
x = nil
=> nil

Identifiers in Ruby

WEB TECHNOLOGIES UNIT-5[R-19] Page 30

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

• Identifiers are names of variables, constants and functions/methods.


• Ruby identifiers are case sensitive.
• Ruby identifiers may consists of alphanumeric characters and also
underscore ( _ ).
For example: Man_1, item_01 are examples of identifiers.
Keywords in Ruby
The reserved words in Ruby which cannot be used as constant or variable
names are called keywords of Ruby.
BEGIN Do next Then
END else nil True
Alias elsif not Undef
And end or Unless
Begin ensure redo Until
Case For retry While
Break false rescue When
Def In self __FILE__
Class If return While

Variables
There are different types of variables in Ruby:
• Local variables
• Instance variables
• Class variables
• Global variable
Local Variables: A local variable name always starts with a lowercase letter(a-z)
or underscore (_). These variables are local to the code construct in which they
are declared. A local variable is only accessible within the block of its
initialization. Local variables are not available outside the method. There is no
need to initialize the local variables.
Example:
age = 10
_Age = 20

Instance Variables: An instance variable name always starts with a @ sign.


They are similar to Class variables but their values are local to specific
instances of an object. Instance variables are available across methods for any
specified instance or object i.e. instance variables can change from object to
object. There is no need to initialize the instance variables and uninitialized
instance variable always contains a nil value.
Example:
# the Instance Variables
class Customer
def initialize(id, name, addr)
# Instance Variables

WEB TECHNOLOGIES UNIT-5[R-19] Page 31

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

@cust_id = id
@cust_name = name
@cust_addr = addr
end
# displaying result
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
end
# Create Objects
cust1 = Customer.new("1", "Bhanu", "GNT")
cust2 = Customer.new("2", "Chaitanya", "VIJ")
# Call Methods
cust1.display_details()
cust2.display_details()
OUTPUT:
Customer id 1
Customer name Bhanu
Customer address GNT
Customer id 2
Customer name Chaitanya
Customer address VIJ

Class Variables: A class variable name always starts with @@ sign.It is


available across different objects. A class variable belongs to the class and it is
a characteristic of a class. They need to be initialized before use. Another way
of thinking about class variables is as global variables within the context of a
single class. A class variable is shared by all the descendants of the class. An
uninitialized class variable will result in an error.
Example:
# the Class Variables
class Customer
# class variable
@@no_of_customers = 0
def initialize(id, name, addr)
# An instance Variable
@cust_id = id
@cust_name = name
@cust_addr = addr
end
# displaying result
def display_details()

WEB TECHNOLOGIES UNIT-5[R-19] Page 32

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

puts "Customer id #@cust_id"


puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
# class variable
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1 = Customer.new("1", "Bhanu", "GNT")
cust2 = Customer.new("2", "Teja", "VIJ")
# Call Methods
cust1.display_details()
cust1.total_no_of_customers()
cust2.display_details()
cust2.total_no_of_customers()
Output:
Customer id 1
Customer name Bhanu
Customer address GNT
Total number of customers: 1
Customer id 2
Customer name Teja
Customer address VIJ
Total number of customers: 2

Global Variables: A global variable name always starts with $. Class variables
are not available across classes. If you want to have a single variable, which is
available across classes, you need to define a global variable. Its scope is
global, means it can be accessed from anywhere in a program. By default, an
uninitialized global variable has a nil value and its use can cause the programs
to be cryptic and complex.
Example:
# global variable
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
class Class2
def print_global

WEB TECHNOLOGIES UNIT-5[R-19] Page 33

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

puts "Global variable in Class2 is #$global_variable"


end
end
class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global
Output:
Global variable in Class1 is 10
Global variable in Class2 is 10

Data types
Data types in Ruby represents different types of data like text, string, numbers,
etc. All data types are based on classes because it is a pure Object-Oriented
language. There are different data types in Ruby as follows:
• Numbers
• Boolean
• Strings
• Hashes
• Arrays
• Symbols
Numbers: Generally a number is defined as a series of digits, using a dot as a
decimal mark.
Optionally the user can use the underscore as a separator. There are different
kinds of numbers
like integers and float. Ruby can handle both Integers and floating point
numbers. According to
their size, there are two types of integers, one is Bignum and second is Fixnum.
• Example:
# Ruby program to illustrate the
# Numbers Data Type
# float type
distance = 0.1
# both integer and float type
time = 9.87 / 3600
speed = distance / time
puts "The average speed of a sprinter is #{speed} km/h"
Output:
The average speed of a sprinter is 36.474164133738604 km/h
Boolean: Boolean data type represents only one bit of information either true or
false.
• Example:
# Ruby program to illustrate the
# Boolean Data Type

WEB TECHNOLOGIES UNIT-5[R-19] Page 34

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

if true
puts "It is True!"
else
puts "It is False!"
end
if nil
puts "nil is True!"
else
puts "nil is False!"
end
if 0
puts "0 is True!"
else
puts "0 is False!"
end
Output:
It is True!
nil is False!
0 is True!
Strings: A string is a group of letters that represent a sentence or a word.
Strings are defined by enclosing a text within a single (=) or double (<=) quotes.

Ruby Scripting:
Ruby is a powerful scripting language. Scripts can be used to automate tasks such
as creating and searching files and managing and organizing subdirectories.
Companies like Github, Chef and Puppet use Ruby for scripting. Devops teams use
scripting to combine development and operations.
hello.rb
#!/usr/bin/ruby
puts "Hello world!"
We can run this script in the command line by going to the directory where the file
lives and typing in ruby hello.rb. The output of the program will be "Hello world!".
puts "Hello world!"

puts is a method that’s available to all Objects; it’s mixed in from the Kernel module
in Ruby. Remember how we used methods() to see that String, Integer and Float
share some methods? Many of these methods are mixed in from Kernel. Specifically,
puts will output a string to the terminal and then add a newline. (We could also use
print, another Kernel method, which doesn’t add a newline.)
hello.rb
#!/usr/bin/env ruby
puts 'What is your name?'
name = gets.chomp

WEB TECHNOLOGIES UNIT-5[R-19] Page 35

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

puts "Hello #{name}!"


puts outputs a line to the terminal, gets accepts input from the terminal. chomp
removes any trailing newlines.
Using ARGV
While gets works fine, responding to prompts in the command line can get tedious
after a while. It would be nice to have the option to pass in an argument on the
command line like this: ruby hello.rb Set
we pass an argument into a method. When we do so, the program has access to the
argument (or arguments) through the ARGV array.

ARGV is short for "argument vector." It’s capitalized because it is a constant,


though we can modify or update ARGV if we need to.
hello.rb
#!/usr/bin/env ruby
first_name = ARGV[0]
last_name = ARGV[1]
age = ARGV[2]
puts "This is ARGV, the arguments array: #{ARGV}."
puts "Hello #{first_name} #{last_name}. You are #{age} years old!"
Now, let’s type the following into the terminal: ruby hello.rb Set Character 2.

Here’s the output in the terminal:

This is ARGV, the arguments array: ["Set", "Character", "2"].


Hello Set Character. You are 2 years old!
As we can see, ARGV is an array that has all the arguments we included when we
executed our script. One interesting thing to note: the arguments have all been
converted to strings. If we want to do some kind of computation with numbers, we
need to make sure to use to_i to convert the strings to integers.

Ruby on rails:
➢ Ruby on Rails is an open-source software used to build web applications.
Rails is a framework used to create websites using the general-purpose
programming language Ruby.
➢ It is generally considered to be a server-side web application development
platform.
➢ Rails is a framework for web application development written in Ruby. It
provides a structure to web developers for all the codes. It is manufactured to
ease web application programming by predicting what every developer needs
to begin with. Rails requires less code but provides more capabilities than
any other language or framework.

WEB TECHNOLOGIES UNIT-5[R-19] Page 36

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

➢ Rails is an opinionated software. It assumes and brings out the best way to
do something, and it is designed to promote that way. If you do it the Rails
way, you will realize your productivity is increasing.
➢ Rails is designed on the basic MVC architecture. MVC or Modal View
Controller is a software design pattern for developing web applications.

The Model View Controller principle divides the work of an application into three
separate but closely cooperative subsystems.
Model (ActiveRecord )
It maintains the relationship between the objects and the database and handles
validation, association, transactions, and more.
This subsystem is implemented in ActiveRecord library, which provides an interface
and binding between the tables in a relational database and the Ruby program code
that manipulates database records. Ruby method names are automatically
generated from the field names of database tables.
View ( ActionView )
It is a presentation of data in a particular format, triggered by a controller's
decision to present the data. They are script-based template systems like JSP, ASP,
PHP, and very easy to integrate with AJAX technology.
This subsystem is implemented in ActionView library, which is an Embedded Ruby
(ERb) based system for defining presentation templates for data presentation.
Every Web connection to a Rails application results in the displaying of a view.
Controller ( ActionController )
The facility within the application that directs traffic, on the one hand, querying the
models for specific data, and on the other hand, organizing that data (searching,
sorting, messaging it) into a form that fits the needs of a given view.
This subsystem is implemented in ActionController, which is a data broker sitting
between ActiveRecord (the database interface) and ActionView (the presentation
engine).
Pictorial Representation of MVC Framework
Given below is a pictorial representation of Ruby on Rails Framework −

WEB TECHNOLOGIES UNIT-5[R-19] Page 37

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

Directory Representation of MVC Framework


Assuming a standard, default installation over Linux, you can find them like this −
tp> cd /usr/local/lib/ruby/gems/2.2.0/gems
tp>ls
You will see subdirectories including (but not limited to) the following −
• actionpack-x.y.z
• activerecord-x.y.z
• rails-x.y.z
Over a windows installation, you can find them like this −
tp>cd ruby\lib\ruby\gems\2.2.0\gems
ruby\lib\ruby\gems\2.2.0\gems\>dir
You will see subdirectories including (but not limited to) the following −

ActionView and ActionController are bundled together under ActionPack.


ActiveRecord provides a range of programming techniques and shortcuts for
manipulating data from an SQL database. ActionController and
ActionViewprovides facilities for manipulating and displaying that data. Rails ties
it all together.
Creating an Empty Rails Web Application
Rails is both a runtime web application framework and a set of helper scripts that
automate many of the things you do when developing a web application. In this
step, we will use one such helper script to create the entire directory structure and
the initial set of files to start our Library System application.
• Go into ruby installation directory to create your application.
• Run the following command to create a skeleton for library application. It will
create the directory structure in the current directory.
tp> rails new library
This will create a subdirectory for the library application containing a complete
directory tree of folders and files for an empty Rails application. Check a complete
directory structure of the application.
Most of our development work will be creating and editing files in
the library/app subdirectories. Here's a quick run down of how to use them −
• The controllers subdirectory is where Rails looks to find controller classes. A
controller handles a web request from the user.

WEB TECHNOLOGIES UNIT-5[R-19] Page 38

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

• The views subdirectory holds the display templates to fill in with data from
our application, convert to HTML, and return to the user's browser.
• The models subdirectory holds the classes that model and wrap the data
stored in our application's database. In most frameworks, this part of the
application can grow pretty messy, tedious, verbose, and error-prone. Rails
makes it dead simple.
• The helpers subdirectory holds any helper classes used to assist the model,
view, and controller classes. This helps to keep the model, view, and
controller code small, focused, and uncluttered.
Starting Web Server
Rails web application can run under virtually any web server, but the most
convenient way to develop a Rails web application is to use the built-in WEBrick
web server. Let's start this web server and then browse to our empty library
application −
This server will be started from the application directory as follows. It runs on port
number 3000.
tp> cd ruby\library
tp\ruby\library\> Rails server
It generates the auto code to start the server as shown below −

This will start your WEBrick web server.


Now open your browser and browse to http://127.0.0.1:3000. If everything is gone
fine, then you should see a greeting message from WEBrick, otherwise there is
something wrong with your setting. If everything goes well it will generate the
output as follows.

**************************** THE END****************************

WEB TECHNOLOGIES UNIT-5[R-19] Page 39

Downloaded by Hanumantharao Murukutla ([email protected])

You might also like