Sunday, 5 March 2017

BCA 5th sem /053/Solved Assignment/Web Programming/2016-2017 New

1. (covers Block 1)

(a)List important technologies of Web 2.0. Explain the term Mashups in the context of Web 2.0 with the help of an example. List the process of creating a Mashup.

Ans(a) Web 2.0 is a term that describes the changing trends in the use of World Wide Web technology and Web design that aim to enhance creativity, secure information sharing, increase collaboration, and improve the functionality of the Web as we know it (Web 1.0). These have led to the development and evolution of Web-based communities and hosted services, such as social-networking sites (i.e. Facebook, MySpace), video sharing sites (i.e. YouTube), wikis, blogs (onlinecode) etc. 
Web 2.0 Websites typically include some of the following features/techniques:
 • Search: the ease of finding information through keyword searching. 
• Links: guides to important pieces of information. The best pages are the most frequently linked to. 
• Authoring: the ability to create constantly updating content that is co-created by users. In wikis, the content is iterative in the sense that the people undo and redo each other’s work. In blogs, it is cumulative in that posts and comments of individuals are accumulated over time.
 • Tags: categorization of content by creating tags that are simple, one-word descriptions to facilitate searching and avoid having to fit into rigid, pre-made categories. 
• Extensions: automation of pattern matching for customization by using algorithms (i.e. Amazon.com recommendations). 
• Signals: the use of RSS (Real Simple Syndication) technology to create a subscription model which notifies users of any content changes. 

mashup (computer industry jargon), in web development, is a web page, or web application, that uses content from more than one source to create a single new service displayed in a single graphical interface. For example, a user could combine the addresses and photographs of their library branches with a Google map to create a map mashup.The term implies easy, fast integration, frequently using open application programming interfaces (open API) and data sources to produce enriched results that were not necessarily the original reason for producing the raw source data. The term mashup originally comes from British - West Indies slang meaning to be intoxicated, or as a description for something or someone not functioning as intended. In recent English parlance it can refer to music, where people seamlessly combine audio from one song with the vocal track from another—thereby mashing them together to create something new.

There are many types of mashup, such as business mashups, consumer mashups, and data mashups. The most common type of mashup is the consumer mashup, aimed at the general public.
  • Business (or enterprisemashups define applications that combine their own resources, application and data, with other external Web services. They focus data into a single presentation and allow for collaborative action among businesses and developers. This works well for an agile development project, which requires collaboration between the developers and customer (or customer proxy, typically a product manager) for defining and implementing the business requirements. Enterprise mashups are secure, visually rich Web applications that expose actionable information from diverse internal and external information sources.
  • Consumer mashups combine data from multiple public sources in the browser and organize it through a simple browser user interface. (e.g.: Wikipediavision combines Google Map and a Wikipedia API)
  • Data mashups, opposite to the consumer mashups, combine similar types of media and information from multiple sources into a single representation. The combination of all these resources create a new and distinct Web service that was not originally provided by either source.

Four easy steps to making your first mashup

So here's how to get going. It probably won't make you a masterpiece, but it will match the BPMs all up nicely for you, give you an easy way to experiment, and cut out all of the mystery. This should give you the confidence to then take mashup creation further.
  1. Find a tune that you have an acappella, a full vocal version and an instrumental of - If you haven't got one, go and look for one. It must all be the same mix - so for instance, an original version, an original instrumental, and then the accapella. (It's not as good having the instrumental of one remix and the vocal of another.) If you're just missing the acappella, try the excellent acapellas4u.co.uk
  2. Set the BPM of the acappella to the same as that of the instrumental version - Unfortunately you can't just press "sync", as your DJ software probably won't be able to guess the BPM of the acappella, as it has no beat. But because you have the instrumental version (and the vocal version), you already know the BPM of the acappella - it's the same as those two! So manually set its BPM to that
  3. Recreate the vocal version of the tune by dropping the acappella over the instrumental - This is a step that I've included to help you to get used to the process. As you now have an acappella at the right BPM, you can start the instrumental playing on one of your DJ software's decks, then at the right time, start the acappella playing. (Not sure where it starts? Refer to the vocal version - that's why we've got it.) Now you have effectively the same track as the full vocal version, but composed of a separate vocal and instrumental. Feel free to mess around with your EQs, crossfader, filters etc to "remix" the track on the fly
  4. Replace the instrumental with a different song's instrumental - When you've had enough of that practice run, stop everything, get the acappella back to the beginning, and on the deck that you have the instrumental loaded on, load the instrumental of a different song. Match its BPM to the BPM of the acappella - hitting "sync" will do it. (You know the BPM of the acappella is correct, because you set it earlier.) Now start the instrumental playing, and wherever you feel it is right to do so (hint: count in eights), start the accapella playing. Use your nudge controls to get it exactly in time if you need to. There you go - your first properly beatsynced mashup!

