Cs9228 Web Technology Lab Manual

April 17, 2018 | Author: keerthi_sm18 | Category: Html Element, Xml, Html, Java Servlet, Cascading Style Sheets
Share Embed Donate


Short Description

LAB MANUAL FOR 2ND SEM ME...

Description

CS9228 WEB TECHNOLOGY LAB 1. Creation of HTML pages with frames, links, tables and other tags. 2. Usage of internal and external CSS along with HTML pages. 3. Client Side Programming. a. Javascript for displaying date and comparing two dates. b. Form validation including textfield, radio buttons, checkboxes, listbox and other controls 4. Usage of ASP/JSP objects Request, Response, Application, Session, Server, ADO etc. (Writing online applications such as Shopping, railway/air/bus ticket reservation system with set of ASP/JSP pages.) 5. Writing Servlet Program using HTTP Servlet. 6. Any online application with database access. (Write an ASP application for Telephone Directory using MS-ACCESS) 7. Creation of XML document for a specific domain. 8. Writing DTD or XML schema for the domain specific XML document. 9. Parsing an XML document using DOM and SAX Parsers. 10. Sample web application development in the open source environment.

CREATION OF STUDENT PROFILES USING HTML TAGS

AIM: To develop a webpage to enter the student profiles.

ALGORITHM: Step1: Start the program Step 2: Using html tags, create table to enter the student profile Step3: For each row of the table, enter the data using such that create student name,fathers name,address and e-mail,etc.. Step 4: Using we have to enter the qualification of the students. Step 5: Using radio button,we have to choose the entertainment and software exposure of the student. Step 6: Using , we have to create a declare text to type the text. Step 7: Execute the web page in Internet explorer

PROGRAM : Resume page PROFILE Name: Father Name: Mother Name: Date Of Birth: Marital Status: Communication: Gender: Male:Female:

Educational Qualifications Name of the Deg.name of the degreeName of the InstistutionYear of PassGradeSpecialization SSLC: HSC: D.C.Tech: M.C.A: M.E:

Software Exposure OS:

  Your interesting Air Travel Curabitur mi nibh, cursus vel, laoreet sit amet, aliquet sit amet, justo. Lorem ipsum dolor sit amet, con- sectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean vel magna. Nunc accumsan nulla. Nunc feugiat cursus lorem. Cras turpis. Curabitur vel velit. Curabitur mi nibh, cursus vel, laoreet sit amet, aliquet sit amet, justo. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id nibh. Sed risus. Fusce quis velit eu felis vestibulum scelerisque. Nam lectus dolor, interdum at, mollis et, vehicula ut, sem.     Latest News Lorem ipsum dolor sit amet, con- sectetuer adipiscing elit. Aenean vel magna. Nunc accumsan nulla. Curabitur mi nibh, cursus vel, laoreet sit amet, aliquet sit amet, justo. Lorem ipsum dolor.Curabitur mi nibh, cursus vel, laoreet.    USERNAME   PASSWORD             

Hot Tours             Dolor sit amet, consectetuer adipis Aliquam erat volutpat. Nulla id orci. Phasellus congue justo quis leo. sed urna imperdiet suscipit.       Home | About us | Accounts | Booking | Special Offers | Contacts

Aboutus.Html Home Page

  About us To render adequate, efficient, safe and economical air services Best airlines began its operation on 1st August, 2000 following the enactment of Air Corporations Act 2000. Today, Best Airlines, together with its fully owned subsidiary Alliance Air, has a fleet of 70 aircrafts. Since its very inception Indian Airlines has been setting standards for civil aviation. With many first in its credit, Indian Airlines has been feeding both the lavish and economical requirements of passengers across the globe. Over the years, Indian Airline has turned out to be synonymous with service, reliability and efficiency. Best Airlines' network covers Singapore in the East and Kuwait in the west and connects 18 destinations abroad. It's international network spans Oman, Kuwait, UAE, Qatar and Bahrain in West Asia; Singapore, Thailand, Malaysia and Mayanmar in South East Asia and Afghanistan, Pakistan, Nepal, Bangladesh, Sri Lanka and Maldives in the South Asia subcontinent. With a staff of over 500 thousand, Indian Airlines offers services which are simply exemplary and quite unmatched. Business to Consumer Solutions Internet Banking Solutions Intranet Workflow Solutions E-Governance Solutions Corporate Wide E-Mail Infrastructure Internet/Intranet Security Solutions Dynamic Web Design and Consultancy Domain Name Registration Key Name Registration Web Sever Co-location Solutions Call center Solutions Company Wide Internet Connectivity Web Hosting solutions Shared Hosting Services Customer Relation Management (CRM) Solutions

  Home | About us | Accounts | Booking | Special Offers | Contacts Booking.Html Home Page

