0% found this document useful (0 votes)
35 views43 pages

AOT File

The document contains a practical file for JavaScript programming submitted by a student. It includes 16 programs of different JavaScript concepts like creating frames, buttons, checkboxes, scroll panes, trees, tables, radio buttons and more. Each program is accompanied by its output.

Uploaded by

NARENDER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views43 pages

AOT File

The document contains a practical file for JavaScript programming submitted by a student. It includes 16 programs of different JavaScript concepts like creating frames, buttons, checkboxes, scroll panes, trees, tables, radio buttons and more. Each program is accompanied by its output.

Uploaded by

NARENDER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

MKM College Of Management & Information Technology for

Girls,hodal

(Affiliated to M.D.U. Rohtak)


(Session 2022-2023)
Practical File – JavaScript Programming

Submitted to: Submitted by:


Mrs. Priyanka Pathak Mam Name: Deepali
(Assistant Professor) Class: MCA 1st (2ndsem)
Roll No.:

1
Index
S.No. Objectives Date Signature
1 Simple HTML Program
2 Java program to create Frame
3 Java program to create Submit
button1
4 Java program to create Click Button
5 Java Program to create CheckBox
and Radio Button
6 Java program to create Scroll Pane
7 Java program to create JTree
8 Java program to create Table
9 Java program to create Radio
Button
10 Java program to create JTable
11 Write a program to show live date and
time in javascript
12 Java program of session tracking
using HTTP servlet interface
13 Java program to create Element of
JSP
14 Java program to create Form to
accept UserName and Password
15 Java program to create Page to
accept client data :
exGetrParameter.html page.
16 Java program to find sum of two
number in JSP.

2
1. HTML Program
<html>
<title>Java Script </title>
<head>
<body>
<h1> hello world</h1>
<h2> hello world</h2>
<button name="button" type="button"> click here</button>
</body>
</head>
</html>
Output:

3
2. Java Program to create Frame

import javax.swing.*;
import java.awt.*;
class Example{

public static void main(String[] args){


JFramejf=new JFrame("Swing Example");
jf.setSize(300,300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

4
3. Java Program to create Submit Button
import java.awt.event.*;
import javax.swing.*;
class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
final JTextFieldtf=new JTextField();

tf.setBounds(50,50,150,30);
JButton b=new JButton("Submit");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText("welcome to Javatpoint");
}
} );
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

5
4. Java Program to create Click Button

import javax.swing.*;
class ButtonExample{
public static void main(String[] args){
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

6
5. Java Program to Create Check Boxes and Radio Buttons

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Button_Checkbox implements ActionListener,ItemListener
{
static JFrame frame;
static JLabel text1,text2;
static JCheckBox[] checkbox;
static JRadioButton[] button;
//Driver function
public static void main(String args[])
{
//Create a frame
frame=new JFrame("Buttons & Checkboxes");
frame.setSize(600,600);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.white);
//Create the text fields
text1=new JLabel("");
text1.setBounds(0,450,600,50);
frame.add(text1);
text2=new JLabel("");
text2.setBounds(0,500,600,50);

7
frame.add(text2);
//Create an object
Button_Checkboxobj=new Button_Checkbox();
//Create 3 buttons
button=new JRadioButton[3];
for(inti=0;i<3;i++)
{
button[i]=new JRadioButton("Button "+(i+1));
button[i].setBounds(200,i*80,100,50);
frame.add(button[i]);
button[i].addActionListener(obj);
}
//Create 3 Checkbox
checkbox=new JCheckBox[3];
for(inti=0;i<3;i++)
{
checkbox[i]=new JCheckBox("Checkbox"+(i+1));
checkbox[i].setBounds(220,(240)+i*80,100,50);
frame.add(checkbox[i]);
checkbox[i].addItemListener(obj);
}
//Display frame
frame.setVisible(true);
}
//To display button selected
public void actionPerformed(ActionEvent e)

8
{
String s="";
for(inti=0;i<3;i++)
{
if(button[i].isSelected())
s=s+" "+button[i].getText();
}
text1.setText("Button(s) Selected : "+" "+s);
}
//To display the checkboxes checked
public void itemStateChanged(ItemEvent e)
{
String s="";
for(inti=0;i<3;i++)
{
if(checkbox[i].isSelected())
s=s+" "+checkbox[i].getText();
}
text2.setText("Checkbox(s) Selected : "+s);
}
}

9
Output:

10
6. Java program to create scroll pane
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

class JScrollPaneExample {
private static final long serialVersionUID = 1L;

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scroll Pane Example");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// set flow layout for the frame


frame.getContentPane().setLayout(new FlowLayout());

JTextAreatextArea = new JTextArea(20, 20);


JScrollPanescrollableTextArea = new JScrollPane(textArea);

11
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCR
OLLBAR_ALWAYS);

scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBA
R_ALWAYS);

frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}

Output:

12
7. Java Program to create JTree
13
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
class Example {
JFrame f;
Example(){
f=new JFrame();
DefaultMutableTreeNode country=new DefaultMutableTreeNode("India");
DefaultMutableTreeNode state=new DefaultMutableTreeNode("States");
country.add(state);
DefaultMutableTreeNodewb=new DefaultMutableTreeNode("WestBengal");
DefaultMutableTreeNode del=new DefaultMutableTreeNode("Delhi");
DefaultMutableTreeNodeap=new DefaultMutableTreeNode("Andhra
Pradesh");
DefaultMutableTreeNodetn=new DefaultMutableTreeNode("Tamil Nadu");
DefaultMutableTreeNode hr=new DefaultMutableTreeNode("Hrayana");
DefaultMutableTreeNodech=new DefaultMutableTreeNode("Chandigarh");
DefaultMutableTreeNodepjb=new DefaultMutableTreeNode("Punjab");
state.add(wb); state.add(del); state.add(ap); state.add(tn); state.add(hr);
state.add(ch); state.add(pjb);
JTreejt=new JTree(state);
f.add(jt);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String[] args) {
new Example();
}}

14
Output:

8. Java Program to create a Table


15
import javax.swing.*;
class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","priya","MCA"},
{"102","kirti","MCA"},
{"101","Sona","MCA"}};
String column[]={"ID","NAME","Class"};
JTablejt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPanesp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output:

16
9. Java Program to create Radio Button
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;

17
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroupbg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"you are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"you are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();

18
}
}
Output:

10. Java program to create Table

import javax.swing.*;
class ListExample

19
{
ListExample(){
JFrame f=new JFrame();
DefaultListModel<String>l1=new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String>list=new JList<>(l1);
list.setBounds(100,100,75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}

20
21
11.Write a program to show live date and time in javascript

import java.awt.*;
import javax.swing.*;

public class QuickApplet extends JApplet {

private JLabel label = new JLabel("This is a Java applet");

public void init() {


setLayout(new FlowLayout());
label.setFont(new Font("Arial", Font.BOLD, 18));
label.setForeground(Color.RED);
add(label);
}

public void drawText(String text) {


label.setText(text);
}
}

This applet shows only label and declare a public


method drawText(String) which updates the label’s text.

Here is code of the HTML page (QuickAppletTest.html):

22
<html>
<head>
<title>Javascript call Applet example</title>
</head>
<body>
<center>
<input type="button" value="Call Applet" onclick="callApplet();"/>
<br/><br/>

<applet id="QuickApplet"
code="QuickApplet.class"
width="300" height="50">
</applet>
</center>
</body>
<script type="text/javascript">

function callApplet() {
varcurrentTime = new Date();
var time = currentTime.toISOString();

// invoke drawText() method of the applet and pass time string


// as argument:

QuickApplet.drawText(time);
}
</script>
</html>

OUTPUT:

23
Let's see the simple example of forName() method.

FileName: Test.java

1. class Simple{}
2.
3. public class Test{
4. public static void main(String args[]) throws Exception {
5. Class c=Class.forName("Simple");
6. System.out.println(c.getName());
7. }
8. }

Output:

Simple

2) getClass() method of Object class

It returns the instance of Class class. It should be used if you know the type.
Moreover, it can be used with primitives.

FileName: Test.java

1. class Simple{}
2.
3. class Test{
4. void printName(Object obj){

24
5. Class c=obj.getClass();
6. System.out.println(c.getName());
7. }
8. public static void main(String args[]){
9. Simple s=new Simple();
10.
11. Test t=new Test();
12. t.printName(s);
13. }
14.}
15.

Output:

Simple

3) The .class syntax