(b) Create a simple Registration form consisting of the following information – First and Last Name, date of birth (it should be validated), email ID (it should be validated), Employment status (Yes or No), Locality (to be selected from drop down list of Metropolitan, Urban, Semi-Urban, Rural), proposed user name and password, and a SUBMIT button. You must perform validations using JavaScript.

Ans(b)
<html>
<head>
<title>anyform</title>
<script language="javascript">
function validation()
{
if(document.getElementById("fname").value=="")
{
alert("Please enter valid name");
document.getElementById("fname").focus();
return false;
}
if(document.getElementById("lname").value=="")
{
alert("Please enter valid name");
document.getElementById("lname").focus();
return false;
}
if(document.getElementById("emid").value=="")
{
alert("Please enter E-mail id ");
document.getElementById("emid").focus();
return false;
}
return true;
}
</script>
</head>
<body>
<fieldset>
<legend><h1>REGISTRATION FORM</h1><legend>
<form name="anyform"method="post"action="profilehtml"onsubmit="return validation();">
<table border="2px"style="width:400px;color:blue;font-size:10px;text-align:centre">
<tr>
<td>FIRST NAME</td>
<td><input type="text"name="first name" id="fname"/></td>
</tr>
<tr>
<td>LAST NAME</td>
<td><input type="text"name="last name" id="lname"/></td>
</tr>
<tr>
<td>DATE OF BIRTH</td>
</tr>
<td>
<Date>
<select>
<option>dd</option>
<option value="0">01</option>
<option value="1">02</option>
<option value="2">03</option>
<option value="3">04</option>
<option value="4">05</option>
</select>
<Month>
<select>
<option >mm</option>
<option value="0">01</option>
<option value="1">02</option>
<option value="2">03</option>
<option value="3">04</option>
<option value="4">05</option>
</select>
<Year>
<select>
<option >yyyy</option>
<option value="0">1990</option>
<option value="1">1991</option>
<option value="2">1992</option>
<option value="3">1993</option>
<option value="4">1994</option>
</select>
</td>
</tr>
<tr>
<td>email ID</td>
<td><input type="text"name="email ID" id="emid"/></td>
</tr>
<tr>
<td>EMPLOYMENT STATUS</td>
<td><input type="radio" name="Employment Status" value="YES" />YES||
 <input type="radio" name="Employment Status" value="NO" />NO</td>
</tr>
<tr>
<td>LOCALITY</td>
<td>
<select>
<option value="0">Metropolitan</option>
<option value="1">Urban</option>
<option value="2">Semi-Urban</option>
<option value="3">Rural</option>
</select>
</td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="password" name="PASSWORD"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name=" submit" value="submit" onclick="validation()" /></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>

(c) Create a simple web page using HTML consisting of two paragraphs about your School. Both the paragraphs should be created in different divisions. You must also create an external CSS file which ensures the following: 

(i) The first paragraph should use font Arial. The background of this paragraph should be light yellow and text colour green. 

(ii) The second paragraph should have light green background and text colour as blue. 

(iii) Both the paragraphs should have one heading which should have same format in both the paragraphs.

 Also show how CSS can change the display format.