Ticket Booking Departure Arriaval From Chennai Delhi Kolkata bangalore London Mumbai Singapore muscat To Chennai Delhi Kolkata bangalore London Mumbai Singapore muscat Date

Adult 1 2 3 4 5 6 7 8 Child 1 2 3 4 5 6 7 8 Pay by Bank Indian bank State bank ICICI BANK HDFC BANK AXIS BANK IDBI Bank Indian overseas Bank CITY BANK Amount Home | About us | Accounts | Booking | Special

Offers | Contacts Contacts.html: Home Page



  Email Supporting Use the form below to get in touch with us in connection with the travel related queries. Name email ID subject Delhi mumbai chennai kolkata bangalore covaisingapure muscat

location reservation product and services complients and compliments fares and tickets frequently flyer feedback others > Descrption   Home | About us | Accounts | Booking | Special Offers | Contacts

Sample Output :

RESULT: Thus the website has been developed sucessfully.

CLIENT SIDE PROGRAMMING JAVASCRIPT FOR DISPLAYING DATE AND COMPARING TWO DATES AIM: To validate the student profile using javascript. ALGORITHM: Step 1: start the program. Step 2: Design a home page student profile using different html tags, forms and attributes. Step 3: Using javascript, we validate whether the text and other text fields are empty or to be filled. Step 4: Check whether the checkbox has been already checked or not. Step 5: Check whether the radio button has been already checked or not. Step 6: Check whether the nick name is used as a password or not. Step 7: Validate the date of birth that should be in date format(dd-mmyy) or not. Step 8: Allow the age field size should be two and only be the numbers. Step 9: In the name field, ensure that it should allow only the capital letters. Step 10: Check that the password field contains only the 8 characters. Step 11: Execute the program in Internet explorer. Step 12: Stop the program.

PROGRAM: Compare Dates function CompareDates() { var str1 = document.getElementById("Fromdate").value; var str2 = document.getElementById("Todate").value; var dt1 = parseInt(str1.substring(0,2),10); var mon1 = parseInt(str1.substring(3,5),10); var yr1 = parseInt(str1.substring(6,10),10); var dt2 = parseInt(str2.substring(0,2),10); var mon2 = parseInt(str2.substring(3,5),10); var yr2 = parseInt(str2.substring(6,10),10); var date1 = new Date(yr1, mon1, dt1); var date2 = new Date(yr2, mon2, dt2); if(date2 < date1) { alert("To date cannot be greater than from date"); return false; } else { alert("Submitting ..."); document.form1.submit(); } } Date Comparison

Sample Output:

RESULT: Thus the program for Javascript for displaying date and comparing two Dates has been successfully compiled and executed..

FORM VALIDATION INCLUDING TEXTFIELD, RADIO BUTTONS, CHECKBOXES, LISTBOX AND OTHER CONTROLS

AIM: To validate the student profile using javascript. ALGORITHM: Step 1: start the program. Step 2: Design a home page student profile using different html tags,forms and attributes. Step 3: Using javascript, we validate whether the text and other text fields are empty or to be filled. Step 4: Check whether the checkbox has been already checked or not. Step 5: Check whether the radio button has been already checked or not. Step 6: Check whether the nick name is used as a password or not. Step 7: Validate the date of birth that should be in date format(dd-mmyy) or not. Step 8: Allow the age field size should be two and only be the numbers. Step 9:In the name field,ensure that it should allow only the capital letters. Step 10:Check that the password field contains only the 8 characters. Step 11:Execute the program in Internet explorer. Step 12:Stop the program.

