wt-unit-5-serverlet-mongodb-ruby
wt-unit-5-serverlet-mongodb-ruby
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.
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:
• 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.
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:
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.
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:
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.
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.
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
Introduction to Servlet:
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.
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()
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.
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.
<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.
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.
<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>
The request object offers techniques for extracting information about the HTTP
header, including form records, cookies, HTTP methods, etc.
index.html
<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
This is the output page for userinfo.jsp. We also obtained the ID and password that
the user entered on the login tab.
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.
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>
<%
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>
• 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
❖ 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.
❖ 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
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-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-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>
<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);
}
public Connection getConnection()
{
return this.connection;
}
}
<%@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);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
try {
connection = DriverManager.getConnection(
connectionUrl + dbName, userId, password);
statement = connection.createStatement();
} 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>
</tr>
<tr>
<td></td>
<td><input type="submit" name="insert" value="Save"></td>
</tr>
</table>
</form>
</html>
Form
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());
}
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Close connection
mysqli_close($link);
?>
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
<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!");
});
Identifiers in Ruby
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
@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
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
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
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
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.
➢ 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 −
• 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 −