Ip Manual
Ip Manual
LABORATORY MANUAL
191CS62B – INTERNET PROGRAMMING LABORATORY
Prepared By
1.Dr.M.Victor Jose
Professor/CSE
2.Mr P Karthick
Asst. Professor/CSE
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH)
Accredited by NAAC.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.
NAME :
REGISTER NO :
VM NO :
BRANCH : B.E - COMPUTER SCIENCE AND ENGINEERING
YEAR : III
SEMESTER : VI
REGULATION : 2019
To emerge as centre for academic excellence in the field of Computer Science and Engineering by exposure to research
Vision
and industry practices.
Mission
M1 - To provide good teaching and learning environment with conducive research atmosphere in the field of Computer
Science and Engineering.
M2 - To propagate lifelong learning.
M3 - To impart the right proportion of knowledge, attitudes and ethics in students to enable them take up positions of
responsibility in the society and make significant contributions.
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.
CERTIFICATE
Name: …………………….……………………………..………….….…………………………..…
Year: ……………… Semester: .................... , Branch: B.E – Computer Science and Engineering
Certified that this is the bonafide record of work done by the above student in the
191CS62B – INTERNET PROGRAMMING LABORATORY during the academic year 2022-23.
Submitted for the University Practical Examination held on ………………... at VEL TECH MULTI TECH
Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, #42, AVADI – VEL TECH ROAD,
AVADI, CHENNAI- 600062.
Signature of Examiners
Date:………………..
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Design solutions for complex computer science and engineering problems using
state of the art tools and techniques, components or processes that meet specified
PEO3
needs with appropriate consideration for public health and safety, cultural, societal,
and environmental considerations.
The design techniques, analysis and the building, testing, operation and
PSO2 maintenance of networks, databases, security and computer systems (both
hardware and software).
An ability to identify, formulate and solve hardware and software problems using
PSO3
sound computer engineering principles.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Problem Analysis: Identify, formulate, review research literature and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
Design / Development of solutions: Design solutions for complex engineering problems and design
PO3 system components or processes that meet specified needs with appropriate consideration for public
health and safety, cultural, societal, and environmental considerations.
Conduct Investigations of Complex Problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO8
engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
PO9
teams, and in multidisciplinary settings.
Project Management and Finance: Demonstrate knowledge and understanding of the engineering and
PO11 management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life-long learning in the broadest context of technological change.
COURSE OBJECTIVES
The student should be made to:
COURSE OUTCOMES
CO-PO &
PSO Mapping
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 3 3 3 3 3 2 1 - - - - 1 3 3 2
CO2 3 3 3 3 2 1 - - - - - 1 3 3 1
CO3 3 3 3 3 2 1 - - - - - 1 3 3 1
CO4 3 3 3 3 3 1 - - 1 - - 1 3 3 1
CO5 3 3 3 3 2 1 1 - - - 1 3 3 1
3 3 3 3 2 1 1 - 1 - - 1
CO 3 3 1
PO's PSO’s
Course Outcome
PSO 1
PSO 2
PSO 3
PO10
PO11
PO12
PO 1
PO 2
PO 3
PO 4
PO 5
PO 6
PO 7
PO 8
PO 9
CO1 3 3 3 3 3 2 1 - - - - 1 3 3 2
CO2 3 3 3 3 2 1 - - - - - 1 3 3 1
CO3 3 3 3 3 2 1 - - - - - 1 3 3 1
CO4 3 3 3 3 3 1 - - 1 - - 1 3 3 1
CO5 3 3 3 3 2 1 1 - - - - 1 3 3 1
CO 3 3 3 3 2 1 1 - 1 - - 1 3 3 1
6
Course Code : 191CS62B
Course Name : INTERNET PROGRAMMING LABORATORY
COURSE PLAN
Ex.
List of COs Page
No
Exercises No
Create a web page with the following usingHTML
1 a. To embed a map in a web page
b. To fix the hot spots in that map
CO1
c. Show all the related information when the hotspots are
clicked.
Create a web page with the following.
2 a. Cascading style sheets.
b. Embedded style sheets.
CO1
c. Inline style sheets. Use our college informationfor the web
pages.
Validate the Registration, user login, user profileand payment
3 by credit card pages using JavaScript. CO1,CO2
Write programs in Java using Servlets:
4 a. To invoke servlets from HTML forms
CO1,CO3
b. Session tracking using hidden form fields andSession
tracking for a hit count.
Write programs in Java to create three-tier
5 applications using servlets for conducting onlineexamination
for displaying student mark list. CO1,CO3
Assume that student information is available in a database which
has been stored in a database server.
Install TOMCAT web server. Convert the static web pages of
6 programs into dynamic web pages using servlets (or JSP) and
cookies. Hint: Users information (user id, password, credit card CO1-CO3
number) would be stored in web.xml. Each user should have a
separate Shopping Cart.
Redo the previous task using JSP by convertingthe static web
7 pages into dynamic web pages. Create a database with user
information and books information. The books catalogue
CO1,CO3
should
be dynamically loaded from the database.
Create and save an XML document at the server, which contains
8 10 users Information. Write a Program, which takes user Id as
an input and returns the User details by taking the user CO1-CO3
information from the XML document.
a. Validate the form using PHP regular expression.
9 b. PHP stores a form data into database. CO1,CO3,CO
4
Write a web service for finding what people think by asking 500
10 people‘s opinion for any consumer product CO1,CO3,CO4
, C05
Create a Spring MVC application. The
CO1,CO3,CO4
11 application should handle form validation, fileupload, session
, CO5
tracking
Ex. No: 1 Create a web page with the following using HTML
DATE: a. To embed a map in a web page
b. To fix the hot spots in that map
c. Show all the related information when the hot spots are clicked.
AIM:
To create a web page with the following using HTML.
i. i) To embed a map in a web page.
ii) To fix the hot spots in that map.
iii) Show all the related information when the hotspots are clicked.
ALGORITHM:
● Open a notepad.
● Write the code for imagemap.html.
● Enter a program that includes tags for <MAP> and other tags.
● Insert Hyperlink using <A href>.
● Save the file with .html extension.
● Run the program in a web browser
● Display Results.
SOURCE CODE:
Main.html
HOME.HTML
<html>
<head>
<title>Home - States of India!!!</title>
</head>
<body bgcolor="gold">
<h1><u><center>Republic of India</center></u></h1>
<p>
India is the Seventh Lagest country in the world by geographical area, the
secondmost populous country with over 1.2 billion people, and the populus
democracy in theworld. India is a federal constitutional republic with a parliamentry
democracy consistingof 28 states and 7 union Terriories.
</p>
<center>
<img align="center" size="100" src="IndiaMap.jpg" usemap="#india"/>
<map name="india">
<area shape="circle" coords="160,340,20" href="ANDHRAPRADESH.html">
<area shape="circle" coords="120,440,10" href="KERALA.html">
<area shape="circle" coords="110,370,20" href=" KARNATAKA.html">
<area shape="circle" coords="140,420,20" href="TAMILNADU.html">
</map></center>
<h2> Features</h2>
<ul>
<li><b>Population</b> - 1,028,783,343(2001 census).
<li><b>Capital</b> - New Delhi
<li><b>Largest City</b> - Mumbai
<li><b>Currency</b> - Indian Rupee
<li><b>Time Format</b> - IST (UTC + 5:30)
<li><b>NAtion Sport</b> - Hockey
<li><b>Current PM</b> - Manmohan Singh
<li><b>Current President</b> - Prathiba Patil</li></ul>
<h2>
<b>To view details of states please click on the specified area in the map !!!</b>
</h2>
</body>
</html>
ANDHRAPRADESH.HTML
<html>
<head><title>Andhra Pradesh - India</title></head>
<body bgcolor="tan">
<h1><center>Andhra Pradesh</center></h1>
<h3>A.P., is a state situated on the southeastern coast of India.
It is India's fourth largest state by area and fifth largest by
population.</h3>
<h3>
<ul>
<li>Districts<i> - 23</i>
<li>Capital City<i> - Hyderabad</i>
<li>Largest City<i> - Hyderabad</i>
<li>Governor<i> - E. S. L. Narasimhan</i>
<li>Chief Minister<i> - N. Kiran Kumar Reddy</i>
<li>Population<i> - 78,323,330</i>
<li>Tourist spots<i> - Tirumala Tirupati, Charminar, Golconda
Fort, Chandragiri, Chowmahalla Place, Falaknuma Palace
etc.,</i>
</ul>
<a href="Home.html">back</a>
</body>
</html>
KARNATAKA.HTML
<html>
<head><title>Karnataka - India</title></head>
<body bgcolor="wheat">
<h1><center>Karnataka</center></h1>
<h3>
<ul>
<li>Districts<i> - 30</i>
<li>Capital City<i> - Bangalore</i>
<li>Largest City<i> - Bangalore</i>
<li>Governor<i>- Hansraj Bhardwaj</i>
<li>Chief Minister<i> - D. V. Sadananda Gowda</i>
<li>Population<i> - 61,130,704</i>
<li>Tourist spots<i> - Gol Gumbaz, Mysore Palace, Keshava Temple etc.,</i>
</ul></h3>
<a href="Home.html">back</a>
</body>
</html>
KERALA.HTML
<html>
<head><title>Kerala - India</title></head>
<body bgcolor="indianred">
<h1><center>Kerala</center></h1>
<h3>
<ul>
<li>Districts<i> - 14</i>
<li>Capital City<i> - Thiruvanandapuram</i>
<li>Largest City<i> - Thiruvanandapuram</i>
<li>Governor<i> - Hansraj Bhardwaj</i>
<li>Chief Minister<i> -Oommen Chandy </i>
<li>Population<i> - 33,387,677</i>
<li>Tourist spots<i>Edakkal Caves, Palayur, KovalamBeach,Munnar, Kochi, Alapuzha etc.,</i>
</ul>
</h3>
<a href="Home.html">Back</a>
</body>
</html>
TAMILNADU.HTML
<html>
<head><title>Tanil Nadu - India</title></head>
<body bgcolor="palegreen">
<h1><center>Tamil Nadu</center></h1>
<h3>is one of the 28 states of India. Its capital and largest city is Chennai.
Tamil Nadu lies in the southernmost part of the Indian Peninsula and
is bordered by the States of puducherry, Kerala, Karnataka, Andha Pradesh.
</h3>
<h3>
<ul>
<li>Districts<i> - 32</i>
<li>Capital City<i> - Chennai</i>
<li>Largest City<i> - Chennai</i>
<li>Governor<i> - KonijetiRosaiah</i>
<li>Chief Minister<i> - Jayalalithaa</i>
<li>Population<i> - 72,138,958</i>
<li>Tourist spots<i> - Mamallapuran, Ooty, Kodaikanal,
Marina, Mudurai Meenakshi Amman Temple, Thanjavur
etc.,</i>
</ul>
<a href="Home.html">back</a>
</body>
</html>
OUTPUT:
RESULT:
Thus creation of a web page using html has been developed successfully.
Ex. No: 2 Create a web page with the following. a. Cascading style sheets.
DATE: b. Embedded style sheets. c. Inline style sheets. Use our college
information for the web pages.
AIM:
To write a webpage that displays college information using various style sheet.
ALGORITHM:
● Start the program.
● Create a web page with framesets consisting two frames.
● In the first frame include the links.
● In the second frameset display the webpage of the link.
● Create a external style sheets.
● Create a inline and internal style and make a link to the external style sheet.
● Stop the program.
SOURCE CODE:
CSSFILE.HTML
<html>
<head>
<title>VTMT</title>
<!--Extended Style Sheet -->
<link rel="stylesheet" type="text/css" href="css.css">
<!-- Embed Style Sheet-->
<style type="text/css">
p{
background-color: lightgrey;
text-align: justify;
margin: 2em 7em;
}
</style>
</head>
<body id="body">
<h1>VTMT</h1>
<p>
<span style="font: 200 x-large fantasy">VELTECH MULTITECH</span>
Vel Tech Multi Tech Dr. Rangarajan Dr. Sakunthala Engineering College, An Autonomous
Institution, has been accredited by NAAC in the year 2016 with ‘A’ Grade and with an
impressive score of 3.49 / 4.0. The Departments of BME, CSE, ECE, EEE, IT & MECH are
accredited by National Board of Accreditation. The Institution stands among the top 200
Institutions in NIRF India Raking consecutively for three years in a row. Vel Tech Multi Tech is
the first Self Financing Affiliated Institution to bag Diamond rating in maximum categories in QS
– IGAUGE Indian College and University Ranking. Our Institution excels as one of the top
premiere institutes in India owing to its State of the art Infrastructure, well equipped
laboratories, and highly qualified and experienced faculty members.
</p>
<!-- Inline Sytle Sheet-->
<table style="background-position: center;text-align: center;padding: 3px;">
<tr>
<tdalign="left">
<div class="div">
<ul>
<li><a href="">AI&DS</a></li>
<li><a href="">MECHANICAL</a></li>
<li><a href="">CSE</a></li>
<li><a href="">BIO-MEDICAL</a></li>
</ul>
</div>
</td>
</tr>
</table>
</body>
</html>
CSS.CSS
h1,h2{
text-decoration:
underline; font-style:
italic;
text-align: center;
}
#body{
background-color:
tan; border: red
dotted; text-align:
center;
}
.div{
border: perusolid ;
}
*{
letter-spacing: 1px;
}
a:link{
color:
black;
}
a:visited{
color:
yellow;
}
a:hover{
color: green;
}
a:active{
color: blue;
}
ulli{
font-size: small;
OUTPUT:
RESULT:
Thus creation of a college information web page using cascading style sheet has been
developed successfully.
EX.NO:03 Validate the Registration, user login, user profile and payment
DATE: by credit card pages using JavaScript
AIM:
Validate the Registration, user login, user profile and payment by credit card pages using
Java Script.
ALGORITHM:
script.
Home page:
Main.html:
<html>
<frameset rows="25%,*">
<frame src="top.html" name="top" scrolling ="no" frameborder ="0">
<frameset cols="25%,75%">
<frame src="left.html" name="left" scrolling ="no" frameborder ="0">
<frame src="right.html" name="right" scrolling ="auto" frameborder ="0">
</frameset>
</frameset>
</html>
Top.html:
<html>
<body bgcolor="pink">
<br><br>
<marquee><h1 align=”center”><b><u>ONLINE
BOOK STORAGE</u></b></h1></marquee>
</body>
</html>
Right.html:
<html>
<body>
<br><br><br><br><br>
<h2 align="center">
<b><p> welcome to online book storage. Press login if you are
having id otherwise press registration.
</p></b></h2>
</body></html>
Left.html:
<html>
<body bgcolor="pink">
<h3>
<ul>
<li><a href="login.html" target="right"><font color="black">LOGIN</font></a></li><br><br>
<li><a href="profile.html" target="right"><font
color="black">USERPROFILE</font></a></li><br><br>
<li><a href="catalog.html" target="right"><font color="black">BOOKS CATALOG
</font></a></li><br><br><li><a href="scart.html" target="right"><font
color="black"> SHOPPINGCART</font></a></li><br><br>
<li><a href="payment.html" target="right"><font
color="black">PAYMENT</font></a></li><br><br>
<br><br>
</ul>
</body>
</html>
Registration and user Login
Login.html:
<html>
<body bgcolor="pink"><br><br><br>
<script
language="javascript">
function validate()
{var flag=1; if(document.myform.id.value==""||document.myform.pwd.value=="")
{ alert("LoginId and Password must be
filled") flag=0;
}if(flag==1)
{ alert("VALID INPUT");
window.open("catalog.html","right");
} else
{ alert("INVALID INPUT");
//document.myform.focus();
}}
</script>
<form name="myform">
<div align="center"><pre>LOGIN ID:<input type="text"
name="id"><br> PASSWORD:<input type="password"
name="pwd"><br><br></pre>
<input type="button" value="ok" onClick="validate()">
<input type="reset" value="clear" ></div>
</form>
</body>
</html>
User profile
page
Profile.html:
<html>
<body bgcolor="pink"><br><br>
<script
type="text/javascript">
function validate()
{
var flag=1;
if(document.myform.name.value==""||document.myform.addr.value==""|
|
document.myform.phno.value==""||document.myform.id.value==""||document.myform.p
wd.valu e=="")
{
alert("Enter all the
details"); flag=0;
}
var
str=document.myform.phno.value;
var x=new RegExp("\\d","g");
if(!(str.match(x)))
{
if(!(str.length==10))
flag=0;
}
var str1=document.myform.id.value;
var x1=new RegExp("^[A-Z][a-zA-
Z]+$","g"); if(!(str1.match(x1)))
{
flag=0;
alert("Invalid UserID");
}
var str1=document.myform.pwd.value;
var x1=new RegExp("^[A-Z][a-zA-
Z]+$","g"); if(!(str1.match(x1)))
{
flag=0;
alert("Invalid password");
}
if(flag==1)
{
alert("VALID INPUT");
window.self.location.href="login.html";
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="type"
name="addr"><br>
Books
catalog:
Scart.html:
<html>
<body bgcolor="pink"><br><br><br>
<script
language="javascript">
function validate()
{
var flag=1;
if(document.myform.title.value=="")
{
flag=0;
}
str=document.myform.title.value;
if(str=="c"||str=="C")
{
document.myform.t1.value="
C";
document.myform.t2.value=4
44;
}
else if(str=="jsp"||str=="JSP")
{
document.myform.t1.value="JS
P";
document.myform.t2.value=555
;
}else
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform" action="payment.html" target="right">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title"><br>
</pre><br><br>
Book Title: <input type="text" name="t1"
disabled> Book Cost: <input type="text"
name="t2" disabled>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">
<input type="reset" value="clear">
<input type="submit" value="Purchase">
</form>
</body>
</html>
Shopping
cart:
Catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<script
language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||document.myform.title.value==""||document.myform.n
o.valu e==""||
document.myform.cost.value=="")
{
flag=0;
}
str=document.myform.title.value;
var str1=document.myform.cost.value;
if(!((str=="c"&& str1==444) || (str=="jsp" && str1==555)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform" action="scart.html" target="right">
<div align="center"><pre>LOGIN ID :<input type="text"
name="id"><br> TITLE :<input type="text" name="title"><br>
NO.OF BOOKS :<input type="text"
name="no"><br> COST OF BOOK :<input
type="text"name="cost"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">
<input type="reset" value="clear">
</form>
</body>
</html>
Payment by credit
card Payment.html:
<html>
<body bgcolor="pink"><br><br><br>
<script
language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""|| document.myform.pwd.value==""||
document.myform.amount.value==""||
document.myform.num.value=="")
{
flag=0;
}
var
str=document.myform.amount.value;
var x=new RegExp("\\d","g");
if(!(str.match(x)))
{ flag=0;
}
Var
str1=document.myform.num.value;
var x1=new RegExp("\\d","g");
if(!(str.match(x1)))
{ flag=0;
}i
f(flag==1
)
{ alert("VALID INPUT");
window.self.location.href="order.html";
} else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password"
name="pwd"><br> AMOUNT :<input type="text"
name="amount"><br>
CREDITCARDNUMBER :<input type="PASSWORD" name="num"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="button" value="ok" onClick="validate()">
<input type="reset" value="clear" >
</form>
</body>
</html>
Order
Conformation
Order.html:
<html>
<head><title>order conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>AMAZON</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>
</body>
</html>
OUTPUT:
Main.html
Login.html:
Catalog.html:
Scart.html:
Payment.html:
Order.html
RESULT :
Thus the Registration, user login, user profile and payment by credit card
pages are validation using JavaScript.
EX.NO :4A Write programs in Java using Servlets:
DATE: a. To invoke servlets from HTML forms
AIM:
To create a java server side application using servlet and invoke it from a HTML client .
ALGORITHM:
1. Create a client using HTML It get the username and password from the user. When
you submit the form it invoke the servlet.
2. Create a server using servlet It receive the data from client and display the result to the
client.
3. Deploy the servlet in to the server.
4. Run the client and server application . When you submit the client form it invoke the
servlet and the server display the result to the client.
PROGRAM CODING:
<HTML>
<HEAD>
<TITLE> Logic Form </TITLE>
</HEAD>
<BODY>
<FORM name="logicform" method="get"
action="http://localhost:7001\myapps\FirstServlet">
<CENTER><TABLE>
<TR><TD>USER NAME:</TD><TD><INPUT name="name" type="text"></TD></TR>
<TR><TD>PASSWORD:</TD><TD><INPUT name="pwd" type="password"></TD></TR>
</TABLE><BR>
<INPUT name="submit" value="submit" type="submit">
</CENTER>
</FORM>
</BODY>
</HTML>
/* First Servlet */
import
javax.servlet.*;
import
javax.servlet.http.*;
import java.io.*;
public class FirstServlet extends HttpServlet
{
RESULT :
Thus the servlet has been deployed and invoked from the HTML client.
Ex.No:4 (b) b. Session tracking using hidden form fields and
DATE: Session tracking for a hit count
AIM
To create a servlet program for Session tracking using hidden form fields
ALGORITHM:
● Create a graphical user interface for allowing the user to enter the data.
● Create the first servlet which will receive these valued and will store
them in hiddenformfiles.Then these valued are transferred to the
second servlet
● The second servlet will display these values with greeting message
● Now compile both the java sevlets by using the following command
⮚ Javac Servlet1.java
⮚ Javac Servlet2.java
● Then edit web.xml file
● Open the web browser and invoke the HTML document created in Step 1.
SOURCE CODE:
GUI.html
<html>
<head>
<title>Session tracking using hidden form field</title>
</head>
<body>
<form method="get"
action="http://localhost:8084/WebApplication2/Servlet1"> Enter
name:<input type="text" name="userName"/><br/>
Enter City:<input type="text" name="userCity"/><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>Servlet
1.java import
java.io.*; import
java.net.*;
import javax.servlet.*;
import
javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
{
Try
{
response.setContentType("text/ht
ml"); PrintWriter
out=response.getWriter();
String
n=request.getParameter("userName");
String
c=request.getParameter("userCity");
out.print("<form
action='http://localhost/WebApplication/Servlet2'>");
out.print("<input type='hidden'name='userName'
value='"+n+"'>"); out.print("<input type='hidden'name='userCity'
value='"+c+"'>"); out.print("<input type='submit' value='just click
here'>"); out.print("</form>");
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Servlet2.java
import java.io.*;
import
java.net.*;
import javax.servlet.*;
import
javax.servlet.http.*;
public class Servlet2 extends HttpServlet {
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
{
try
{
response.setContentType("text/html)");
PrintWriter out=response.getWriter();
String
n=request.getParameter("userName");
out.println("Hello"+n);
String
c=request.getParameter("userCity");
out.println("you are from"+c);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}}
OUTPUT:
RESULT:
Thus session tracking using hidden form fields and session tracking hit count has
been developed and validate successfully.
Ex. No: 5 Write programs in Java to create three-tier applications using servlets for
DATE: conducting online examination for displaying student mark list.
Assume that student information is available in a database which has been
stored in a database server.
AIM:
To write an online Examination using Servlet three tier architecture
ALGORITHM:
● Create a user interface form for getting Seat number and Name
● Create jsp file which calculates the total marks on the server
● Place the jsp file …\Tomcat 5.5\webapps\Examples\WEB-INF\jsp\ folder.
● Create a data base to store the existing user details. If a new login has to be
● created, then display the corresponding page.
● Create a table in MS ACCESS or ORACLE that contains three fields .
● Create a DSN to map the Microsoft Access Driver using ODBC in Administrative Tools.
● Import java.sql.* in the java program to execute the SQL queries.
● Load the database driver by using Class.forName().
● Create a Connection and Statement Object.
● Establish a Database Connection with DSN using DriverManager.getConnection.
● Execute the query using executeQuery() and that gets stored in a Resultset.
● Until there are records in table specified get the fields in each record
one by one and display onto the screen.
● Close the Statement and Connection Object.
● Display the results
SOURCE CODE:
<!Save as onlineexam.html>
<html>
<head><title>Online Examination</title>
<script
language="javascript">
function
validation(Form_obj)
{
if(Form_obj.Seat_no.value.length==0)
{
alert("Please,fill up the Seat
Number");
Form_obj.Seat_no.focus();
return false;
}
if(Form_obj.Name.value.length==0)
{
alert("Please,fill up the
Name");
Form_obj.Name.focus();
return false;
}
return true;
}
</script></head>
<body bgcolor=lightgreen>
<center>
<h1>OnLine Examination</h1>
</center>
<form action="StudentServlet3" method="post"
name="entry" onSubmit="return validation(this)">
<input type="hidden" value="list" name="action">
<table>
<tr><td><h3>Seat Number:</h3></td>
<td><input type="text" name="Seat_no"></td></tr>
<tr><td><h3>Name:</h3></td>
<td><input type="text" name="Name" size="50"></td></tr><hr/>
<tr><td><b>Total Marks:10(Each question carries equal marks) </b></td>
<td></td><td></td><td></td><td><b>Time: 15 Min.</b></td></tr>
</table><hr/>
<b>1. Apache is an open source web server</b><br/>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<br/><b>2. In Modern PC there is no cache memory.</b><br/>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<br/><b>3. Tim-Berner Lee is the originator of Java.</b><br/>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False<br>
<br/><b>4.JPG is not a video file extension.</b><br/>
<input type="radio" name="group4" value="True">True
<input type="radio" name="group4" value="False">False<br>
<br/><b>5. HTTP is a statefull protocol</b><br/>
<input type="radio" name="group5" value="True">True
<input type="radio" name="group5" value="False">False<br>
<hr/><center>
<input type = "submit" value="Submit">
<input type = "reset" value="Clear"><br><br>
</center></form></body></html>
StudentServlet.jav
a) import java.sql.*;
import java.io.*;
import java.util.*;
import
javax.servlet.*;
import javax.servlet.http.*;
out.println("<h1>Thanks</h1>\n
"); out.println("</table>");
out.println("</center>");
out.println("</body></html>");
}}}
OUTPUT:
RESULT:
Thus the development of program in java to create three tier application using
servlet has been developed successfull.
EX.NO:06 Install TOMCAT web server. Convert the static web pages of programs
DATE: into dynamic web pages using servlets (or JSP) and cookies.
Hint: Users information (user id, password, credit card number) would
be stored in web.xml. Each user should have a separate Shopping Cart.
AIM:
Install TOMCAT web server. Convert the static web pages of programs into
dynamic web pages using servlets (or JSP) and cookies
PROCEDURE:
Step 3:
The process of installing Tomcat 6.0 begins here from now. It takes various
steps for installingand configuring the Tomcat 6.0
For Windows OS, Tomcat comes in two forms: .zip file and .exe file (the Windows
installer file).Here we are exploring the installation process by using the .exe file. First
unpack the zipped fileand simply execute the '.exe' file.
A Welcome screen shot appears that shows the beginning of installation process.
Just click on the 'Next' button to proceed the installation process.
Steps 4:
A screen of 'License Agreement' displays.
Step
6:
A screen shot of 'Configuration Options' displays on the screen. Choose the
location for the Tomcat files as per your convenience. You can also opt the default
Location
The port number will be your choice on which you want to run the tomcat server. The
port number 8080 is the default port value for tomcat server to proceed the HTTP
requests. The usercan also change the 'port number' after completing the process of
installation; for this, users haveto follow the following tips.
Go to the specified location as " Tomcat 6.0 \conf \server.xml ". Within the
server.xml file choose "Connector" tag and change the port number.
Now, click on the 'Next' button to further proceed the installation process.
Step 7:
A Window of Java Virtual Machine displays on the screen
This window asks for the location of the installed Java Virtual Machine. Browse the
location ofthe JRE folder and click on the Install button. This will install the Apache
tomcat at the specifiedlocation.
Step 8:
A processing window of installing displays on the screen.
To get the information about installer click on the "Show details" button
Step 9:
A screen shot of 'Tomcat Completion' displays on the screen.
Click on the 'Finish'
button. Step 10:
A window of Apache Service Manager appears with displaying the running process.
Step 11:
After completing the installation process, the Apache Tomcat Manager appears on
the toolbar panel like shown in the below picture.
PROCEDURE:
1. First install the tomcat into the system.
2. Then make a sub directory(eg., books) in the \tomcat\webapps.
3. Under books create WEB-INF directory and also place week1 programs in
this books directory only.
4. After this start tomcat by giving the following command at the instll_dir>tomcat>bin
5. Catalina.bat run
6. At the I.E(web browser) give the url as http://localhost:8080/ books /main.html
7. Port no 8080 is assigned for the tomcat.
Screen shot:
RESULT:
Thus tomcat web server is installed successfully and Convert the static web pages of
programs into dynamic web pages using servlets (or JSP) and cookies.
EX.NO:07 Redo the previous task using JSP by converting the static web pages
DATE: into dynamic web pages. Create a database with user information
and
books information. The books catalogue should be dynamically
loaded
from the database.
AIM:
Develop static pages (using only HTML) of an online Book store. The pages
should resemble: www.amazon.com. The website should consist the following pages.
● Home page
● Registration and user Login
● User profile page
● Books catalog
● Shopping cart
● Payment by credit card Order Conformation
PROCEDURE:
Home page
Main.html:
<html>
<head>
<title>
Amazon</title
>
</head>
<body bgcolor="cyan"><center>
<strong><h1>Welcome to AMAZON</h1></strong>
<form method="post" action="login.html" target=_blank >
<h4>for books</h4><input type="submit" value="click here">
</form>
</center>
</body>
</html>
Registration and user Login
Login.html:
<html>
<head>
<title>
login page</title>
</head>
<body bgcolor="cyan"><center>
<strong><h1> AMAZON </h1></strong></center>
<right>
<table align="right">
<tr>
<td><h4>user name</td>
<td><input type="text" ></td>
<td></td>
</tr>
<tr>
<td><h4>password</td>
<td><input type="password"></td>
<td></td>
</tr>
<tr>
<td>
<form method="post" action="catalog.html" >
<input type="submit" value="submit" >
</form>
</td>
<td>
<form method="post" action="userpro.html" >
<input type="submit"
value="register" >
<input type="reset" value="reset"></form></td>
</tr>
</table>
</body>
</html>
</h4>
<center>
<b>for buy one of these books
<br>
</b><input type="submit" value="click here">
</center>
</form>
</body>
</html>
Shopping
cart Shopping.html:
<html>
<head><title>shopping cart</title>
</head>
<body bgcolor="cyan">
<center><h1>
Shopping Cart</h1></center>
<br><br><br><br><br>
<table align="center">
<tr>
<td>Text Books</td>
<td><select>
<optgroup label="select the book">
<option value="C&Ds">C&Ds
<option value="Ads">Ads
<option value="Java">Java
<option value="Oracle">Oracle
<option value="Ms SQL Server">Ms SQL Server
<option value="MySql">MySql
</optgroup>
</select>
</td></tr>
<tr>
<td>
Quantity</td
>
<td>
<input type="text" id="q">
</td></tr><tr>
<td></td>
<td>
<form method=post action="payment.html">
<input type="submit" value=ok />
</form>
</td></tr>
</table>
<center>
<pre>Cost of one book is"500" + shipping "100"</pre>
</center>
<body>
</html>
Payment by credit
card Payment.html:
<html>
<head><title>payment</title></head>
<body bgcolor="cyan">
<center><h1>Payment By Credit Card</h1></center>
<form method=post action="ordrconform.html">
<br><br><br><br><br>
<table align="center">
<tr>
<td>
<h4>Total Amount</h4></td>
<td><input type="text">
</td>
</tr>
<tr>
<td><h4>Credit Card Number</td>
<td><input type="text"></td>
</tr>
<tr>
<td>
</td>
<td><input type="submit" value=OK>
</td>
</tr>
</table>
</form></body>
</html>
Order
Conformation
Ordrconform:
<html>
<head><title>order conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>BOOK SHOPPING</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>
</body></html>
OUTPUT:
Main.html:
Login.html:
Catalog.html:
Userpro.html
Shooping.html:
Ordrconform.html:
RESULT:
Thus the books catalogue should be dynamically loaded from the database.
Ex.No:8 Create and save an XML document at the server, which contains 10 users
DATE: Information. Write a Program, which takes user Id as an input and returns
the User details by taking the user information from the XML document.
Aim:
To Create and save an XML document at the server, this contains 10 users
Information. And takes user Id as an input and returns the User details by
taking the user information from the XML document.
Algorithm:
Programdata.xml
<?xml version="1.0"?>
<userdata>
<user1>
<rollno>561</rollno>
<name> chandu</name>
<phno>9989891510</phno>
<address>chennai</address>
</user1>
<user2>
<rollno>540</rollno>
<name>karteek</name>
<phno>9701443556</phno>
<address>chennai</address>
</user2>
<user3>
<rollno>525</rollno>
<name>giri</name>
<phno>9897895301</phno>
<address>trichy</address>
</user3>
<user4>
<rollno>526</rollno>
<name>gopi</name>
<phno>9999789540</phno>
<address>salem</address>
</user4>
<user5>
<rollno>513</rollno>
<name>manoj</name>
<phno>9989233331</phno>
<address>madurai</address>
</user5>
<user6>
<rollno>514</rollno>
<name>balaji</name>
<phno>9999789560</phno>
<address>trichy</address>
</user6>
<user7>
<rollno>567</rollno>
<name>kiran</name>
<phno>9999178957</phno>
<address>thanjavur</address>
</user7>
<user8>
<rollno>518</rollno>
<name>sekhar</name>
<phno>789580</phno>
<address>neyveli</address>
</user8>
<user9>
<rollno>517</rollno>
<name>chaitu</name>
<phno>789590</phno>
<address>coimbatore</address>
</user9>
<user10>
<rollno>595</rollno>
<name>sravan</name>
<phno>9000789500</phno>
<address>cuddalore</address>
</user10>
</userdata>
Information Retrieval
data.html
<html>
<head>
<title>user profile example</title>
</head>
<body>
<script type="text/JavaScript">
var xmldoc=new ActiveXObject("Microsoft.XMLDOM");xmldoc.load("data.xml");
var ele=xmldoc.documentElement;
var y=window.prompt("eneter user num",1);
var node=ele.childNodes.item(y-1);
for(var i=0;i<node.childNodes.length;i++)
{
var child=node.childNodes.item(i);
var val=child.firstChild;
document.write("<h2>"+child.nodeName+":"+val.nodeValue);
}
</script>
</body>
</html>
EXECUTION:
Step 1: Save xml file with file extension as .xml and html file with file extensionas
.html inone
directory.
OUTPUT:
RESULT:
Thus the program, which takes user Id as an input and returns the User details by
taking the user information from the XML document is executed successfully.
EX NO : 9(a) Validate the form using PHP regular expression.
DATE:
AIM:
To validate the form using PHP regular expression
ALGORITHM:
SOURCE CODE:
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website
= ""; if ($_SERVER["REQUEST_METHOD"] ==
"POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and
whitespace if (!preg_match("/^[a-zA-Z
]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
{
$websiteErr = "Invalid URL";
}}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data =
htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text"
name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br
>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your
Input:</h2>"; echo $name;
echo
"<br>";
echo
$email;
echo "<br>";
echo $website;
echo "<br>";
echo
$comment;
echo "<br>";
echo $gender;
?></body>
</html>
OUTPUT:
RESULT
Thus the form created using PHP regular expression was created successfully.
EX.NO:09(b) PHP STORES A FORM DATA INTO DATABASE.
DATE:
AIM:
To create a form using PHP and store the data into MYSQL Database.
ALGORITHM:
● Create a client using PHP. It get the username and password from the user. When
you submit the form using Php.
● Create a server using servlet It receive the data from client and display the result to the
client.
● Deploy the servlet in to the server.
● Run the client and server application . When you submit the client form it invoke the
servlet and the server display the result to the client.
INDEX.PHP
<html>
<body>
<h1>A small example page to insert some data in to the MySQL database using PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname"
/><br><br>Lastname: <input type="text" name="lname"
/><br><br>
<input type="submit" />
</form>
</body>
</html>
OUTPUT:
2. To connect to MySQL :-
Before you can access your MySQL database, you must contact the system
administrators to request an account. Once the administrators have notified you
that your account has been created, you may connect using the following
instructions.
3. Now enter the new table name “nametable” , number of fields in that table as “2”
and hit GO button.
4. Enter the field names to be “firstname” and “lastname” and keep the length
attributes to be “20” for both the fields. The default type of VARCHAR is kept
as it is.
5. After the table fields are being created, the following screen will be shown to you
6. Now we need to make a connection to the MySQL database and then send this entered
data from our textboxes. For that we create a new PHP page “insert.php” and use the
following connection strings to the connection variable $con
After making a connection, a SQL query is being written to enter this data in to the
MySQL database being created (“nametable”)
To tell the user that the data is being entered we set the echo to "1 record added"
INSERT.PHP
<html>
<body>
<?php
$con =
mysql_connect("mysql.cis.ksu.edu","cis_id","password"); if
(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cis_id", $con);
$sql="INSERT INTO nametable (fname,
lname)VALUES('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
7. Now type the index page URL in your browser and enter some data in to the
textboxes. Submit the Query.
RESULT:
Thus a form is created using PHP and store the data into MYSQL Database
successfully.
EX NO : 10 WRITE A WEB SERVICE FOR FINDING WHAT PEOPLE THINK BY
DATE: ASKING 500 PEOPLE‘S OPINION FOR ANY CONSUMER PRODUCT
AIM:
To Write a web service for finding what people think by asking 500 people‘s
opinion for any consumer product
ALGORITHM:
<div class="imagebg"></div>
<h2>Feedback</h2>
<p>
</p>
<div class="row">
<p><label class="radio-inline">
<input type="radio" name="experience" id="radio_experience" value="bad" >Bad </label>
<label class="radio-inline">
</label><label class="radio-inline">
</label></p>
</div></div>
<div class="row">
<label for="comments">Comments:</label>
</div></div>
<div class="row">
<label for="email">Email:</label>
</div>
</div>
</form>
<div id="success_message" style="width:100%; height:100%; display:none; ">
</div>
<h3>Error</h3>
</div></div></div>
CSS Styling
<link rel="stylesheet"
href="form.css" >jQuery Form
submission handling
<script>
$(function()
{
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_messageul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label =
$btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
} });
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
$.ajax({type: "POST", url: 'handler.php',data: $form.serialize(), success:
after_form_submitted, dataType: 'json'});
});
});
</script>
Form Validations
required></textarea>
?phpini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once
'./vendor/autoload.php'; use
FormGuide\Handlx\FormHandler;
OUTPUT:
RESULT:
Thus web service for finding what people think by asking 500 people‘s opinion
for any consumer product is executed and output is verified successfully.
EX NO:11 WRITE A SPRING MVC APPLICATION. THE APPLICATION
DATE: SHOULD HANDLE FORM VALIDATION, FILE UPLOAD, SESSION
TRACKING.
AIM:
To write a spring MVC application. The application should handle form
validation, file upload, session tracking.
ALGORITHM:
Step 1: Start the program
Step 2: Create pom.xml with below dependencies
Step 3: Create web.xml file with Dispatcher servlet
Step 4: Create the spring configuration file
Add the multipartResolver bean in the configuration file so that spring can
handle multipart requests like file upload.
Step 5: Create the view page
uploadFile.jsp
fileUploadSuccess.jsp
fileUploadFailure.jsp
Step 6: Create the controller
Step 7: Create a custom validator class
Step 8: Create the messages.properties file under WEB-INF directory
Step 9: Session tracking the file using the URL in spring.
Step 10:Deploy the application.
Step 11: Display the output.
Step 12: Stop the program.
PROGRAM:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Spring</groupId>
<artifactId>SpringFileUploadValidation</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>FileUpload Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>4.2.0.RELEASE</org.springframework.version
>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>FileUpload</display-name>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolve
r">
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessa
geSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
</beans>
class="org.springframework.web.servlet.view.InternalResourceViewResolver
">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartReso
lver">
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMes
sageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
</beans>
<html>
<body>
<h2>Spring MVC file upload Success</h2>
FileName : <strong> ${fileName} </strong> - Uploaded Successful.
</body>
</html>
<html>
<body>
<h2>Spring MVC file upload failure</h2>
FileName : <strong> ${fileName} </strong> - Upload error due to some
technical issues
Please try again later.
</body>
</html>
package com.kb.controllers;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.kb.model.FileUploadModel;
import com.kb.validator.CustomFileValidator;
@Controller
public class FileUploadController implements ServletContextAware {
private ServletContextservletContext;
@Autowired
CustomFileValidatorcustomFileValidator;
@RequestMapping(value = "/uploadFile", method = RequestMethod.GET)
public String uploadFileFormDisplay(Model model) {
model.addAttribute("fileUploadModel", new FileUploadModel());
return "uploadFile";
}
package com.kb.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;
import com.kb.model.FileUploadModel;
@Component
public class CustomFileValidator implements Validator{
public static final String PNG_MIME_TYPE="image/png";
public static final long TEN_MB_IN_BYTES = 10485760;
@Override
public boolean supports(Class<?>clazz) {
return FileUploadModel.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
FileUploadModelfileUploadModel = (FileUploadModel)target;
MultipartFile file = fileUploadModel.getFile();
if(file.isEmpty()){
errors.rejectValue("file", "upload.file.required");
}
else if(!PNG_MIME_TYPE.equalsIgnoreCase(file.getContentType())){
errors.rejectValue("file", "upload.invalid.file.type");
}
else if(file.getSize() > TEN_MB_IN_BYTES){
errors.rejectValue("file", "upload.exceeded.file.size");
}
}
}
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>EduSprMvc</groupId>
<artifactId>EduSprMvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>3.1.1.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- CGLIB is required to process @Configuration classes -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Servlet API, JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Click on upload
Session
RESULT:
Thus the spring MVC application should handle form validation, file
upload, session tracking program was successfully executed.
88