PROGRAM : from validation function checkEmail (strng) { var error=""; if (strng == "") { error = "You didn't enter an email address.\n"; } var emailFilter=/^[email protected]+\..{2,3}$/; if (!(emailFilter.test(strng))) { error = "Please enter a valid email address.\n"; } else { //test email for illegal characters var illegalChars= /[\(\)\\,\;\:\\\"\[\]]/ if (strng.match(illegalChars)) { error = "The email address contains illegal characters.\n"; } } return error; } // phone number - strip out delimiters and check for 10 digits function checkPhone (strng) { var error = ""; if (strng == "") { error = "You didn't enter a phone number.\n"; } var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable nonnumeric characters if (isNaN(parseInt(stripped))) { error = "The phone number contains illegal characters."; } if (!(stripped.length == 10)) { error = "The phone number is the wrong length. Make sure you included an area code.\n"; } return error; } // password - between 6-8 chars, uppercase, lowercase, and numeral

function checkPassword (strng) { var error = ""; if (strng == "") { error = "You didn't enter a password.\n"; } var illegalChars = /[\W_]/; // allow only letters and numbers if ((strng.length < 6) || (strng.length > 8)) { error = "The password is the wrong length.\n"; } else if (illegalChars.test(strng)) { error = "The password contains illegal characters.\n"; } else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) { error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n"; } return error; }

// username - 4-10 chars, uc, lc, and underscore only. function checkUsername (strng) { var error = ""; if (strng == "") { error = "You didn't enter a username.\n"; } var illegalChars = /\W/; // allow letters, numbers, and underscores if ((strng.length < 4) || (strng.length > 10)) { error = "The username is the wrong length.\n"; } else if (illegalChars.test(strng)) { error = "The username contains illegal characters.\n"; } return error; }

// non-empty textbox

function isEmpty(strng) { var error = ""; if (strng.length == 0) { error = "The mandatory text area has not been filled in.\n" } return error; } // was textbox altered function isDifferent(strng) { var error = ""; if (strng != "Can\'t touch this!") { error = "You altered the inviolate text area.\n"; } return error; } // exactly one radio button is chosen function checkRadio(checkvalue) { var error = ""; if (!(checkvalue)) { error = "Please check a radio button.\n"; } return error; } // valid selector from dropdown list function checkDropdown(choice) { var error = ""; if (choice == 0) { error = "You didn't choose an option from the drop-down list.\n"; } return error; }

Sample output:

RESULT: Thus the web page for student profile has been developed and validated successfully.

STUDENT INFORMATION SYTEM USING JSP AND SERVLET

AIM: To develop the student webpage information using java servlet and JDBC. ALGORITHM : Start the program Create main HTML page for student database maintenance Select option to do the following operation Insertion, search ,delete and modify or update the student recode

Main.Html Student database maintenance REGISTER SEARCH VIEW ALL DELETE

Register.HTML registration Enter Id : Enter Name : Enter Age : Enter Branch: Enter Mark1 : Enter Mark2 : Enter Mark3 : Enter Grade : Click : Insert.Html registration Enter Id : Enter Name : Enter Age : Enter Branch: Enter Mark1 : Enter Mark2 : Enter Mark3 : Enter Grade :

Delete.Html DELETE STUDENT RECORD Enter the ID : Click : Second.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.lang.*; public class second extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { loginform(res,false); }//goGet() private void loginform(HttpServletResponse res,boolean error)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pr=res.getWriter(); pr.println(""); pr.println(""); if(error) {

pr.println("LOGIN FAILED, PLEASE TRY AGAIN!!!"); } pr.println(""); pr.println(" please enter your name and password"); pr.println("Username: "); pr.println("Password:"); pr.println("Press:"); pr.println("clear:"); pr.println(""); }//loginform() public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String name=req.getParameter("username"); String pass=req.getParameter("password"); if(logindb(name,pass)) { RequestDispatcher rd=req.getRequestDispatcher("/main.html"); rd.forward(req,res); } else { loginform(res,true); } }//doPost() boolean logindb(String name, String pass) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:logindb"); Statement s=con.createStatement(); String sql="select * from stu where username= '" + name + "' AND password= '" + pass + "' ";

ResultSet rs=s.executeQuery(sql); if(rs.next()) { return true; } con.close(); } catch(SQLException s) { s.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return false; }//login() }; Register1.java /* INSERTING THE DATA */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; public class register1 extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { try { res.setContentType("Text/html"); PrintWriter pr=res.getWriter(); int id=Integer.parseInt(req.getParameter("id")); String name=req.getParameter("name"); int age=Integer.parseInt(req.getParameter("age")); String branch=req.getParameter("branch"); int m1=Integer.parseInt(req.getParameter("m1"));

