Web Programming Lecture Notes Overview
Web Programming Lecture Notes Overview
WEB PROGRAMMING
LECTURE NOTES
By
Ogunjimi Olalekan L. A.
(PhD (Comp. Sc.), MSc (OR), MSc (IT), BSc (Math), IPCT, NCE(Math&Physic) LMACP, MIEEE, MBCS,
MNCS, MCert, BCP, CCLA, CCWA, CCHA, CCWP, CCIA)
WEB PROGRAMMING
COURSE OBJECTIVES:
1. To study the insights of the Web architecture and how servlets works.
2. To gain knowledge in interfacing Java Servlet Program with JDBC Connection
3. To be trained to dynamically generate the web pages using Java Server Pages.
4. To understand the designing applications over web using Spring Framework.
5. To get acquainted with applications over the web using ‘Django’ Framework.
UNIT –I:
Web Basics and Overview: Introduction to Internet, World Wide Web, Web Browsers, URL ,
HTTP.
PHP: Declaring Variables, Data types, Operators, Control structures, Functions. MVC
Framework and Design Pattern, Types of PHP MVC framework.
UNIT II
Servlets: Introduction to Servlets, Benefits of Servlets, use as controller in MVC, basic HTTP,
servlet container, Servlets API, [Link] Package, Reading Servlet parameters, service
method detail. HTML clients, servlet lifecycle.
Servlets with JDBC, JDBC: Architecture - JDBC API, Passing Control and Data between Pages.
UNIT III
Java Server Pages: Generating Dynamic Content, Using Scripting Elements, Implicit JSP Objects.
Conditional Processing – Displaying Values, setting attributes, Error Handling and Debugging
UNIT IV
Spring Framework Overview, Spring Web MVC Overview, Controllers, Handler Methods, Install
and Configure WebServer, Developing Web Application using Spring.
UNIT V
Introduction to Django, Django architecture, Django Models and Database Backends,
Developing Web Application using Django
TEXT BOOKS
REFERENCE BOOKS
1. Joseph J. Bambara, Paul R. Allen, Mark Ashnault, Ziyad Dean, Thomas Garben, Sherry
Smith J2EE UNLEASHED –– SAMS Techmedia 5 StepahnieBodoff, Dale Green, Kim Hasse,
Eric Jendrock, Monica Pawlan, Beth Stearns , The J2EE Tutorial, Pearson Education ,
Asia.
2. Learning Django Web Development, SanjeevJaiswalRatanKumar,PACKT Publishing.
3. [Link]
spring framework (IBM)
UNIT - I
Web Basics and Overview: Introduction to Internet, World Wide Web, Web Browsers, URL ,
HTTP.
PHP: Declaring Variables, Data types, Operators, Control structures, Functions. MVC
Framework and Design Pattern, Types of PHP MVC framework.
The Internet is the global system of interconnected computer networks that use the Internet
protocol suite (TCP/IP) to link devices worldwide. It is a network of networks that consists of
private, public, academic, business, and government networks of local to global scope, linked by
a broad array of electronic, wireless, and optical networking technologies. The Internet carries a
vast range of information resources and services.
History of Internet
This marvelous tool has quite a history that holds its roots in the cold war scenario. A
need was realized to connect the top universities of the United States so that they can share all
the research data without having too much of a time lag. This attempt was a result of Advanced
Research Projects Agency (ARPA) which was formed at the end of 1950s just after the Russians
had climbed the space era with the launch of Sputnik. After the ARPA got success in 1969, it
didn’t take the experts long to understand that how much potential can this interconnection tool
have. In 1971 Ray Tomlinson made a system to send electronic mail. This was a big step in the
making as this opened gateways for remote computer accessing i.e. telnet.
During all this time, rigorous paper work was being done in all the elite research
institutions. From giving every computer an address to setting out the rules, everything was
getting penned down. 1973 saw the preparations for the vital TCP/IP and Ethernet services. At
the end of 1970s, Usenet groups had surfaced up. By the time the 80s had started, IBM came up
with its PC based on Intel 8088 processor which was widely used by students and universities for
it solved the purpose of easy computing. By 1982, the Defense Agencies made the TCP/IP
compulsory and the term ―internet‖ was coined. The domain name services arrived in the year
1984 which is also the time around which various internet based marked their debut. A worm, or
a rust the computers, attacked in 1988 and disabled over 10% of the computer systems all over
the world. While most of the researchers regarded it as an opportunity to enhance computing as it
was still in its juvenile phase, quite a number of computer companies became interested in
dissecting the cores of the malware which resulted to the formation Computer Emergency
Rescue Team (CERT). Soon after the world got over with the computer worm, World Wide Web
came into existence. Discovered by Tim Berners-Lee, World Wide Web was seen as a service to
connect documents in websites using hyperlinks.
World Wide Web
The World Wide Web (abbreviated WWW or the Web) is an information space where
documents and other web resources are identified by Uniform Resource Locators (URLs),
interlinked by hypertext links, and can be accessed via the Internet. English scientist Tim
Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer
program in 1990 while employed at CERN in Switzerland. The Web browser was released
outside CERN in 1991, first to other research institutions starting in January 1991 and to the
general public on the Internet in August 1991.
The World Wide Web has been central to the development of the Information Age and is
the primary tool billions of people use to interact on the Internet. Web pages are primarily text
documents formatted and annotated with Hypertext Markup Language (HTML). In addition to
formatted text, web pages may contain images, video, audio, and software components that are
rendered in the user's web browser as coherent pages of multimedia content.
Embedded hyperlinks permit users to navigate between web pages. Multiple web pages
with a common theme, a common domain name, or both, make up a website. Website content
can largely be provided by the publisher, or interactively where users contribute content or the
content depends upon the users or their actions. Websites may be mostly informative, primarily
for entertainment, or largely for commercial, governmental, or non-governmental organizational
purposes
WWW is another example of client/server computing. Each time a link is followed, the client is
requesting a document (or graphic or sound file) from a server (also called a Web server) that's
part of the World Wide Web that "serves" up the document. The server uses a protocol called
HTTP or Hyper Text Transport Protocol. The standard for creating hypertext documents for the
WWW is Hyper Text Markup Language or HTML. HTML essentially codes plain text
documents so they can be viewed on the Web.
Browsers:
WWW Clients, or "Browser": The program you use to access the WWW is known as a
browser because it "browses" the WWW and requests these hypertext documents. Browsers can
be graphical, allows to see and hear the graphics and audio;
text-only browsers (i.e., those with no sound or graphics capability) are also available. All of
these programs understand http and other Internet protocols such as FTP, gopher, mail, and
news, making the WWW a kind of "one stop shopping" for Internet users.
Year List of Web browsers
1991 World Wide Web (Nexus)
1992 Viola WWW, Erwise, MidasWWW, MacWWW (Samba)
1993 Mosaic, Cello,[2] Lynx 2.0, Arena, AMosaic 1.0
IBM WebExplorer, Netscape Navigator, SlipKnot 1.0, MacWeb, IBrowse, Agora (Argo),
1994 Minuet
Internet Explorer 1, Internet Explorer 2, Netscape Navigator 2.0, OmniWeb, UdiWWW,
1995 Grail
Arachne 1.0, Internet Explorer 3.0, Netscape Navigator 3.0, Opera 2.0,
1996 PowerBrowser 1.5,[4] Cyberdog, Amaya 0.9,[5] AWeb, Voyager
Internet Explorer 4.0, Netscape Navigator 4.0, Netscape Communicator 4.0, Opera
1997 3.0,[6] Amaya 1.0[5]
1998 iCab, Mozilla
1999 Amaya 2.0,[5] Mozilla M3, Internet Explorer 5.0
2000 Konqueror, Netscape 6, Opera 4,[7] Opera 5,[8] K-Meleon 0.2, Amaya 3.0,[5] Amaya 4.0[5]
2001 Internet Explorer 6, Galeon 1.0, Opera 6,[9] Amaya 5.0[5]
2002 Netscape 7, Mozilla 1.0, Phoenix 0.1, Links 2.0, Amaya 6.0,[5] Amaya 7.0[5]
2003 Opera 7,[10] Apple Safari 1.0, Epiphany 1.0, Amaya 8.0[5]
2004 Firefox 1.0, Netscape Browser, OmniWeb 5.0
Opera 8,[11] Apple Safari 2.0, Netscape Browser 8.0, Epiphany 1.8, Amaya 9.0,[5] AOL
2005 Explorer 1.0, Maxthon 1.0,Shiira 1.0
Mozilla Firefox 2.0, Internet Explorer 7, Opera 9,[12], SeaMonkey 1.0, K-Meleon 1.0,
2006 Galeon 2.0, Camino 1.0, Avant11, iCab 3
2007 Apple Safari 3.0, Maxthon 2.0, Netscape Navigator 9, NetSurf 1.0, Flock 1.0, Conkeror
Google Chrome 1, Mozilla Firefox 3, Opera 9.5,[13], Apple Safari 3.1, Konqueror 4, Amaya
2008 10.0,[5] Flock 2, Amaya 11.0[5]
Google Chrome 2–3, Mozilla Firefox 3.5, Internet Explorer 8, Opera 10,[14], Apple Safari 4,
2009 SeaMonkey 2, Camino 2,surf, Pale Moon 3.0[15]
Google Chrome 4–8, Mozilla Firefox 3.6, Opera 10.50,[16], Opera 11, Apple Safari 5, K-
2010 Meleon 1.5.4,
Google Chrome 9–16, Mozilla Firefox 4-9, Internet Explorer 9, Opera 11.50, Apple
2011 Safari 5.1, Maxthon 3.0, SeaMonkey 2.1–2.6
Google Chrome 17–23, Mozilla Firefox 10–17, Internet Explorer 10, Opera 12, Apple
2012 Safari 6, Maxthon 4.0, SeaMonkey 2.7-2.14
2013 Google Chrome 24–31, Mozilla Firefox 18–26, Internet Explorer 11, Opera 15–18, Apple
Safari 7, SeaMonkey 2.15-2.23
2014 Google Chrome 32–39, Mozilla Firefox 27–34, Opera 19–26, Apple Safari 8
2015 Google Chrome 40–47, Microsoft Edge, Mozilla Firefox 35–43, Opera 27–34, Vivaldi
Google Chrome 48–55, Mozilla Firefox 44–50, Microsoft Edge 14, Opera 35–42, Apple
2016 Safari 10, SeaMonkey 2.24–2.30, Pale Moon 26.0.0[17], Pale Moon 27.0.0[18]
Google Chrome 56–60, Microsoft Edge 15, Mozilla Firefox 51–55.0.2, Opera 43–45, Opera
2017 Neon
Uniform Resource Locators, or URLs: A Uniform Resource Locator, or URL is the address of
a document found on the WWW. Browser interprets the information in the URL in order to
connect to the proper Internet server and to retrieve your desired document. Each time a click on
a hyperlink in a WWW document instructs browser to find the URL that's embedded within the
hyperlink.
The elements in a URL: Protocol://server's address/filename
Servers insert the MIME header at the beginning of any Web transmission. Clients use
this header to select an appropriate "player" application for the type of data the header indicates.
Some of these players are built into the Web client or browser (for example, all browsers come
with GIF and JPEG image players as well as the ability to handle HTML files); other players
may need to be downloaded.
New MIME data types are registered with the Internet Assigned Numbers Authority
(IANA).
MIME is specified in detail in Internet Request for Comments 1521 and 1522, which
amend the original mail protocol specification, RFC 821 (the Simple Mail Transport Protocol)
and the ASCII messaging header, RFC 822.
HTTPS: A similar abbreviation, HTTPS means Hyper Text Transfer Protocol Secure.
Basically, it is the secure version of HTTP. Communications between the browser and website
are encrypted by Transport Layer Security (TLS), or its predecessor, Secure Sockets Layer
(SSL).
PHP INTRODUCTION
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. RasmusLerdorf unleashed the first version of PHP way back in 1994.
PHP is a server side scripting language that is embedded in HTML. PHP scripts are executed
on the server
It is used to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, Microsoft SQL Server , etc.)
PHP is an open source software.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the
Unix side. The MySQL server, once started, executes even very complex queries with huge
result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP Syntax is C-Like.
Common uses of PHP:
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them. The other uses of PHP are:
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send
data, return data to the user.
You add, delete, and modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP:
Simplicity
Efficiency
Security
Flexibility
Familiarity
All PHP code must be included inside one of the three special markup tags are recognized by the
PHP Parser.
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing.
<?php
$male = False;
$r = rand(0, 1);
$male = $r ? True: False;
if ($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
} ?>
The script uses a random integer generator to simulate our case. $r = rand(0, 1);
The rand( ) function returns a random number from the given integer boundaries 0 or 1.
$male = $r? True: False;
We use the ternary operator to set a $male variable. The variable is based on the random $r
value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable
is set to False.
PHP Strings
String is a data type representing textual data in computer programs. Probably the single most
important data type in programming.
<?php
$a = "PHP ";
$b = 'PERL';
echo $a . $b; ?>
Output: PHP PERL
We can use single quotes and double quotes to create string literals.
The script outputs two strings to the console. The \n is a special sequence, a new line.
The escape-sequence replacements are −
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
<?php
define("MINSIZE",50);
echo MINSIZE;
echo constant("MINSIZE");// same thing as the previous line
?>
Output: 50 50
Only scalar data (boolean, integer, float and string) can be contained in constants.
PHP - Operators:
What is Operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. PHP language supports following type of operators.
Arithmetic Operators:
There are following arithmetic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
Increment/Decrement operators
Operator Description Example
-- Decrement operator, decreases integer value by one $A-- will give 9 / --$A
Comparison Operators:
There are following comparison operators supported by PHP language Assume variable A
holds 10 and variable B holds 20 then:
Operator Description Example
== Checks if the value of two operands are equal or not ($A==$B) is not true.
!= Checks if the values of two operands are equal or not, ($A != $B) is true.
if values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the ($A >$B) is not true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or ($A >= $B) is not true.
equal to the value of right operand, if yes then returns
true.
<= Checks if the value of left operand is less than or equal ($A <= $B) is true.
to the value of right operand, if yes then condition
becomes true.
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
and (or) && Called Logical AND operator. If both the operands ($A and$B) is true.
are true then then condition becomes true.
($A &&$B) is true.
or (or) || Called Logical OR Operator. If any of the two ($A or$B) is true.
operands are non zero then then condition becomes
true. ($A || $B) is true.
Assignment Operators:
There are following assignment operators supported by PHP language:
Operator Description Example
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
result of the evaluation.
The conditional operator has this syntax:
Operator Description Example
=== Identity $x === $y (Returns true if $x and $y have the same key/value
pairs in the same order and of the same types)
If you want to execute some code if a condition is true and another code if a condition is
false, use the if....else statement.
The elseif Statement
If you want to execute some code if one of the several conditions is true use the elseif
statement
Syntax EX: <html>
if (condition) <body>
code to be executed if condition is true; <?php
elseif (condition) $d=date("D");
code to be executed if condition is true; if($d=="Fri")
else echo"Have a nice weekend!";
code to be executed if condition is false; elseif($d=="Sun")
Example echo"Have a nice Sunday!";
The following example will output "Have a else
nice weekend!" if the current day is Friday, echo"Have a nice day!";
and "Have a nice Sunday!" if the current day ?>
is Sunday. Otherwise, it will output "Have a </body>
nice day!" </html>
PHP – Functions
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value. You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you –
Creating a PHP Function
Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more
than 1000 of built-in library functions created for different area and you just need to call
them according to your requirement.
Creating PHP Function
It’s very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.
<html><head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
functionwriteMessage()
{
echo"Have a nice time Kalpana!";
}/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
Output: Have a nice time Kalpana!
<html>
<head><title>Writing PHP Function with Parameters</title></head>
<body>
<?php
functionaddFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo"Sum of the two numbers is : $sum";
}
addFunction(10,20);
?></body></html>
Output: Sum of the two numbers is : 30
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
functionaddFive($num)
{
$num+=5;
}
functionaddSix(&$num)
{
$num+=6;
}
$orignum=10;
addFive( $orignum);
echo"Original Value is $orignum<br />";
addSix( $orignum);
echo"Original Value is $orignum<br />";
?>
</body>
</html>
Output: Original Value is 10
Original Value is 16
PHP Functions returning value
A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code. You can return more than one value from a function using return array(1,2,3,4).
<html><head><title>Writing PHP Function which returns value</title></head>
<body>
<?php
functionaddFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value=addFunction(10,20);
echo"Returned value from the function : $return_value";
?></body></html>
Output:Returned value from the function : 30
Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html><head><title>Writing PHP Function which returns value</title></head>
<body>
<?php
functionprintMe($param= NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body></html>
Output:This is test
Dynamic Function Calls
It is possible to assign function names as strings to variables and then treat these variables
exactly as you would the function name itself.
<html> <html>
<head> <head>
<title>Dynamic Function <title>Dynamic Function
Calls</title></head> Calls</title></head>
<body> <body>
<?php <?php
functionsayHello() function add($x,$y)
{ {
echo "Hello<br />"; echo"addition=" . ($x+$y);
} }
$function_holder="sayHello"; $function_holder="add";
$function_holder(); $function_holder(20,30);
?></body></html> ?></body></html>
Output:Hello Output:addition=50
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight \t";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
O/P: 350 50 135 80
MVC Framework
The Model-View-Controller (MVC) is an architectural pattern that separates an application
into three main logical components: the model, the view, and the controller. Each of these
components are built to handle specific development aspects of an application. MVC is one
of the most frequently used industry-standard web development framework to create scalable
and extensible projects.
MVC Components
Following are the components of MVC −
Model
The Model component corresponds to all the data-related logic that the user works with. This
can represent either the data that is being transferred between the View and Controller
components or any other business logic-related data. For example, a Customer object will
retrieve the customer information from the database, manipulate it and update it data back to
the database or use it to render data.
View
The View component is used for all the UI logic of the application. For example, the
Customer view will include all the UI components such as text boxes, dropdowns, etc. that
the final user interacts with.
Controller
Controllers act as an interface between Model and View components to process all the
business logic and incoming requests, manipulate data using the Model component and
interact with the Views to render the final output. For example, the Customer controller will
handle all the interactions and inputs from the Customer View and update the database using
the Customer Model. The same controller will be used to view the Customer data.
Once you are comfortable with the way MVC frameworks work, you should move on to the
mature and already tested frameworks.
The table below briefly describes some of the popular php frameworks and the features that
each framework offers.
Framework Description
It is one of the most popular PHP MVC frameworks. It’s lightweight and has a short learnin
CodeIgniter rich set of libraries that help build websites and applications rapidly. Users with limited kno
programming can also use it. CodeIgniter powered applications include
It’s a Hierarchical Model View Controller HMVC secure and lightweight framework. It has
Kohana components for developing applications rapidly. Companies that use Kohana include;
CakePHP It is modeled after Ruby on rails. It’s known for concepts such as software design patterns,
configuration, ActiveRecord etc. CakePHP powered applications include;
Zend It features APIs from vendors like Amazon, Google, Flickr, Yahoo etc. It’s ideal for develo
applications. Zend powered applications include;
Pimcore CMS,
DotKernel.
BBC
Cisco
Webex
[Link]
UNIT – II
Servlets: Introduction to Servlets, Benefits of Servlets, use as controller in MVC, basic HTTP,
servlet container, Servlets API, [Link] Package, Reading Servlet parameters, service
method detail. HTML clients, servlet lifecycle.
Servlets with JDBC, JDBC: Architecture - JDBC API, Passing Control and Data between Pages.
INTRODUCTION TO SERVLETS
Servlets:
• Servlets are server side programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser and databases or
applications on the server.
• Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
• Servlets don’t fork new process for each request, instead a new thread is created.
• Servlets are loaded and ready for each request.
• The same servlet can handle many requests simultaneously.
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language
Servlet API
Servlet API consists of two important packages that encapsulates all the important classes
and interface, namely :
1. [Link]
2. [Link]
1. [Link]
Interfaces
1. Servlet – Declares life cycle methods for a servlet.
2. ServletConfig – To get initialization parameters
3. ServletContext- To log events and access information
4. ServletRequest- To read data from a client request
5. ServletResponse – To write data from client response
Classes
1. GenericServlet – Implements Servlet and ServletConfig
2. ServletInputStream – Provides an input stream for reading client requests.
3. ServletOutputStream - Provides an output stream for writing
responses to a client.
4. ServletException – Indicates servlet error occurred.
5. UnavailableException - Indicates servlet is unavailable
Servlet Interface
Method Description
public void init(ServletConfigconfig) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void provides response for the incoming request.
service(ServletRequestrequest,ServletResponse It is invoked at each request by the web
response) container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.
public ServletConfiggetServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
import [Link].*;
import [Link].*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
[Link]=config;
[Link]("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
[Link]("text/html");
PrintWriter out=[Link]();
[Link]("<html><body>");
[Link]("<b>hello KALPANA</b>");
[Link]("</body></html>");
}
public void destroy(){
[Link]("servlet is destroyed");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "copyright 2007-1010";
}
}
ServletConfig interface
• When the Web Container initializes a servlet, it creates a ServletConfig object for the
servlet.
• ServletConfig object is used to pass information to a servlet during initialization by getting
configuration information from [Link](Deployment Descriptor).
Methods
• getInitParameter(String name): returns a String value initialized parameter
• getInitParameterNames(): returns the names of the servlet's initialization parameters as an
Enumeration of String objects
• getServletContext(): returns a reference to the ServletContext
• getServletName(): returns the name of the servlet instance
ServletContext Interface
• For every Web application a ServletContext object is created by the web container.
• ServletContext object is used to get configuration information from Deployment
Descriptor([Link]) which will be available to any servlet.
Methods:
• getAttribute(String name) - returns the container attribute with the given name
• getInitParameter(String name) - returns parameter value for the specified parameter name
• getInitParameterNames() - returns the names of the context's initialization parameters as
an Enumeration of String objects
• setAttribute(String name,Objectobj) - set an object with the given attribute name in the
application scope
• removeAttribute(String name) - removes the attribute with the specified name from the
application context
Servlet RequestInterface
• True job of a Servlet is to handle client request.
• Servlet API provides two important interfaces [Link] to
encapsulate client request.
• Implementation of these interfaces provides important information about client request to
a servlet.
Methods
• getAttribute(String name), removeAttribute(String name), setAttribute(String name,
Object o), getAttributeName() – used to store and retrieve an attribute from request.
• getParameter(String name) - returns value of parameter by name
• getParameterNames() - returns an enumeration of all parameter names
• getParameterValues(String name) - returns an array of String objects containing all of the
values the given request parameter has, or null if the parameter does not exist
Servlet ResponseInterface
• Servlet API provides ServletResponseto assist in sending response to client.
Methods
• getWriter()- returns a PrintWriter object that can send character text to the client.
• setContentType(String type)- sets the content type of the response being sent to the client
before sending the respond.
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except the service
method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Methods
ServletOutputStream Class
It provides a stream to write binary data into the response. It is an abstract class.
The getOutputStream() method of ServletResponse interface returns the instance of
ServletOutputStream class.
ServletOutputStream class provides print() and println() methods that are overloaded.
2. [Link]
Interfaces
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
Classes
1. HttpServlet
[Link]
2. Parameters -
The HttpServletRequest provides methods for accessing parameters of a request. The
methods getParameter(), getParameterValues()and getParameterNames() are offered
as ways to access the arguments.
3. Attributes –
The request object defines a method called getAttribute(). The servlet interface
provides this as a way to include extra information about the request that is not covered
by any of the other HttpServletRequest methods.
4. ServletInputStream –
The ServletInputStream is an InputStream that allows your servlets to read all of the
request’s input following the headers.
HTTPSession
HttpSession object is used to store entire session with a specific client.
We can store, retrieve and remove attribute from HttpSession object.
Any servlet can have access to HttpSession object throughout the getSession() method of
the HttpServletRequest object.
HTTPServlet
HttpServlet is extends from GenericServlet and does not override init, destroy and other
methods.
It implements the service () method which is abstract method in GenericServlet.
A subclass of HttpServlet must override at least one method, usually one of these:
o doGet(), if the servlet supports HTTP GET requests
o doPost(), for HTTP POST requests
o doPut(), for HTTP PUT requests
o doDelete(), for HTTP DELETE requests
o Init() and destroy(), to manage resources that are held for the life of the servlet
o getServletInfo(), which the servlet uses to provide information about itself
Cookie
A cookie is a small piece of information that is persisted between the multiple client
requests.
[Link] class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.
Reading Servlet Parameters(or) Handling HTTPRequest and HTTPResponse
The parameters are the way in which a client or user can send information to the Http
Server.
The HTTPServletRequest interface includes methods that allow you to read the names
and values of parameters that are included in a client request.
The HttpServletResponse Interface provides functionality for sending response to client.
The browser uses two methods to pass this information to web server. These methods are
GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character as follows:
[Link]
The GET method is the defualt method to pass information from browser to web server.
Never use the GET method if you have password or other sensitive information to pass to
the server.
The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable.
Servlet handles this type of requests using doGet() method.
POST method:
A generally more reliable method of passing information to a backend program is the
POST method.
This message comes to the backend program in the form of the standard input which you
can parse and use for your processing.
Servlet handles this type of requests using doPost() method.
Life Cycle of Servlet
Life Cycle
Steps:
The sequence in which the Web container calls the life cycle methods of a servlet is:
1. The Web container loads the servlet class and creates one or more instances of the
servlet class.
2. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
3. The Web container invokes the service() method to allow a servlet to process a client
request.
4. The service() method processes the request and returns the response back to the Web
container.
5. The servlet then waits to receive and process subsequent requests as explained in steps
3 and 4.
6. The Web container calls the destroy() method before removing the servlet instance
from the service. The destroy() method is also invoked only once in a servlet life cycle.
Architecture of
JDBC
Description:
1. Application: It is a java applet or a servlet that communicates with a data
source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and
interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It
uses some database-specific drivers to effectively connect enterprise
applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you
need a JDBC driver that intelligently communicates with the respective
data source.
JDBC API
The Java Database Connectivity (JDBC) API provides universal data access from the Java
programming language. Using the JDBC API, you can access virtually any data source, from
relational databases to spreadsheets and flat files. JDBC technology also provides a common
base on which tools and alternate interfaces can be built.
[Link]
[Link]
JDBC was designed to keep simple things simple. This means that the JDBC API makes
everyday database tasks, like simple SELECT statements, very easy.
Import a package [Link].* : This package provides you set of all classes that enables a
network interface between the front end and back end database.
•DriverManager will create a Connection object.
•[Link] interface represents a connection with a specific database.
Methods of connection is close(),
creatStatement(),
prepareStatement(),
commit(),
close()
prepareCall()
•Statement interface used to interact with database via the execution of SQL statements.
Methods of this interface are executeQuery(),
executeUpdate(),
execute()
getResultSet().
•A ResultSet is returned when you execute an SQL statement. It maintains a pointer to a row
within the tablur results.
Mehods of this interface are next(),
getBoolean(),
getByte(),
getDouble(),
getString()
close()
getInt().
UNIT – III
Java Server Pages: Generating Dynamic Content, Using Scripting Elements, Implicit JSP
Objects. Conditional Processing – Displaying Values, setting attributes, Error Handling and
Debugging
Servlet technology and JavaServer Pages (JSP) are the two main technologies for developing
java Web applications. When first introduced by Sun Microsystems in 1996, the Servlet
technology was considered superior to the reigning Common Gateway Interface (CGI)
because servlets stay in memory after they service the first requests. Subsequent requests for
the same servlet do not require instantiation of the servlet’s class therefore enabling better
responsetime.
Servlets are Java classes that implement the [Link] interface. They are
compiled and deployed in the web server. The problem with servlets is that you embed
HTML in Java code. If you want to modify the cosmetic look of the page or you want to
modify the structure of the page, you have to change code. Generally speaking, this
is left to the better hands (and brains) of a web page designer and not to aJava developer.
PrintWriter pw = [Link]();
[Link]("<html><head><title>Testing</title></head>"); [Link]("<body
bgcolor=\"# ffdddd\">");
As seen from the example above this method presents several difficulties to the web
developer:
1. The code for a servlet becomes difficult to understand for theprogrammer.
2. The HTML content of such a page is difficult if not impossible for a web designer to
understand ordesign.
3. This is hard to program and even small changes in the presentation, such as the page’s
background color, will
[Link]
hewholeservlet.
4. It's hard to take advantage of web-page development tools when designing the
application interface. If such tools are used to develop the web page layout, the
generated HTML must then be manually embedded into the servlet code, a process
which is time consuming, error prone, and extremelyboring.
5. In many Java servlet-based applications, processing the request and generating the
response are both handled by a single servletclass.
6. The servlet contains request processing and business logic (implemented by methods ),
and also generates the response HTML code, are embedded directly in the servletcode.
JSP solves these problems by giving a way to include java code into an HTML page using
scriptlets. This way the HTML code remains intact and easily accessible to web designers,
but the page can sill perform itstask.
In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java
tools: JavaServer Pages (JSP). JavaServer Pages are built on top of Java servlets and
designed to increase the efficiency in which programmers, and even nonprogrammers, can
create webcontent.
Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as in
a regular web page, and add a few JSP elements to generate the dynamic parts of the page.
The request processing can remain the domain of the servlet, and the business logic can be
handled by JavaBeans and EJBcomponents.
A JSP page is handled differently compared to a servlet by the web server. When a servlet is
deployed into a web server in compiled (bytecode) form, then a JSP page is deployed in its
original, human-readable form.
When a user requests the specific page, the web server compiles the page into a servlet and
from there on handles it as a standard servlet.
This accounts for a small delay, when a JSP page is first requested, but any subsequent
requests benefit from the same speed effects that are associated with servlets.
The Problem with Servlet
• Servlets are difficult to code which are overcome in JSP. Other way, we can say, JSP is
almost a replacement of Servlets, (by large, the better word is extension of Servlets),
where coding decreases more than half.
• In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example,In Servlets:
[Link](―Hello Mr.‖ + str + ‖ you are great man‖);
wherestr is the name of the client which changes for each client and is known as dynamic
content. The strings, ―Hello Mr.‖ and ―you are great man‖ are static content which is the
same irrespective of client. In Servlets, in println(), both are put together.
• In JSP, the static content and dynamic content is separated. Static content is written in
HTML and dynamic content in JSP. As much of the response comprises of static content
(nearly 70%) only, the JSP file more looks as a HTML file.
• Programmer inserts, here and there, chunks of JSP code in a running HTML developed
by Designer. As much of the response delivered to cleint by server comprises of static
content (nearly 70%), the JSP file more looks like a HTML file. Other way we can say,
JSP is nothting but Java in HTML (servlets are HTML
• in Java); java code embedded in HTML.
• When the roles of Designer and Programmer are nicely separated, the product
development becomes cleaner and fast. Cost of developing Web site becomes cheaper as
Designers are much paid less than Programmers, especially should be thought in the
present competitive world.
• Both presentation layer and business logic layer put together in Servlets. In JSP, they can
be separated with the usage of JavaBeans.
• The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets and used. But in JSP,
they are builtin and are known as "implicit objects". That is, in JSP, Programmer never
creates these objects and straightaway use them as they are implicitly created and given
by JSP container. This decreases lot of coding.
• JSP can easily be integrated with JavaBeans.
• JSP is much used in frameworks like Sturts etc.
• With JSP, Programmer can build custom tags that can be called in JavaBeans directly.
Servlets do not have this advantage. Reusability increases with tag libraries and JavaBean
etc.
• Writing alias name in <url-pattern> tag of [Link] is optional in JSP but mandatory in
Servlets.
• A Servlet is simply a Java class with extension .java written in normal Java code.
• A Servlet is a Java class. It is written like a normal Java. JSP is comes with some
elements that are easy to write.
• JSP needs no compilation by the Programmer. Programmer deploys directly a JSP
source code file in server where asincase of Servlets, the Programmer compiles manually
a Servlet file and deploys a .class file in server.
• JSP is so easy even a Web Designer can put small interactive code (not knowing much
of Java) in static Web pages.
• First time when JSP is called it is compiled to a Servlet. Subsequent calls to the same
JSP will call the same compiled servlet (instead of converting the JSP to servlet),
Ofcourse, the JSP code would have not modified. This increases performance.
Anatomy of JSP
JSP Processing
Once you have a JSP capable web-server or application server, you need to know the
following information about it:
• Where to place the files
• How to access the files from your browser (with an http: prefix, not as file:)
You should be able to create a simple file, such as
<HTML>
<BODY>
Hello, world
</BODY></HTML>
Know where to place this file and how to see it in your browser with an http:// prefix.
Since this step is different for each web-server, you would need to see the web-server
documentation to find out how this is done. Once you have completed this step, proceed to
the next.
Your first JSP
JSP simply puts Java inside HTML pages. You can take any existing HTML page and change
its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your first JSP.
Take the HTML file you used in the previous exercise. Change its extension from ".html" to
".jsp". Now load the new file, with the ".jsp" extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you
reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file,
compiled and loaded. This compilation only happens once, so after the first load, the file
doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-
compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We now
proceed to see what makes JSP so useful
Adding dynamic content via expressions
As we saw in the previous section, any HTML file can be turned into a JSP file by changing
its extension to .jsp. Of course, what makes JSP useful is the ability to embed Java. Put the
following text in a file with .jsp extension (let us call it [Link]), place it in your JSP
directory, and view it in a browser.
<HTML>
<BODY>
Hello! The time is now <%= new [Link]() %>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the current time.
The character sequences
<%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dyamic HTML pages that change in
response to user actions or vary from user to user.
1 Request
This is the HttpServletRequest object associated with the request.
Response
2
This is the HttpServletResponse object associated with the response to the
client.
3 Out
This is the PrintWriter object used to send output to the client.
4 Session
This is the HttpSession object associated with the request.
5 Application
This is the ServletContext object associated with the application context.
6 Config
This is the ServletConfig object associated with the page.
pageContext
7
This encapsulates use of server-specific features like higher
performance JspWriters.
Page
8
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
9
The Exception object allows the exception data to be accessed by designated
JSP.
1 [Link](dataTypedt)
Print a data type value
2 [Link](dataTypedt)
Print a data type value then terminate the line with new line character.
3 [Link]()
Flush the stream.
Spring supports a wide range of application scenarios. In a large enterprise, applications often
exist for a long time and have to run on a JDK and application server whose upgrade cycle is
beyond developer control. Others may run as a single jar with the server embedded, possibly
in a cloud environment. Yet others may be standalone applications (such as batch or
integration workloads) that do not need a server.
Spring is open source. It has a large and active community that provides continuous feedback
based on a diverse range of real-world use cases. This has helped Spring to successfully
evolve over a very long time.
The Spring Framework is divided into modules. Applications can choose which modules they
need. At the heart are the modules of the core container, including a configuration model and
a dependency injection mechanism. Beyond that, the Spring Framework provides
foundational support for different application architectures, including messaging,
transactional data and persistence, and web. It also includes the Servlet-based Spring MVC
web framework and, in parallel, the Spring WebFlux reactive web framework.
A note about modules: Spring’s framework jars allow for deployment to JDK 9’s module
path ("Jigsaw"). For use in Jigsaw-enabled applications, the Spring Framework 5 jars come
with "Automatic-Module-Name" manifest entries which define stable language-level module
names ("[Link]", "[Link]", etc.) independent from jar artifact names (the jars
follow the same naming pattern with "-" instead of ".", e.g. "spring-core" and "spring-
context"). Of course, Spring’s framework jars keep working fine on the classpath on both
JDK 8 and 9+.
2. History of Spring and the Spring Framework
Spring came into being in 2003 as a response to the complexity of the
early J2EE specifications. While some consider Java EE and Spring to be in competition,
Spring is, in fact, complementary to Java EE. The Spring programming model does not
embrace the Java EE platform specification; rather, it integrates with carefully selected
individual specifications from the EE umbrella:
The Spring Framework also supports the Dependency Injection (JSR 330) and Common
Annotations (JSR 250) specifications, which application developers may choose to use
instead of the Spring-specific mechanisms provided by the Spring Framework.
As of Spring Framework 5.0, Spring requires the Java EE 7 level (e.g. Servlet 3.1+, JPA
2.1+) as a minimum - while at the same time providing out-of-the-box integration with newer
APIs at the Java EE 8 level (e.g. Servlet 4.0, JSON Binding API) when encountered at
runtime. This keeps Spring fully compatible with e.g. Tomcat 8 and 9, WebSphere 9, and
JBoss EAP 7.
Over time, the role of Java EE in application development has evolved. In the early days of
Java EE and Spring, applications were created to be deployed to an application server. Today,
with the help of Spring Boot, applications are created in a devops- and cloud-friendly way,
with the Servlet container embedded and trivial to change. As of Spring Framework 5, a
WebFlux application does not even use the Servlet API directly and can run on servers (such
as Netty) that are not Servlet containers.
Spring continues to innovate and to evolve. Beyond the Spring Framework, there are other
projects, such as Spring Boot, Spring Security, Spring Data, Spring Cloud, Spring Batch,
among others. It’s important to remember that each project has its own source code
repository, issue tracker, and release cadence. See [Link]/projects for the complete list of
Spring projects.
3. Design Philosophy
When you learn about a framework, it’s important to know not only what it does but what
principles it follows. Here are the guiding principles of the Spring Framework:
Provide choice at every level. Spring lets you defer design decisions as late as
possible. For example, you can switch persistence providers through configuration
without changing your code. The same is true for many other infrastructure concerns
and integration with third-party APIs.
Care about API design. The Spring team puts a lot of thought and time into making
APIs that are intuitive and that hold up across many versions and many years.
Set high standards for code quality. The Spring Framework puts a strong emphasis on
meaningful, current, and accurate javadoc. It is one of very few projects that can
claim clean code structure with no circular dependencies between packages.
The Model encapsulates the application data and in general, they will consist of POJO.
The View is responsible for rendering the model data and in general, it
generates HTML output that the client's browser can interpret.
The Controller is responsible for processing User Requests and Building Appropriate
Model and passes it to the view for rendering.
Required Configuration
We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in
the [Link] file. The following is an example to show declaration and mapping
for HelloWeb DispatcherServlet −
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
[Link]
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>
The [Link] file will be kept in the WebContent/WEB-INF directory of your web application. Upon
initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context
from a file named [servlet-name]-[Link] located in the application's WebContent/WEB-INF
directory. In this case, our file will be [Link].
Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet.
Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet.
If you do not want to go with the default filename as [servlet-name]-[Link] and default location
as WebContent/WEB-INF, you can customize this file name and location by adding the servlet
listener ContextLoaderListener in your [Link] file as follows −
<web-app...>
<listener>
<listener-class>
[Link]
</listener-class>
</listener>
</web-app>
Now, let us check the required configuration for [Link] file, placed in your web
application's WebContent/WEB-INF directory.
<beans xmlns = "[Link]
xmlns:context = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "
[Link]
[Link]
[Link]
[Link]
</beans>
Following are some important points about [Link] file −
The [servlet-name]-[Link] file will be used to create the beans defined, overriding the
definitions of any beans defined with the same name in the global scope.
The <context:component-scan...> tag will be used to activate the Spring MVC annotation
scanning capability, which allows to make use of annotations
like @Controller and @RequestMapping, etc.
The InternalResourceViewResolver will have rules defined to resolve the view names. As per
the above-defined rule, a logical view named hello is delegated to a view implementation
located at /WEB-INF/jsp/[Link].
Let us now understand how to create the actual components i.e., Controller, Model and View.
Defining a Controller
The DispatcherServlet delegates the request to the controllers to execute the functionality specific to
it. The @Controller annotation indicates that a particular class serves the role of a controller.
The @RequestMapping annotation is used to map a URL to either an entire class or a particular
handler method.
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = [Link])
public String printHello(ModelMap model) {
[Link]("message", "Hello Spring MVC Framework!");
return "hello";
}
}
The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage
of @RequestMapping indicates that all handling methods on this controller are relative to
the /hello path.
The next annotation @RequestMapping (method = [Link]) is used to declare
the printHello() method as the controller's default service method to handle HTTP GET request. We
can define another method to handle any POST request at the same URL.
We can also write the above controller in another form, where we can add additional attributes in the
@RequestMapping as follows −
@Controller
public class HelloController{
}
The value attribute indicates the URL to which the handler method is mapped and
the method attribute defines the service method to handle the HTTP GET request.
Following are some important points to be noted regarding the controller defined above −
You will define the required business logic inside a service method. You can call another
method inside this method as per the requirement.
Based on the business logic defined, you will create a model within this method. You can set
different model attributes and these attributes will be accessed by the view to present the result.
This example creates a model with its attribute "message".
A defined service method can return a String, which contains the name of the view to be used
to render the model. This example returns "hello" as the logical view name.
Creating JSP Views
Spring MVC supports many types of views for different presentation technologies. These include -
JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON,
Atom and RSS feeds, JasperReports, etc. However, the most common ones are the JSP templates
written with JSTL. So, let us write a simple hello view in /WEB-INF/hello/[Link] −
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
CONTROLLERS
The following example shows how to use the Controller Class Name Handler
Mapping using the Spring Web MVC framework.
The ControllerClassNameHandlerMapping class is the convention-based handler
mapping class, which maps the URL request(s) to the name of the controllers
mentioned in the configuration. This class takes the Controller names and converts
them to lower case with a leading "/".
For example − HelloController maps to "/hello*" URL.
<beans>
<bean class="[Link]">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
[Link]("message", "Hello World!");
return model;
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
[Link]("message", "Welcome!");
return model;
}
}
[Link]
<beans xmlns = "[Link]
xmlns:context = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "
[Link]
[Link]
[Link]
[Link]
[Link]
<%@ page contentType = "text/html; charset=UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
Once you are done with creating source and configuration files, export your application. Right click on
the application, use the Export → WAR File option and save the [Link] file in Tomcat's
webapps folder.
Now, start your Tomcat server and make sure you are able to access other webpages from the
webapps folder using a standard browser. Try a URL
− [Link] and we will see the following screen, if everything
is fine with the Spring Web Application.
Step Description
1 Create a Dynamic Web Project with a name HelloWeb and create a
package [Link] under the src folder in the created project
2 Drag and drop below mentioned Spring and other libraries into the folder WebContent/WEB-
INF/lib.
3 Create a Java classes Student, StudentController and SpringException under
the [Link] package.
4 Create Spring configuration files [Link] and [Link] under the WebContent/WEB-
INF folder.
5 Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a view
files [Link], [Link], [Link], and [Link] under jsp sub-folder.
6 The final step is to create the content of all the source and configuration files and export the
application as explained below.
Following is the content of [Link] file
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = [Link])
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = [Link])
@ExceptionHandler({[Link]})
public String addStudent( @ModelAttribute("HelloWeb")Student student,
ModelMap model) {
if([Link]().length() < 5 ){
throw new SpringException("Given name is too short");
} else {
[Link]("name", [Link]());
}
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Following is the content of another Spring Web configuration file [Link]
<beans xmlns = "[Link]
xmlns:context = "[Link]
axmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]
[Link]
[Link]
</beans>
Here you specified ExceptionPage as an exception view in case SpringException occurs, if there is
any other type of exception then a generic view error will take place.
Following is the content of Spring view file [Link]
<%@taglib uri = "[Link] prefix = "form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id" /></td>
</tr>
<tr>
<td colspan = "2"><input type = "submit" value = "Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Following is the content of Spring view file [Link]
<html>
<head>
<title>Spring Error Page</title>
</head>
<body>
<p>An error occured, please contact webmaster.</p>
</body>
</html>
Following is the content of Spring view file [Link]. Here you will access the exception
instance via ${exception}.
<%@taglib uri = "[Link] prefix = "form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h2>Spring MVC Exception Handling</h2>
<h3>${[Link]}</h3>
</body>
</html>
Following is the content of Spring view file [Link]
<%@taglib uri = "[Link] prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
Finally, following is the list of Spring and other libraries to be included in your web application. You
simply drag these files and drop them in WebContent/WEB-INF/lib folder.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Once you are done creating the source and configuration files, export your application. Right-click on
your application and use the Export > WAR File option and save [Link] file in
Tomcat's webapps folder.
Now start your Tomcat server and make sure you are able to access other web pages from webapps
folder using a standard browser. Now try to access the URL [Link] If
everything is fine with your Spring Web Applicationand, you should see the following result.
Enter the values as shown above and click the Submit buttom. If everything is fine with your
Spring Web Application, you should see the following result.
You can install WAMP to the default c:\wamp directory, which it suggests. You can also use
the default SMTP and e-mail settings it suggests, which you can change later if you need to. At
some point, it will ask you to choose
your default browser. Since I have Google Chrome installed, I want to use that as my default. The
quickest way to find that executable is to right-click the Google Chrome shortcut icon and select
Properties ° Shortcut. Then copy the whole Target value and paste it into the File name box. This
is demonstrated in Figures A-2 and A-3.
After you have completed the installation of WAMP, you will see a new icon in your system
tray. If you left- click on this icon, you will see a pop-up menu. Click localhost.
Developing Web Application using Spring.
Web Applications
Spring makes building web applications fast and hassle-free. By removing much of the boilerplate
code and configuration associated with web development, you get a modern web programming model
that streamlines the development of server-side HTML applications, REST APIs, and bidirectional,
event-based systems.
Developer productivity
Spring Boot is the starting point of your developer experience, whatever you’re building. Spring Boot
is designed to get you up and running as quickly as possible, with minimal upfront configuration. With
its embedded application servers, you can be serving in seconds.
Spring’s out-of-the-box, production-ready features (like tracing, metrics, and health status) provide
developers with deep insight into their applications.
Finally, Spring supports multiple JVM languages: Java, Kotlin, and Groovy.
Battle-tested security
When it’s time to secure your web application, Spring Security supports many industry-standard
authentication protocols, including SAML, OAuth, and LDAP.
Get protection from top OWASP attacks, such as session fixation, clickjacking, cross-site request
forgery, and more.
Data access made easy
Spring helps developers connect their web applications to a number of data stores. It supports
relational and non-relational databases, map-reduce frameworks, and cloud-based data services.
Get Started with JPA or Get Started with MongoDB
Unit- V
Introduction to Django
Django is a Python-based web framework that allows you to quickly create efficient web applications.
It is also called batteries included framework because Django provides built-in features for everything
including Django Admin Interface, default database – SQLlite3, etc. When you’re building a website,
you always need a similar set of components: a way to handle user authentication (signing up, signing
in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives
you ready-made components to use and that too for rapid development.
Why Django Framework ?
Excellent documentation and high scalability.
Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket,
Dropbox, etc. and the list is never-ending.
Easiest Framework to learn, rapid development and Batteries fully included.
The last but not least reason to learn Django is Python, Python has huge library and features such
as Web Scrapping, Machine Learning, Image Processing, Scientific Computing, etc. One can
integrate it all this with web application and do lots and lots of advance stuff.
2. View
This component contains the UI logic in the Django architecture.
View is actually the User Interface of the web-application and contains the parts like HTML, CSS and
other frontend technologies. Generally, this UI creates from the Models component, i.e., the content
comes from the Models component.
For example:
When you click on any link or interact with the website components, the new webpages that
website generates is actually the specific views that stores and generates when we are interacting
with the specific components.
3. Controller
The controller as the name suggests is the main control component. What that means is, the
controller handles the user interaction and selects a view according to the model.
The main task of the controller is to select a view component according to the user interaction and
also applying the model component.
This architecture has lots of advantages and that’s why Django is also based on this architecture. It
takes the same model to an advanced level.
For example:
When we combine the two previous examples, then we can very clearly see that the component
which is actually selecting different views and transferring the data to the model’s component is the
controller.
Django Models and Database Backends
Databases
Django officially supports the following databases:
PostgreSQL
MariaDB
MySQL
Oracle
SQLite
PostgreSQL notes
Django supports PostgreSQL 10 and higher. psycopg2 2.8.4 or higher is required, though the
latest release is recommended.
PostgreSQL connection settings
See HOST for details.
To connect using a service name from the connection service file and a password from the
password file, you must specify them in the OPTIONS part of your database configuration in
DATABASES:
[Link]¶
DATABASES = {
'default': {
'ENGINE': '[Link]',
'OPTIONS': {
'service': 'my_service',
'passfile': '.my_pgpass',
},
}
}
MariaDB notes
To use MariaDB, use the MySQL backend, which is shared between the two. See the MySQL
notes for more details.
MySQL notes
Version support
MySQL notes
Version support
Django supports MySQL 5.7 and [Link]’s inspectdb feature uses the
information_schema database, which contains detailed data on all database [Link]
expects the database to support Unicode (UTF-8 encoding) and delegates to it the task of
enforcing transactions and referential integrity. It is important to be aware of the fact that the
two latter ones aren’t actually enforced by MySQL when using the MyISAM storage engine,
see the next section.