If a type is available, but there is no instance, then it is possible to obtain a


Class by appending ".class" to the name of the type. It can be used for
primitive data types also.

FileName: Test.java

1. class Test{
2. public static void main(String args[]){
3. Class c = boolean.class;
4. System.out.println(c.getName());
5.
6. Class c2 = Test.class;
7. System.out.println(c2.getName());
8. }
9. }

Output:

boolean
Test

25
12. Example of Session tracking using HttpServlet Interface: In the
below example the setAttribute() and getAttribute() methods of the
HttpServlet class is used to create an attribute in the session scope of
one servlet and fetch that attribute from the session scope of another
servlet.

 index.html

<html>

<head>

<body>

<formaction="servlet1">

Name:<inputtype="text"name="userName"/><br/>

<inputtype="submit"value="submit"/>

</form>

</body>

</html>

 First.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

26
< div class = "noIdeBtnDiv" > public class First extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)
{
try { /*Declaration of the get method*/

response.setContentType("text/html"); // Setting the content


type to text
PrintWriter out = response.getWriter();

String n = request.getParameter("userName"); /*Fetching the


contents of
the userName field from the form*/
out.print("Welcome " + n); // Printing the username

HttpSession session = request.getSession(); /* Creating a new


session*/

session.setAttribute("uname", n);
/*Setting a variable uname
containing the value as the fetched
username as an attribute of the session
which will be shared among different servlets
of the application*/

out.print("<a href='servlet2'>visit</a>"); // Link to the second


servlet

out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}

27
 Second.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response) try {
/*Declaration of the get method*/
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(false);


/*Resuming the session created
in the previous servlet using
the same method that was used
to create the session.
The boolean parameter 'false'
has been passed so that a new session
is not created since the session already
exists*/

String n = (String)session.getAttribute("uname");
out.print("Hello " + n);

out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}

 web.xml

28
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Second</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

OutPut:

29
13.We will discuss Syntax in JSP. We will understand the basic use of
simple syntax (i.e, elements) involved with JSP development.
Elements of JSP
The elements of JSP have been described below −
The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.
Following is the syntax of Scriptlet −
<% code fragment %>

30
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet.
Following is the simple and first example for JSP −

<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
out.println("Your IP address is "+request.getRemoteAddr());
%>
</body>
</html>

HTTP Status Code Example


Following example shows how a 407 error code is sent to the client browser.
After this, the browser would show you "Need authentication!!!" message.

<html>
<head>
<title>Setting HTTP Status Code</title>
</head>

31
<body>
<%
// Set error code and reason.
response.sendError(407,"Need authentication!!!");
%>
</body>
</html>

32
Program14: Form to accept username and password:
Login.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>User Details</h1>
<%-- The form data will be passed to acceptuser.jsp
for validation on clicking submit
--%>
<form method ="get" action="acceptuser.jsp">
Enter Username :<input type="text"
name="user"><br/><br/>
Enter Password :<input type="password" name
="pass"><br/>
<input type ="submit" value="SUBMIT">
</form>
</body>

33
</html>