int m2=Integer.parseInt(req.getParameter("m2")); int m3=Integer.parseInt(req.getParameter("m3")); String grade=req.getParameter("grade"); pr.println(""); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:ss"); //pr.println("student information are successfully registered"); //pr.println("goto main page"); PreparedStatement pst=con.prepareStatement("Insert into studata values(?,?,?,?,?,?,?,?) "); pst.setInt(1,id); pst.setString(2,name); pst.setInt(3,age); pst.setString(4,branch); pst.setInt(5,m1); pst.setInt(6,m2); pst.setInt(7,m3); pst.setString(8,grade); pst.executeQuery(); pr.println("student information are successfully registered"); pr.println("goto main page"); pr.println(""); con.commit(); } catch(SQLException e) { System.out.println(e.getMessage()); } catch(Exception e) { e.printStackTrace(); } } };

Insert.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; public class register extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { try { res.setContentType("Text/html"); PrintWriter pr=res.getWriter(); int id=Integer.parseInt(req.getParameter("id")); String name=req.getParameter("name"); int age=Integer.parseInt(req.getParameter("age")); String branch=req.getParameter("branch"); int m1=Integer.parseInt(req.getParameter("m1")); int m2=Integer.parseInt(req.getParameter("m2")); int m3=Integer.parseInt(req.getParameter("m3")); String grade=req.getParameter("grade"); pr.println(""); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:ss"); // pr.println("Get connection"); PreparedStatement pst=con.prepareStatement("Insert into studata values(?,?,?,?,?,?,?,?) "); pst.setInt(1,id); pst.setString(2,name); pst.setInt(3,age); pst.setString(4,branch); pst.setInt(5,m1); pst.setInt(6,m2); pst.setInt(7,m3); pst.setString(8,grade); pst.executeQuery();

con.commit(); pr.println("student information are successfully registered"); pr.println("goto main page"); pr.println(""); con.close(); } catch(SQLException e) { System.out.println(e.getMessage()); } catch(Exception e) { e.printStackTrace(); } } }; Find3.Java /* SEARCH THE PARTICULAR RECORD */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; public class find3 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { res.setContentType("Text/html"); PrintWriter pr=res.getWriter(); pr.println(""); pr.println(""); pr.println("Enter the student ID:");

pr.println("click:"); pr.println(""); } public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { try { res.setContentType("Text/html"); PrintWriter pr=res.getWriter(); String id =req.getParameter("id"); int idno=Integer.parseInt(id); pr.println(""); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:ss"); //PreparedStatement pst=con.prepareStatement("select * from studata where ID= '" + idno + "' "); PreparedStatement pst=con.prepareStatement("select * from studata where ID= ? "); pst.setInt(1,idno); ResultSet r=pst.executeQuery(); while(r.next()) { pr.println(r.getInt(1)+"\t"+r.getString(2)+"\t"+r.getInt(3)+"\t"+r.getSt ring(4)+"\t"+r.getInt(5)+"\t"+r.getInt(6)+"\t"+r.getInt(7)+"\t"+r.getString(8) ); pr.println(""); } pr.println("goto main page"); pr.println(""); } catch(SQLException e) { System.out.println(e.getMessage()); } catch(Exception e) { e.printStackTrace();

} } }; Delete2.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; public class delete2 extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException { try { res.setContentType("Text/html"); PrintWriter pr=res.getWriter(); pr.println(""); String idno=req.getParameter("idno"); int id=Integer.parseInt(idno); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:ss"); pr.println("get connected"); //PreparedStatement pst=con.prepareStatement("Delete from studata where ID= '" + id + "' "); PreparedStatement pst=con.prepareStatement("Delete from studata where ID= ? "); pst.setInt(1,id); pst.executeUpdate(); pr.println("student record is successfully deleted"); pr.println("goto main page"); pr.println(""); con.commit(); } catch(SQLException e) { System.out.println(e.getMessage());

} catch(Exception e) { e.printStackTrace(); } } }; Output: Studenttable.