Ans(c)
<!DOCTYPEhtml>
<html>
 <head>
 <title>bca:bcs53Q1(c)</title>
 <style>
 .format{color:#ff0000;background-color:#99ffcc;}
 #para1{background-color:yellow;color:green}
 #para2{background-color:lightgreen;color:blue}
 </style>
 </head>
 <body>
 <center><h2>ABOUT SCHOOL</h2></center>
 <div id="para1">
 A school is an institution designed to provide learning spaces and learning environments for the teaching of
students (or "pupils")
 under the direction of teachers. Most countries have systems of formal education, which is commonly
compulsory.[citation needed] In
 these systems, students progress through a series of schools. The names for these schools vary by country
(discussed in the Regional
 section below) but generally include primary school for young children and secondary school for teenagers who
have completed primary
 education. An institution where higher education is taught, is commonly called a university college or
university.

 </div>
 <div id="para2">
 In addition to these core schools, students in a given country may also attend schools before and after primary
and secondary education.
 Kindergarten or pre-school provide some schooling to very young children (typically ages 3–5). University,
vocational school, college or
 seminary may be available after secondary school. A school may also be dedicated to one particular field, such
as a school of economics
 or a school of dance. Alternative schools may provide non-traditional curriculum and methods.
 There are also non-government schools, called private schools.
 </div>
 </body>
</html>


(d) A Library maintains detailed record of its books using XML. Every book has a unique book procurement number. A book has a Title, one or more authors, a publisher, year of publication, price, and an optional abstract. Create an XML documents containing information of five such Books. Also create the DTD for the XML Books document.

Ans(d)  The element library defines all elements that particular reference types might want to store in a database. This is reasonably easy for a database programmer to translate into a database schema which can hold all the required information. But how does RelaxNG help the reference data author to fill in the required data? Let's look at some examples. Most reference types require the publication element (the element that holds monographic data). The following definition in rbib-library.rnc defines the superset of all elements that might ever end up in the publication element

publication =
element publication { pubtitle, title, author+, edition, volume, refdate,
publisher, publication-typespecific, serial }
Some "elements" like publication-typespecific and refdate are named patterns which in turn
consist of several XML elements, but don't let yourself get distracted by this. Now let's
have a look at two reference types that use the publication element in different ways:
book-publication = element publication { pubtitle, title, author+,
shortrefdate, edition?, volume?, publisher?, serial? }
datafile-publication = element publication { pubtitle }
XML Document
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
 <book category="WIN">
 <title lang="en">Learning .NEt Windows</title>
 <author>Erik T. Ray</author>
 <publisher>R.Puteam</publisher>
 <year>2003</year>
 <price>399.95</price>
 </book>
 <book category="COOKING">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <publisher>R.Puteam</publisher>
 <year>2005</year>
 <price>330.00</price>
</book>
 <book category="CHILDREN">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <publisher>R.Puteam</publisher>
 <year>2005</year>
 <price>829.99</price>
 </book>
 <book category="WEB">
 <title lang="en">XQuery Kick Start</title>
 <author>James McGovern</author>
 <author>Per Bothner</author>
 <author>Kurt Cagle</author>
 <author>James Linn</author>
 <author>Vaidyanathan Nagarajan</author>
 <publisher>R.Puteam</publisher>
 <year>2003</year>
 <price>249.99</price>
 </book>
 <book category="WEB">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>
 <publisher>R.Puteam</publisher>
 <year>2003</year>
 <price>397.95</price>
 </book>
</bookstore>

DTD

<!DOCTYPE bookstore
[
 <!ELEMENT bookstore (title,author,year,price)>
 <!ELEMENT title (#PCDATA)>
 <!ELEMENT author (#PCDATA)>
 <!ELEMENT year (#PCDATA)>
 <!ELEMENT price (#PCDATA)>
]>

(e) Write a script using JavaScript that changes the content of a title – First Assignment to the title – Ready for Assignment. The script should change the colour of the content Ready for Assignment after every 4 seconds. Make suitable assumptions, if any.

Ans(e)
<html>
<head>
<script language="JavaScript">
var str="First Assignment";
var res=str.replace("First","Ready For");
var colors=new Array(6);
colors[0]="#0000FF"; colors[1]="#FF0000"; colors[2]="#006600";
colors[3]="#FFCC00";colors[4]="#00FFFF"; colors[5]="#000000";
var i=1;
</script>
</head>
<script language="JavaScript">
function changecolor()
{

document.fgColor=colors[i];
i++;
 if(i>5)
 i=0;
 setTimeout("changecolor()",400);
}
</script>
<body onLoad="changecolor()">
<div align="center"><strong><font size="7">Ready For Assignment </font></strong>
</div>
</body>
</html>


The text color changing every 4  sec.

(f)Explain any five Formatting and Link elements in WML with the help of an example each. Create a simple WML program that should ask for an input from a list of options. 

Ans(f)
The topmost layer in the WAP (Wireless Application Protocol) architecture is made up
of WAE (Wireless Application Environment), which consists of WML and WML scripting
language.
• WML stands for Wireless Markup Language
• WML is an application of XML, which is defined in a document-type definition.
• WML is based on HDML and is modified so that it can be compared with HTML.
• WML takes care of the small screen and the low bandwidth of transmission.
• WML is the markup language defined in the WAP specification.
• WAP sites are written in WML, while web sites are written in HTML.
• WML is very similar to HTML. Both of them use tags and are written in plain text
format.
• WML files have the extension ".wml". The MIME type of WML is "text/vnd.wap.wml".
• WML supports client-side scripting. The scripting language supported is called
WMLScript.

WML Program Structure:
Following is the basic structure of a WML program:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="one" title="First Card"> <p>
This is the first card in the deck </p>
</card>
<card id="two" title="Second Card"> <p>
Ths is the second card in the deck </p>
</card>
</wml>

2. (Covers Block 2)

(a) Differentiate between Static and Dynamic websites. How does MVC help in creating dynamic websites? Explain with the help of an example. Also differentiate between GET and POST methods of HTTP.

Ans(a)  Differentiate between Static and Dynamic websites:-

MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup for enjoyable, agile development. ASP.NET MVC includes many features that enable fast, TDD-friendly development for creating sophisticated applications that use the latest web standards. 

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


(b) Explain the following in the context of JSP with the help of an example.

 (i) page Directive 
(ii) scriptlet code 
(iii)<jsp:getProperty>
 (iv)<jsp:param>
(v) Request and Response objects 

Ans(b)
(i) Page Directive
The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
You can write XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value" />

Attributes:

Following is the list of attributes associated with page directive:
AttributePurpose
bufferSpecifies a buffering model for the output stream.
autoFlushControls the behavior of the servlet output buffer.
contentTypeDefines the character encoding scheme.
errorPageDefines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPageIndicates if this JSP page is a URL specified by another JSP page's errorPage attribute.
extendsSpecifies a superclass that the generated servlet must extend
importSpecifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.
infoDefines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafeDefines the threading model for the generated servlet.
languageDefines the programming language used in the JSP page.
sessionSpecifies whether or not the JSP page participates in HTTP sessions
isELIgnoredSpecifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabledDetermines if scripting elements are allowed for use.
(ii)scriptlet code 
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the scripting elements first.

JSP Scripting elements

The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements:
  • scriptlet tag
  • expression tag
  • declaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
  1. <%  java source code %>  

Example of JSP scriptlet tag

In this example, we are displaying a welcome message.
  1. <html>  
  2. <body>  
  3. <% out.print("welcome to jsp"); %>  
  4. </body>  
  5. </html>  

Example of JSP scriptlet tag that prints the user name

In this example, we have created two files index.html and welcome.jsp. The index.html file gets the username from the user and the welcome.jsp file prints the username with the welcome message.
File: index.html
  1. <html>  
  2. <body>  
  3. <form action="welcome.jsp">  
  4. <input type="text" name="uname">  
  5. <input type="submit" value="go"><br/>  
  6. </form>  
  7. </body>  
  8. </html>  
File: welcome.jsp

<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>

(iii) <jsp:getProperty> Action
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required ans simple syntax is as follows:
<jsp:useBean id="myName" ... /> ...
 <jsp:getProperty name="myName" property="someProperty" .../>
Following is the list of required attributes associated with setProperty action:
AttributeDescription
nameThe name of the Bean that has a property to be retrieved. The Bean must have been previously defined.
propertyThe property attribute is the name of the Bean property to be retrieved.

Example:

Let us define a test bean which we will use in our example:
/* File: TestBean.java */
package action;
 
public class TestBean {
   private String message = "No message specified";
 
   public String getMessage() {
      return(message);
   }
   public void setMessage(String message) {
      this.message = message;
   }
}
Compile above code to generated TestBean.class file and make sure that you copied TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and CLASSPATH variable should also be set to this folder:
Now use the following code in main.jsp file which loads the bean and sets/gets a simple String parameter:
<html>
 <head> 
<title>Using JavaBeans in JSP</title>
 </head> 
<body>
 <center>
 <h2>Using JavaBeans in JSP</h2> 
<jsp:useBean id="test" class="action.TestBean" /> 
<jsp:setProperty name="test" property="message" value="Hello JSP..." /> <p>Got message....</p> <jsp:getProperty name="test" property="message" /> 
</center> 
</body> 
</html>

(iv)<jsp:param>
The <jsp:param> action is used to provide information in the form of key/value pair. This action can be used as direct child element of the following actions: <jsp:include><jsp:forward> and <jsp:params> (which is a child element of the <jsp:plugin> action). The JSP compiler will issue a translation error if this element is used elsewhere.

Syntax

The <jsp:param> action has pretty simple and straightforward syntax:
<jsp:param name="paramName" value="paramValue" />
Both of the attributes paramName and paramValue are mandatory, and the paramValue can accept a runtime expression.
For the <jsp:include> and <jsp:forward> actions, the parameters will be added to the request object of the included page and forwarded page.

Examples

  • Use <jsp:param> within <jsp:include> action: 
    1
    2
    3
    4
    5
    6
    7
    <jsp:include page="header.jsp" >
     
        <jsp:param name="language" value="english" />
     
        <jsp:param name="country" value="USA" />
     
    </jsp:include>

    Access the parameters in the included page:
    1
    2
    Language: ${param.language}
    Country: ${param.country}

  • Use <jsp:param> within <jsp:forward> action: 
    1
    2
    3
    4
    5
    <jsp:forward page="login.jsp" />
     
        <jsp:param name="username" value="Tom"/>
     
    </jsp:forward>

    Access the parameters in the forwarded page:
    1
    Username: ${param.username}
  • Use <jsp:param> within <jsp:params> element of <jsp:plugin> action:
1
2
3
4
5
6
7
8
9
<jsp:plugin
    type="applet"
    code="net.codejava.applet.MyApplet.class"
    codebase="html">
 
    <jsp:params>
        <jsp:param name="username" value="Tom" />
    </jsp:params>
</jsp:plugin>

Access the parameters in the applet:

1
String username = getParameter("username");

(v)Request and Response objects 

Request and Response objects :- 
(a) The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
 (b) The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. 


(c) What is the need of Session management in HTTP? Explain with the help of an example. Create a simple form consisting of two user input fields – username and password. Check these username and password from a database (consisting of username, password and name of account holder) using JSP/Servlet. In case the username or password does not match then display a message “Username or password is not valid” else the following message is displayed “Welcome ”. 

Ans(c)
HTTP protocol and Web Servers are stateless, what it means is that for web server every
request is a new request to process and they can’t identify if it’s coming from client that
has been sending request previously.
But sometimes in web applications, we should know who the client is and process the
request accordingly. For example, a shopping cart application should know who is sending
the request to add an item and in which cart the item has to be added or who is sending
checkout request so that it can charge the amount to correct client.
That’s why we need Session Management .

Index.html

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<h1>Login Page</h1>
<h1>Hello World!</h1>
<form action="LoginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>

<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
LoginServlet.java
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor. */
/* @author Aashi */

//package com.amzi.servlets;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.RequestDispatcher;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
//import com.amzi.dao.LoginDao;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
 @Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
 String n=request.getParameter("username");
 String p=request.getParameter("userpass");
HttpSession session = request.getSession(false);

if(session!=null)
session.setAttribute("name", n);
if(LoginDao.validate(n, p)){
RequestDispatcherrd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
 }
else{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcherrd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
 }
out.close();
 }
}
LoginDao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/* @author Aashi */
//package com.amzi.dao;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
public class LoginDao {
public static boolean validate(String name, String pass) {
boolean status = false;
 Connection conn = null;
PreparedStatementpst = null;
ResultSetrs = null;

 String url = "jdbc:mysql://localhost:3306/";
 String dbName = "form";
 String driver = "com.mysql.jdbc.Driver";
 String userName = "root";
 String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager
 .getConnection(url + dbName, userName, password);
pst = conn
 .prepareStatement("select * from login where UserName=? and
password=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
status = rs.next();
 } catch (ClassNotFoundException | IllegalAccessException | InstantiationException |
SQLException e) {
System.out.println(e);
 } finally {
if (conn != null) {
try {
conn.close();
 } catch (SQLException e) {
 }
 }
if (pst != null) {
try {
pst.close();
 } catch (SQLException e) {
 }
 }
www.onlinecode.in
Provided By : Online Code
Prepared by : IGNOU ROCK
Page |
16
if (rs != null) {
try {
rs.close();
 } catch (SQLException e) {
 }
 }
 }
return status;
 }
}
Welcome.jsp
<%--
 Document : Welcome
 Created on : Sep 20, 2016, 11:39:41 PM
 Author : Aashi
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4>
 Hello,<%=session.getAttribute("UserName")%></h4>
</body>
</html>

(d) Assume that you have a database of the accounts of the students of a University in a local bank. The database fields include account number, name, phone number, address, and balance. Write a program using JSP which displays all the details of the accounts whose balance is less than 100 Rupees. 

Ans(d)
Here, we are going to create the simple example to create the login form using servlet. We have used oracle10g as the database. There are 5 files required for this application.
o index.html
o FirstServlet.java
o AccountDao.java
o SecondServlet.java
o web.xml
You must need to create a table userreg with name and pass fields. Moreover, it must have
contained some data. The table should be as:
1. create table userreg(name varchar2(40),pass varchar2(40));
index.html
1. <form action="servlet1" method="post">
2. Enter Account Number:<input type="text" name="accountno"/><br/><br/>
3. <input type="submit" value="Display Balance less than 100"/>
4. </form>
FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
14.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("accountno");
if(AccountDao.validate(n)){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request,response);
}
else{
out.print("Sorry account number error");
RequestDispatcher rd=request.getRequestDispatcher("index.html"); 

rd.include(request,response);
}
30.
out.close();
}
}
AccountDao.java
1. import java.sql.*;
2.
public class AccountDao {
public static boolean validate(String accountno){
boolean status=false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"select * from Account where accountno=? and balance>100");
ps.setString(1, accountno);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter(); 

ResultSet rs=ps.executeQuery();
While(rs.next())
{
String accountno =request.getParameter("accountno");
String name =request.getParameter("name");
String phonenumber =request.getParameter("phonenumber");
String address =request.getParameter("address");
String balcance =request.getParameter("balcance");
out.print("Accout Nnumber"+ accountno+”\t”);
out.print("Name"+ name+”\t”);
out.print("Phone Nnumber"+ phonenumber+”\t”);
out.print("Address"+ address+”\t”);
out.print("Balance"+ balcance+”\t”);
out,println();
}
out.close();
}
}

No comments:

Post a Comment