JSP to accept from data and verify a user: acceptuser.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Accept User Page</title>
</head>
<body>
<h1>Verifying Details</h1>
<%-- Include the ValidateUser.java class whose method
booleanvalidate(String, String) we will be using
--%>
<%-- Create and instantiate a bean and assign an id to
uniquely identify the action element throughout the jsp
--%>
<jsp:useBean id="snr" class="saagnik.ValidateUser"/>

<%-- Set the value of the created bean using form data --%>
<jsp:setProperty name="snr" property="user"/>

34
<jsp:setProperty name="snr" property="pass"/>

<%-- Display the form data --%>


The Details Entered Are as Under<br/>
<p>Username :<jsp:getProperty name="snr"
property="user"/></p>
<p>Password :<jsp:getProperty name="snr"
property="pass"/></p>

<%-- Validate the user using the validate() of


ValidateUser.java class
--%>
<%if(snr.validate("GeeksforGeeks", "GfG")){%>
Welcome! You are a VALID USER<br/>
<%}else{%>
Error! You are an INVALID USER<br/>
<%}%>
</body>
</html>

35
The validateUser.java class
package saagnik;
import java.io.Serializable;

// To persist the data for future use,


// implement serializable
public class ValidateUser implements Serializable {
private String user, pass;

// Methods to set username and password


// according to form data
public void setUser(String u1) { this.user = u1; }
public void setPass(String p1) { this.pass = p1; }

// Methods to obtain back the values set


// by setter methods
public String getUser() { return user; }
public String getPass() { return pass; }

// Method to validate a user

36
public booleanvalidate(String u1, String p1)
{
if (u1.equals(user) && p1.equals(pass))
return true;
else
return false;
}
}
Output:

37
15.Page to accept client data : exGetrParameter.html page
<html>
<head>
<title>Get Parameter Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<!-- Here we specify that the from data will be sent to
getparam.jsp page using the action attribute
-->
<form name="testForm" action="getparam.jsp">
<label><h1>Enter a text and click Submit<h1/></label><br/>
<input type="text" name="testParam"><br/>
<input type="submit">
</form>
</body>
</html>

38
<%@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>
<%-- Here we fetch the data using the name attribute
of the text from the previous page
--%>
<% String val = request.getParameter("testParam"); %>
</body>
<%-- Here we use the JSP expression tag to display value
stored in a variable
--%>
<h2>The text entered was :</h2><%=val%>
</html>

39
Output:

40
16.Program to Find Sum of Two Numbers in JSP
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add Two Number</title>
</head>
<body>
<h1 align="center" style="color:red">ADD TWO NUMBER</h1>

<%
String result=(String)request.getAttribute("result");
%>

<%
if(result!=null)
{
%>
<h3 align="center" style="color:red">Sum of two number is <span
style="color:blue"><%=result %></span></h3>
<%
}
%>
<div align="center">

<form action="AddNoServlet" method="post">


<table>
<tr>
<td>Enter 1st number: </td>
<td><input type="text" name="no1"></td>

41
</tr>

<tr>
<td>Enter 2nd number: </td>
<td><input type="text" name="no2"></td>
</tr>

<tr>
<td><input type="submit" value="Add Numbers"></td>
</tr>
</table>
</form>

</div>
</body>
</html>

AddNoServlet.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/AddNoServlet")
public class AddNoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public AddNoServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.getWriter().append("Served at:
").append(request.getContextPath());
}

42
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

System.out.println("Entered into Servlet.");


String number1=request.getParameter("no1");
String number2=request.getParameter("no2");

int no1=Integer.parseInt(number1);
int no2=Integer.parseInt(number2);

int sum=no1+no2;

String result=String.valueOf(sum);

request.setAttribute("result",result);

RequestDispatcherrd=request.getRequestDispatcher("addTwoNumber.jsp");
rd.forward(request, response);

IMAGE REFERENCED IN THE VIDEO FOR EXPLAINING THE CONCEPTS.

43

You might also like