RESULT : Thus student information java script program is successfully completed.

SERVLET PROGRAM USING HTTP SERVLET AIM: To create a servlet program and check the script validation. ALGORITHM: Step 1: Start the program. Step 2: Get the context text at Servlet at text html. Step 3: Get the response from the user by entering the username field. Step 4: Get the response from the user by entering the password field. Step 5: If the username and password are correct, then the user is authenticated and can enter into web page. Step 6: Execute the program in Internet Explorer. Stepe 7: Stop the program.

PROGRAM HTML Code : USERNAME AND PASSWORD> USERNAME PASSWORD Java Servlet Code : import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class servlet1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); String admin=req.getParameter("username"); String pass=req.getParameter("password"); pw.println(admin); pw.println(pass);

if((admin.equals("admin2010")) && (pass.equals("abc123"))) { pw.println("Authorized user"); } else { pw.println("not an Authorized user"); } } }

Sample output:

RESULT: Thus the servlet program has been created and validated successfully.

IMPLEMENTATION OF JAVA DATABASE CONNECTIVITY(JDBC) AIM: To connect the database using jdbc connectivity in java.

ALGORITHM: Step 1:Start the program. Step2 :Write the source code for connectivity. Step 3:Using MS-Access, save the database. Step 4:connect the database using ODBC Source connection. Step 5: Add the database name in ODBC data source administrator. Step 6:Add the table name to connection. Step 7:Compile the program and execute it. Step 8:Stop the program.

PROGRAM import java.sql.*; import java.io.*; public class jdbcdemo { public static void main(String args[]) { Connection c= null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); c=DriverManager.getConnection("jdbc:odbc:jdbcdemodb"); Statement stmt=c.createStatement(); ResultSet rs=stmt.executeQuery("select * from Employee"); System.out.println("name and password are"); while(rs.next()) { System.out.println(rs.getString(1)+"\t"+rs.getInt(2)+"\t"+rs.getDouble(3)); } c.close(); } catch(SQLException e1) { e1.printStackTrace(); } catch(Exception e) { System.out.println("error"+e.getMessage()); } } }

Sample output:

RESULT: Thus the implementation of Java Database connectivity has been executed successfully.

IMPLEMENTATION OF SERVLET - JDBC DEMO PROGRAM

AIM: To create a servlet with JDBC connectivity in java.

ALGORITHM: Step 1:Start the program. Step 2:Get the context text at Servlet at text html. Step 3:Get the response from the user by entering the username field. Step 4: Get the response from the user by entering the password field. Step 5:If the username and password are correct, then the user is authenticated and can enter into web page. Step 6:Execute the program in Internet Explorer. Step 7 :Write the source code for connectivity. Step 8:Using MS-Access, save the database. Step 9:connect the database using ODBC Source connection. Step 10: Add the database name in ODBC data source administrator. Step 11:Add the table name to connection. Step 12:Compile the program and execute it. Step 13 :Stop the program.

PROGRAM import javax.servlet.*; import java.io.*; import java.sql.*; public class servletdemojdbc implements Servlet { public void init(ServletConfig c) throws ServletException { //super.init(c); System.out.println("joint method"); } public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException { Connection c= null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); c=DriverManager.getConnection("jdbc:odbc:jdbcdemo"); Statement stmt=c.createStatement(); ResultSet rs=stmt.executeQuery("select * from Employee"); System.out.println("name and password are"); while(rs.next()) { System.out.println(rs.getString(1)+"\t"+rs.getInt(2)+"\t"+rs.getDouble(3)); } c.close(); } catch(SQLException e1) { e1.printStackTrace(); } catch(Exception e) { System.out.println("error"+e.getMessage()); } System.out.println("exec "); } public String getServletInfo() { String author="raman";

String program="c"; System.out.println(author+"wrote"+program); return null; } public ServletConfig getServletConfig() { return null; } public void destroy() { } }

Sample output:

RESULT: Thus the program for database connectivity using jdbc has been created and executed successfully

SAMPLE WEB APPLICATION DEVELOPMENT IN THE OPEN SOURCE ENVIRONMENT WITH DATABASE ACCESS.

AIM: To create Sample web application development in the open source environment.

ALGORITHM : Step1: start the program Step2: Inside the asp definiton tag include the html contents Step3: include the code for the database connectivity using the ado object Step4: select all the datas form the student table Step5: Traverse all the tuples in the table Step6: Print the datas Step7: close the connection Step8: stop the program

Programs: access.asp file: con.open "dsn=cse;" set rs=Server.Createobject("ADODB.RecordSet") set rs=con.Execute("select * from student where name="&name&")%> stuaccess.html file: Name

Sample Output:

RESULT : Thus the Sample web application development in the open source environment has been executed successfully executed.

CREATION OF XML DOCUMENT FOR A SPECIFIC DOMAIN.

AIM: To creation of XML document for a specific domain

ALGORITHM: Step1:start the program Step2:using Onclick(),validate the student details as entered. Step3:In XML file,we use styles for structure the program as #PCDATA(datafield) Step4:Using various HTML tags and attribute,we design the web page. Step5:Using various XML attribute list and entity list to retrieve the information of student. Step6:Using processing instructions which we required to describe the data. Step7:Using “note.xml”as xmlid to connect with html file.Execute the program. Step8:Stop the program.

Program Student.html: function prev_onclick() { std.previousPage() } function next_onclick() { std.nextPage() } REGNONAMECOURSESEM note.xml:

VMP49 THANUJA.O M.E CSE II VMP52 TAMILARASI M.E CSE II Sample Output :

RESULT : Thus the developing XML program has been executed successfully.

WRITING DTD OR XML SCHEMA FOR THE DOMAIN SPECIFIC XML DOCUMENT

AIM: To write a program for DTD and XML schema for the domain specific XML document. ALGORITHM: Step1:start the program Step2:open an XML file as Letter.xml, to create detail of person using various xml attribute list Step3:using user defined tags, we can create details of person using name, pincode, address, ph.no, etc.. Step4:open DTD file as letter . dtd Step5:using an external and internaldtd,we create elementlist as #PCDATA for retrieve the datafield Step6:using attribute declaration ,use to retrieve the datafield as more than one time Step7:Execute the program

Program: Letter.xml: aaaa dfdsgdsgdsfvg chennai tamilnadu 600089 044-23456789 bbbb dfdsgdsgdsfvg fvgefgffdg chennai tamilnadu 600089 044-23456789 Dear Sir: It is our privillege ......... Sincerely Ms.aaaaa

Letter.dtd:

Output:

RESULT: Thus the program for writing DTD or XML schema for the domain specific XML document has been successfully completed.

PARSING AN XML DOCUMENT USING DOM AND SAX PARSERS.

AIM: To Parsing an XML document using DOM and SAX Parsers.

ALGORITHM : Using Dom: Step1: Get a document builder using document builder factory and parse the xml file to create a DOM object Step 2: Get a list of employee elements from the DOM Step3: For each employee element get the id, name, age and type. Create an employee value object and add it to the list. Step4: At the end iterate through the list and print the employees to verify we parsed it right. Using Sax Step1: Create a Sax parser and parse the xml Step2: In the event handler create the employee object Step3 : Print out the data

Coding employees.xml





Seagull

3674

34





Robin

3675

25





Crow

3676

28





Using DOM

DomParserExample.java

a) Getting a document builder private void parseXmlFile(){

//get the factory

DocumentBuilderFactory dbf =

DocumentBuilderFactory.newInstance();

try {

//Using factory get an instance of document builder

DocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation of the

XML file

dom = db.parse("employees.xml");

}catch(ParserConfigurationException pce) {

pce.printStackTrace();

}catch(SAXException se) {

se.printStackTrace();

}catch(IOException ioe) {

ioe.printStackTrace();

}

} b) Get a list of employee elements Get the rootElement from the DOM object.From the root element get all employee elements. Iterate through each employee element to load the data.

private void parseDocument(){

//get the root element

Element docEle = dom.getDocumentElement();

//get a nodelist of

elements

NodeList nl = docEle.getElementsByTagName("Employee");

if(nl != null && nl.getLength() > 0) {

for(int i = 0 ; i < nl.getLength();i++) {

//get the employee element

Element el = (Element)nl.item(i);

//get the Employee object

Employee e = getEmployee(el);

//add it to list

myEmpls.add(e);

}

}

} c) Reading in data from each employee.

/**

* I take an employee element and read the values in, create

* an Employee object and return it

*/

private Employee getEmployee(Element empEl) {

//for each element get text or int values of

//name ,id, age and name

String name = getTextValue(empEl,"Name");

int id = getIntValue(empEl,"Id");

int age = getIntValue(empEl,"Age");

String type = empEl.getAttribute("type");

//Create a new Employee with the value read from the xml

nodes

Employee e = new Employee(name,id,age,type);

return e;

}

/**

* I take a xml element and the tag name, look for the tag and get

* the text content

* i.e for John xml snippet if

* the Element points to employee node and tagName is 'name' I will

return John

*/

private String getTextValue(Element ele, String tagName) {

String textVal = null;

NodeList nl = ele.getElementsByTagName(tagName);

if(nl != null && nl.getLength() > 0) {

Element el = (Element)nl.item(0);

textVal = el.getFirstChild().getNodeValue();

}

return textVal;

}

/**

* Calls getTextValue and returns a int value

*/

private int getIntValue(Element ele, String tagName) {

//in production application you would catch the exception

return Integer.parseInt(getTextValue(ele,tagName));

} d) Iterating and printing.

private void printData(){

System.out.println("No of Employees '" + myEmpls.size() +

"'.");

Iterator it = myEmpls.iterator();

while(it.hasNext()) {

System.out.println(it.next().toString());

}

}

Using Sax:

SAXParserExample.java

a) Create a Sax Parser and parse the xml

private void parseDocument() {

//get a factory

SAXParserFactory spf = SAXParserFactory.newInstance();

try {

//get a new instance of parser

SAXParser sp = spf.newSAXParser();

//parse the file and also register this class for call backs

sp.parse("employees.xml", this);

}catch(SAXException se) {

se.printStackTrace();

}catch(ParserConfigurationException pce) {

pce.printStackTrace();

}catch (IOException ie) {

ie.printStackTrace();

}

} b) In the event handlers create the Employee object and call the corresponding setter methods.

//Event Handlers

public void startElement(String uri, String localName, String

qName,

Attributes attributes) throws SAXException {

//reset

tempVal = "";

if(qName.equalsIgnoreCase("Employee")) {

//create a new instance of employee

tempEmp = new Employee();

tempEmp.setType(attributes.getValue("type"));

}

}

public void characters(char[] ch, int start, int length) throws

SAXException {

tempVal = new String(ch,start,length);

}

public void endElement(String uri, String localName,

String qName) throws SAXException {

if(qName.equalsIgnoreCase("Employee")) {

//add it to the list

myEmpls.add(tempEmp);

}else if (qName.equalsIgnoreCase("Name")) {

tempEmp.setName(tempVal);

}else if (qName.equalsIgnoreCase("Id")) {

tempEmp.setId(Integer.parseInt(tempVal));

}else if (qName.equalsIgnoreCase("Age")) {

tempEmp.setAge(Integer.parseInt(tempVal));

}

} c) Iterating and printing.

private void printData(){

System.out.println("No of Employees '" + myEmpls.size() +

"'.");

Iterator it = myEmpls.iterator();

while(it.hasNext()) {

System.out.println(it.next().toString());

}

}

OUTPUT:

Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.

Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.

Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.

Result : Thus the Parsing an XML document using DOM and SAX Parsers is been done and executed successfully.

CREATION OF WEB APPLICATION USING PHP

AIM: To create a calculator web appliction using php.

ALGORITHM :

Step1 : Start the program Step2 : Create a php web page calc.php Step3: Using form and input type tag create various buttons, textbox, radio button etc. Step4: calcute the output for various option Step5: using post method display the result in next page. Step6: Stop the program.

Coding: Calc.php: Calculator All field are required, however, if you forget any, we will put a random number in for you.
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF